| 1 | 1 | new file mode 100644 |
| index 0000000..f692b12 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | |
| 2 | +plugin_netcheck | |
| 3 | +plugin_netcheck.exe | |
| 4 | +plugin_netcheck.musl | |
| 5 | +plugin_netcheck.arm64 | |
| 6 | +plugin_netcheck.macos-arm64 | |
| 7 | +plugin_netcheck.macos-x86_64 | |
| 8 | +bin/ | |
| 9 | + | |
| 10 | +# local scratch | |
| 11 | +*.tmp | |
| 12 | +*.log | |
| 13 | + | |
| 14 | +# python tooling | |
| 15 | +__pycache__/ | |
| 16 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..cc65982 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,79 @@ | ||
| 1 | +# plugin_netcheck - SCORPIOX BOT open-source network diagnostics for your node | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_netcheck | |
| 5 | +# make musl static musl x86_64 -> ./plugin_netcheck.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_netcheck.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_netcheck.exe | |
| 8 | +# make macos Apple clang -> ./plugin_netcheck (run this on macOS) | |
| 9 | +# make ui regenerate src/ui_html.h from src/ui.html | |
| 10 | +# make test build + run tests/run.sh | |
| 11 | +# make e2e build + run tests/e2e.py (Playwright) | |
| 12 | +# make clean | |
| 13 | +# | |
| 14 | +# The resolver deadline runs in a worker thread, so every POSIX leg links | |
| 15 | +# -lpthread (musl and macOS carry pthread inside libc). | |
| 16 | + | |
| 17 | +CC ?= cc | |
| 18 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src | |
| 19 | +MUSL_CC ?= musl-gcc | |
| 20 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 21 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 22 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 23 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 24 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | |
| 25 | +PTHREAD := -lpthread | |
| 26 | +SRC := src/plugin_netcheck.c | |
| 27 | +UI_SRC := src/ui.html | |
| 28 | +UI_HDR := src/ui_html.h | |
| 29 | +BIN := plugin_netcheck | |
| 30 | +EXE := plugin_netcheck.exe | |
| 31 | + | |
| 32 | +.PHONY: all native musl arm64 win64 macos ui test e2e clean help | |
| 33 | + | |
| 34 | +all: native | |
| 35 | + | |
| 36 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | |
| 37 | + @echo "==> regenerating $(UI_HDR)" | |
| 38 | + python3 tools/gen_ui.py | |
| 39 | + | |
| 40 | +ui: $(UI_HDR) | |
| 41 | + | |
| 42 | +native: $(BIN) | |
| 43 | + | |
| 44 | +$(BIN): $(SRC) $(UI_HDR) | |
| 45 | + @echo "==> native build ($(CC))" | |
| 46 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(PTHREAD) | |
| 47 | + | |
| 48 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 49 | +musl: $(SRC) $(UI_HDR) | |
| 50 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 51 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) $(PTHREAD) | |
| 52 | + | |
| 53 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 54 | +arm64: $(SRC) $(UI_HDR) | |
| 55 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 56 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) $(PTHREAD) | |
| 57 | + | |
| 58 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 59 | +win64: $(SRC) $(UI_HDR) | |
| 60 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 61 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) -lws2_32 -liphlpapi | |
| 62 | + | |
| 63 | +# Apple clang build (run this on macOS) | |
| 64 | +macos: $(SRC) $(UI_HDR) | |
| 65 | + @echo "==> Apple clang build" | |
| 66 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(PTHREAD) | |
| 67 | + | |
| 68 | +test: native | |
| 69 | + @sh tests/run.sh | |
| 70 | + | |
| 71 | +e2e: native | |
| 72 | + @python3 tests/e2e.py | |
| 73 | + | |
| 74 | +clean: | |
| 75 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 76 | + rm -rf bin | |
| 77 | + | |
| 78 | +help: | |
| 79 | + @echo "make | make musl | make arm64 | make win64 | make macos | make ui | make test | make e2e | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..5967b4b | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +# netcheck — Network Diagnostics From This Node | |
| 2 | + | |
| 3 | +**Binary:** `plugin_netcheck` · **Slug:** `netcheck` · **Category:** `network` · **License:** MIT | |
| 4 | + | |
| 5 | +A zero-dependency, single-binary SCORPIOX BOT plugin that runs network | |
| 6 | +diagnostics **on the node it is installed on** and shows the result in a dark / | |
| 7 | +light panel that looks like part of SCORPIOX BOT. | |
| 8 | + | |
| 9 | +| Action | Query | What it does | | |
| 10 | +|---|---|---| | |
| 11 | +| `ifaces` | `?action=ifaces` | Lists every interface with its address, netmask, broadcast, family and up/down state, plus the configured DNS servers. | | |
| 12 | +| `dns` | `?action=dns&host=example.com` | Resolves a name through the node's resolver with a 3 s deadline and reports every address. | | |
| 13 | +| `tcp` | `?action=tcp&host=example.com&port=443` | Three non-blocking connects, reported as samples plus min / avg / max. | | |
| 14 | +| `http` | `?action=http&url=http://example.com/` | One `HEAD` request over plain TCP. Status line and header count only — the body is never read and redirects are never followed. | | |
| 15 | +| `info` | `?action=info` | Plugin identity, the action list and the configured deadlines. | | |
| 16 | + | |
| 17 | +`GET` with no `action` serves the HTML panel. | |
| 18 | + | |
| 19 | +## Why this plugin | |
| 20 | + | |
| 21 | +When a node is unreachable from the bot, the useful question is never "is the | |
| 22 | +bot down" but "what does this node see": which interfaces are up, what the | |
| 23 | +resolver returns, whether a port is actually accepting, and whether a URL | |
| 24 | +answers. netcheck answers all four from inside the node, in one binary, with no | |
| 25 | +`curl`, no `dig`, no `ping`, no `ss`, and no TLS library. | |
| 26 | + | |
| 27 | +## The no-TLS contract | |
| 28 | + | |
| 29 | +There is no TLS library anywhere in the binary, so an `https://` target cannot | |
| 30 | +be handshaken. netcheck does the only thing it honestly can — a TCP connect to | |
| 31 | +port 443 — and reports `"tls":"not_checked"` with a note saying the handshake | |
| 32 | +was not attempted. It never pretends to have validated a certificate. | |
| 33 | + | |
| 34 | +## Security model | |
| 35 | + | |
| 36 | +netcheck is a node-owner's tool, and it is the plugin that *makes* connections, | |
| 37 | +so the surface is deliberately small: | |
| 38 | + | |
| 39 | +* **Node auth required.** Every action sits behind `require_node_auth()`, which | |
| 40 | + accepts `X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` and is a | |
| 41 | + no-op only when `BOT_PASSWORD` is unset. `--meta` stays unauthenticated so | |
| 42 | + discovery still works. An unauthenticated `curl` to `/plugin_netcheck` must | |
| 43 | + return **401**. | |
| 44 | +* **Host validation.** A typed host is accepted only as a DNS hostname label | |
| 45 | + sequence or a literal IPv4 / IPv6 address (`inet_pton`). Shell | |
| 46 | + metacharacters, slashes, spaces and punctuation are refused with 400. | |
| 47 | +* **Port validation.** 1–65535, digits only. | |
| 48 | +* **URL validation.** `http://` or `https://` only; the scheme, host, port, path | |
| 49 | + and query are parsed by hand, userinfo is stripped, and the path must begin | |
| 50 | + with `/`. | |
| 51 | +* **Hard deadlines.** 3 s for resolution, 3 s per connect, 2 s for the HTTP read. | |
| 52 | + A typed host cannot make the plugin hang. | |
| 53 | +* **Body never read.** The HTTP probe sends `HEAD` and stops reading at the end | |
| 54 | + of the header block, so a 50 GB page costs the same as a 1 KB one. | |
| 55 | +* **No redirects.** A 3xx is reported with `"redirect":"not_followed"`. | |
| 56 | +* **One request per call.** No retries on the HTTP path; the TCP path takes | |
| 57 | + exactly three samples of the same target. | |
| 58 | + | |
| 59 | +The trust notice on the card and in `plugin.json` says it plainly: this plugin | |
| 60 | +opens exactly the outbound connections **you** ask for. | |
| 61 | + | |
| 62 | +## Build | |
| 63 | + | |
| 64 | +``` | |
| 65 | +make native build -> ./plugin_netcheck | |
| 66 | +make musl static musl x86_64 -> ./plugin_netcheck.musl | |
| 67 | +make arm64 static aarch64 -> ./plugin_netcheck.arm64 | |
| 68 | +make win64 MinGW-w64 static -> ./plugin_netcheck.exe | |
| 69 | +make macos Apple clang -> ./plugin_netcheck (run on macOS) | |
| 70 | +make ui regenerate src/ui_html.h from src/ui.html | |
| 71 | +make test build + tests/run.sh | |
| 72 | +make e2e build + tests/e2e.py (Playwright) | |
| 73 | +make clean | |
| 74 | +``` | |
| 75 | + | |
| 76 | +On Windows use `powershell -ExecutionPolicy Bypass -File build.ps1`; it | |
| 77 | +regenerates the page header, compiles a static PE, and refuses to emit anything | |
| 78 | +that is not a real `MZ` executable. | |
| 79 | + | |
| 80 | +The resolver deadline runs in a worker thread, so every POSIX leg links | |
| 81 | +`-lpthread` (musl and macOS carry pthread inside libc). Windows links | |
| 82 | +`-lws2_32 -liphlpapi`. | |
| 83 | + | |
| 84 | +## The page | |
| 85 | + | |
| 86 | +`src/ui.html` is the readable source of the panel; `tools/gen_ui.py` compiles it | |
| 87 | +into `src/ui_html.h` with two control-byte placeholders that expand into the | |
| 88 | +bot's theme macros, so the page can never drift from the palette SCORPIOX BOT | |
| 89 | +actually uses. The theme is decided before first paint in the order | |
| 90 | +`?theme=` → `localStorage.bot_theme` → `prefers-color-scheme`, and the page | |
| 91 | +follows the bot's `sx-theme` postMessage without a reload. Its own toggle is | |
| 92 | +hidden under `?embed=1`. | |
| 93 | + | |
| 94 | +No `<script src=>`, no CDN, no emoji, no web fonts. The latency sparkline is a | |
| 95 | +hand-drawn SVG polyline built from the TCP samples in the page — no chart | |
| 96 | +library, no network request. | |
| 97 | + | |
| 98 | +## Tests | |
| 99 | + | |
| 100 | +`tests/run.sh` is fully offline: the resolver, the interface table and the | |
| 101 | +outbound connect are replaced by three environment hooks the plugin exposes for | |
| 102 | +exactly this purpose, and the TCP/HTTP legs talk to throwaway listeners started | |
| 103 | +by `tests/mockd.py` on `127.0.0.1`. | |
| 104 | + | |
| 105 | +``` | |
| 106 | +NETCHECK_MOCK_IFACES "lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,eth0|..." | |
| 107 | + name|address|netmask|broadcast|family|up | |
| 108 | +NETCHECK_MOCK_DNS "host=addr,addr;host2=addr" | |
| 109 | +NETCHECK_MOCK_TIMEOUT 1 -> every resolution reports a deadline miss | |
| 110 | +``` | |
| 111 | + | |
| 112 | +On a real node none of these are set, so the hooks are never consulted. | |
| 113 | + | |
| 114 | +`tests/e2e.py` drives the page with Playwright at 1440 / 1024 / 390 CSS pixels | |
| 115 | +in both themes and asserts there is no horizontal overflow and no console error. | |
| 116 | + | |
| 117 | +## Screenshots | |
| 118 | + | |
| 119 | +`docs/` holds the panel at 1440, 1024 and 390 px in dark and light. | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | +## Sibling plugins | |
| 124 | + | |
| 125 | +netcheck is part of the SCORPIOX BOT open-source plugin family published to | |
| 126 | +`https://dist.scorpiox.net/bot-plugins/` and mirrored to | |
| 127 | +`https://plugingit.scorpiox.net/`. See `release-dist.sh` for the six-target | |
| 128 | +release recipe (linux x86_64 glibc + musl, arm64 musl, macOS arm64 + x86_64, | |
| 129 | +Windows x86_64) plus `source.tar.gz`. |
| 1 | 1 | new file mode 100644 |
| index 0000000..fb88b76 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_netcheck | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_netcheck.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 | +# The link needs -lws2_32 and -liphlpapi: Winsock for getaddrinfo/connect and | |
| 10 | +# GetAdaptersAddresses for the interface table. | |
| 11 | + | |
| 12 | +$ErrorActionPreference = "Stop" | |
| 13 | +$ScriptDir = $PSScriptRoot | |
| 14 | +Push-Location $ScriptDir | |
| 15 | +try { | |
| 16 | + $Src = Join-Path $ScriptDir "src\plugin_netcheck.c" | |
| 17 | + $Out = Join-Path $ScriptDir "plugin_netcheck.exe" | |
| 18 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 19 | + | |
| 20 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 21 | + | |
| 22 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | |
| 23 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 24 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 25 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 26 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 27 | + $Cc = "gcc" | |
| 28 | + } else { | |
| 29 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 30 | + } | |
| 31 | + } | |
| 32 | + | |
| 33 | + # Regenerate the page header so the binary always matches src/ui.html. | |
| 34 | + if (Get-Command python -ErrorAction SilentlyContinue) { | |
| 35 | + python tools\gen_ui.py | |
| 36 | + } | |
| 37 | + | |
| 38 | + Write-Host "==> building plugin_netcheck.exe with $Cc" | |
| 39 | + & $Cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static ` | |
| 40 | + -o $Out $Src -lws2_32 -liphlpapi | |
| 41 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 42 | + | |
| 43 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 44 | + | |
| 45 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 46 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 47 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 48 | + throw "output is not a PE executable (missing MZ header)" | |
| 49 | + } | |
| 50 | + | |
| 51 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | |
| 52 | + Write-Host " smoke test: .\plugin_netcheck.exe --meta" | |
| 53 | +} finally { | |
| 54 | + Pop-Location | |
| 55 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..594033c |

| 1 | 1 | new file mode 100644 |
| index 0000000..49f2f54 |

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

| 1 | 1 | new file mode 100644 |
| index 0000000..8d82321 |

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

| 1 | 1 | new file mode 100644 |
| index 0000000..8427d88 |

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

| 1 | 1 | new file mode 100644 |
| index 0000000..3af4b31 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,26 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "netcheck", | |
| 3 | + "id": "plugin_netcheck", | |
| 4 | + "name": "netcheck", | |
| 5 | + "desc": "Net checks", | |
| 6 | + "title": "Network Diagnostics From This Node", | |
| 7 | + "summary": "Zero-dependency network diagnostics that run on the node itself: list the interfaces and their addresses, show the configured DNS servers, resolve a name, measure a TCP connect three times and report min/avg/max with a latency sparkline, and check a plain-HTTP URL for reachability with a single HEAD request that reads only the status line and headers. There is no TLS library in the binary, so an https target is checked as a TCP connect to 443 and reported as tls not_checked. Dark and light themes follow the bot, the layout stays fluid down to 390px and inside the Chat floating window, and nothing is written to disk.", | |
| 8 | + "category": "network", | |
| 9 | + "version": "1.0.0", | |
| 10 | + "license": "MIT", | |
| 11 | + "capabilities": [ | |
| 12 | + "outbound_tcp_user_requested", | |
| 13 | + "dns_resolve", | |
| 14 | + "iface_list" | |
| 15 | + ], | |
| 16 | + "trust_notice": "Executes native C code on your node. It reads the local interface table and the configured DNS servers, and it opens exactly the outbound connections you ask for: one DNS lookup, a TCP connect, or one HEAD request over plain HTTP. Response bodies are never read, redirects are never followed, hosts are validated as hostnames or IP literals, ports are limited to 1-65535, and every phase has a hard 3 second deadline. There is no TLS library, so an https URL is only checked for a TCP connect to 443. Every action requires node authentication.", | |
| 17 | + "author": "SCORPIOX INC", | |
| 18 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-netcheck", | |
| 19 | + "ldflags_posix": [ | |
| 20 | + "-lpthread" | |
| 21 | + ], | |
| 22 | + "ldflags_win64": [ | |
| 23 | + "-lws2_32", | |
| 24 | + "-liphlpapi" | |
| 25 | + ] | |
| 26 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..232f187 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh - build, scan and publish plugin_netcheck to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | +# ./release-dist.sh --standalone # use this script even if the CLI is installed | |
| 27 | +# # (needed for plugins that link extra Win32 libs, | |
| 28 | +# # which the CLI's fixed link line cannot express) | |
| 29 | + | |
| 30 | +set -euo pipefail | |
| 31 | + | |
| 32 | +SLUG="netcheck" | |
| 33 | +ID="plugin_netcheck" | |
| 34 | +VERSION="1.0.0" | |
| 35 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 36 | + | |
| 37 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 38 | +cd "$ROOT" | |
| 39 | + | |
| 40 | +DRY_RUN=0 | |
| 41 | +DO_MACOS=1 | |
| 42 | +DO_MIRROR=1 | |
| 43 | +STANDALONE=0 | |
| 44 | +for arg in "$@"; do | |
| 45 | + case "$arg" in | |
| 46 | + --standalone) STANDALONE=1 ;; | |
| 47 | + --dry-run) DRY_RUN=1 ;; | |
| 48 | + --no-macos) DO_MACOS=0 ;; | |
| 49 | + --no-mirror) DO_MIRROR=0 ;; | |
| 50 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | |
| 51 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 52 | + esac | |
| 53 | +done | |
| 54 | + | |
| 55 | +DIST_HOST="${DIST_HOST:-}" | |
| 56 | +DIST_PASS="${DIST_PASS:-}" | |
| 57 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 58 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 59 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 60 | + | |
| 61 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 62 | +mkdir -p "$STAGE" | |
| 63 | +trap 'rm -rf "$STAGE"' EXIT | |
| 64 | + | |
| 65 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 66 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 67 | + | |
| 68 | +# ---------------------------------------------------------------- 0. preflight | |
| 69 | +say "0/7 preflight" | |
| 70 | + | |
| 71 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 72 | + say "using scorpiox-cli-botplugin publish" | |
| 73 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 74 | +fi | |
| 75 | +echo " running the standalone pipeline" | |
| 76 | + | |
| 77 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 78 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 79 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 80 | +echo " version $VERSION" | |
| 81 | +echo " commit $COMMIT" | |
| 82 | + | |
| 83 | +# ---------------------------------------------------------------- 1. secret scan | |
| 84 | +say "1/7 secret & LAN scan (full history)" | |
| 85 | + | |
| 86 | +SCAN_TMP="$STAGE/history.txt" | |
| 87 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 88 | +# audit rather than the code: the committer identity line, and any line that is | |
| 89 | +# itself a scan definition - otherwise this file's own detector patterns (and the | |
| 90 | +# test suite's identical checks) read as findings in every historical revision of | |
| 91 | +# them. A real secret on any other line still hits. | |
| 92 | +git log -p --all 2>/dev/null \ | |
| 93 | + | grep -v '^Author: ' \ | |
| 94 | + | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \ | |
| 95 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 96 | +HITS=0 | |
| 97 | +scan() { # scan <label> <regex> | |
| 98 | + local out | |
| 99 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 100 | + if [ -n "$out" ]; then | |
| 101 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 102 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 103 | + HITS=$((HITS + 1)) | |
| 104 | + else | |
| 105 | + printf ' ok %s\n' "$1" | |
| 106 | + fi | |
| 107 | +} | |
| 108 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 109 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 110 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 111 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 112 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 113 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 114 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 115 | +P_ROOT="/codebases" | |
| 116 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 117 | +P_WT=".work""trees" | |
| 118 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 119 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 120 | +if [ "$HITS" -ne 0 ]; then | |
| 121 | + die "secret scan found $HITS problem(s) - refusing to publish" | |
| 122 | +fi | |
| 123 | +echo " clean: 0 hits" | |
| 124 | + | |
| 125 | +# ---------------------------------------------------------------- 2. build | |
| 126 | +say "2/7 build targets" | |
| 127 | + | |
| 128 | +# linux-x86_64 (glibc, native) | |
| 129 | +if command -v cc >/dev/null 2>&1; then | |
| 130 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c -lpthread || die "native build failed" | |
| 131 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 132 | +else | |
| 133 | + die "no native cc found" | |
| 134 | +fi | |
| 135 | + | |
| 136 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | |
| 137 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 138 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c -lpthread \ | |
| 139 | + || die "musl build failed" | |
| 140 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 141 | +else | |
| 142 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 143 | +fi | |
| 144 | + | |
| 145 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | |
| 146 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 147 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c -lpthread \ | |
| 148 | + || die "arm64 build failed" | |
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 150 | +else | |
| 151 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | |
| 152 | +fi | |
| 153 | + | |
| 154 | +# windows-x86_64 (static PE) | |
| 155 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 156 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \ | |
| 157 | + -I src -o "$STAGE/$ID.exe" src/$ID.c -lws2_32 -liphlpapi || die "MinGW build failed" | |
| 158 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 159 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 160 | +else | |
| 161 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 162 | +fi | |
| 163 | + | |
| 164 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | |
| 165 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 166 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 167 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 168 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 169 | + echo " building macOS legs on $MAC_HOST" | |
| 170 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 171 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 172 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 173 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 174 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 175 | + fi | |
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 177 | + tar -czf "$STAGE/src.tgz" src | |
| 178 | + if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \ | |
| 179 | + && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then | |
| 180 | + # Build straight from the uploaded file - no src/ tree on the remote. | |
| 181 | + for slice in arm64 x86_64; do | |
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c -lpthread" \ | |
| 184 | + 2>/dev/null; then | |
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 187 | + else | |
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 189 | + fi | |
| 190 | + done | |
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | |
| 192 | + else | |
| 193 | + echo " warn: could not upload source to $MAC_HOST" | |
| 194 | + fi | |
| 195 | + else | |
| 196 | + echo " warn: cannot reach macOS builder $MAC_HOST" | |
| 197 | + fi | |
| 198 | +else | |
| 199 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | |
| 200 | +fi | |
| 201 | + | |
| 202 | +# ---------------------------------------------------------------- 3. manifest | |
| 203 | +say "3/7 manifest + checksums" | |
| 204 | + | |
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 209 | + | |
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> | |
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" | |
| 212 | + [ -f "$file" ] || return 0 | |
| 213 | + local sha size | |
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 218 | +} | |
| 219 | + | |
| 220 | +{ | |
| 221 | + printf '{\n' | |
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 223 | + printf ' "id": "%s",\n' "$ID" | |
| 224 | + printf ' "name": "netcheck",\n' | |
| 225 | + printf ' "desc": "Net checks",\n' | |
| 226 | + printf ' "title": "Markdown Notes",\n' | |
| 227 | + printf ' "summary": "Zero-dependency network diagnostics that run on the node itself: list the interfaces and their addresses, show the configured DNS servers, resolve a name, measure a TCP connect three times and report min/avg/max with a latency sparkline, and check a plain-HTTP URL for reachability with a single HEAD request that reads only the status line and headers. There is no TLS library in the binary, so an https target is checked as a TCP connect to 443 and reported as tls not_checked. Dark and light themes follow the bot, the layout stays fluid down to 390px and inside the Chat floating window, and nothing is written to disk.",\n' | |
| 228 | + printf ' "category": "network",\n' | |
| 229 | + printf ' "version": "%s",\n' "$VERSION" | |
| 230 | + printf ' "license": "MIT",\n' | |
| 231 | + printf ' "trust_notice": "Executes native C code on your node. It reads the local interface table and the configured DNS servers, and it opens exactly the outbound connections you ask for: one DNS lookup, a TCP connect, or one HEAD request over plain HTTP. Response bodies are never read, redirects are never followed, hosts are validated as hostnames or IP literals, ports are limited to 1-65535, and every phase has a hard 3 second deadline. There is no TLS library, so an https URL is only checked for a TCP connect to 443. Every action requires node authentication.",\n' | |
| 232 | + printf ' "capabilities": ["outbound_tcp_user_requested", "dns_resolve", "iface_list"],\n' | |
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 241 | + printf ' "targets": {\n' | |
| 242 | + first=1 | |
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | |
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | |
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | |
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | |
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | |
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | |
| 250 | + printf '\n }\n}\n' | |
| 251 | +} > "$STAGE/manifest.json" | |
| 252 | + | |
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 254 | + || die "generated manifest.json is not valid JSON" | |
| 255 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | |
| 256 | + | |
| 257 | +# SHA256SUMS - relative paths, exactly as published | |
| 258 | +( cd "$STAGE" | |
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 266 | + true ) > "$STAGE/SHA256SUMS" | |
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 268 | + | |
| 269 | +# ---------------------------------------------------------------- 4. stage | |
| 270 | +say "4/7 stage tree" | |
| 271 | +PKG="$STAGE/pkg" | |
| 272 | +mkdir -p "$PKG" | |
| 273 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 274 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | |
| 275 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | |
| 276 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | |
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | |
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | |
| 279 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | |
| 280 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | |
| 281 | + | |
| 282 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 283 | + say "dry run - leaving the staging tree in $PKG" | |
| 284 | + trap - EXIT | |
| 285 | + exit 0 | |
| 286 | +fi | |
| 287 | + | |
| 288 | +# ---------------------------------------------------------------- 5. upload | |
| 289 | +say "5/7 upload to the dist server" | |
| 290 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | |
| 291 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 292 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 293 | +if [ -n "$DIST_PASS" ]; then | |
| 294 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 295 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 296 | +fi | |
| 297 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 298 | + | |
| 299 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 300 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 301 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 302 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 303 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 304 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 305 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 306 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 307 | + || die "remote extract failed" | |
| 308 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 309 | + | |
| 310 | +# latest.json = copy of this version's manifest | |
| 311 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 312 | + || die "latest.json update failed" | |
| 313 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 314 | + | |
| 315 | +# index.json - merge, preserving every sibling <slug>/latest.json | |
| 316 | +say "index.json merge" | |
| 317 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 318 | +import json, os, sys, glob | |
| 319 | +slug = sys.argv[1] | |
| 320 | +entries = {} | |
| 321 | +for p in sorted(glob.glob('*/latest.json')): | |
| 322 | + s = os.path.dirname(p) | |
| 323 | + try: | |
| 324 | + entries[s] = json.load(open(p)) | |
| 325 | + except Exception: | |
| 326 | + pass | |
| 327 | +index = { | |
| 328 | + 'ok': True, | |
| 329 | + 'service': 'bot-plugins-dist', | |
| 330 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 331 | + 'count': len(entries), | |
| 332 | + 'slugs': sorted(entries), | |
| 333 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 334 | +} | |
| 335 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 336 | +os.replace('index.json.tmp', 'index.json') | |
| 337 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 338 | +PY" || die "index.json merge failed" | |
| 339 | + | |
| 340 | +# ---------------------------------------------------------------- 6. mirror | |
| 341 | +say "6/7 plugingit mirror" | |
| 342 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 343 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 344 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | |
| 345 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 346 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 347 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 348 | +else | |
| 349 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 350 | +fi | |
| 351 | + | |
| 352 | +# ---------------------------------------------------------------- 7. verify | |
| 353 | +say "7/7 verify" | |
| 354 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 355 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 356 | +if [ "$CODE" = "200" ]; then | |
| 357 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 358 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 359 | +else | |
| 360 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 361 | +fi | |
| 362 | + | |
| 363 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 364 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 365 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..6d0d630 | ||
| --- /dev/null | ||
| +++ b/src/plugin_netcheck.c | ||
| @@ -0,0 +1,1608 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_netcheck - SCORPIOX BOT open-source network diagnostics from this node | |
| 3 | + * | |
| 4 | + * A single clean-room C99 binary that serves THREE modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | |
| 6 | + * 2. ?action=ifaces | dns&host= | tcp&host=&port= | http&url= | info -> JSON node API | |
| 7 | + * 3. GET (default) -> responsive HTML diagnostics UI | |
| 8 | + * | |
| 9 | + * Everything it reports is about the node it runs on: the interfaces and their | |
| 10 | + * addresses, the configured DNS servers, a name resolution, a TCP connect | |
| 11 | + * latency, and a plain-HTTP reachability check (status line and headers only, | |
| 12 | + * body never read). The only outbound connections are the ones the node owner | |
| 13 | + * asks for by typing a host into the box, and every one of them sits behind | |
| 14 | + * node authentication, so the plugin is not a blind SSRF pivot. | |
| 15 | + * | |
| 16 | + * Interfaces come from getifaddrs(3) on Linux/macOS and from | |
| 17 | + * GetAdaptersAddresses on Windows. DNS uses getaddrinfo guarded by a deadline | |
| 18 | + * (a worker thread, because the resolver itself is blocking). TCP latency is | |
| 19 | + * the mean of three non-blocking connect() round trips. HTTP is a raw HEAD | |
| 20 | + * request over TCP - there is no TLS library anywhere in this binary, so an | |
| 21 | + * https:// target is reported as a TCP connect to port 443 with | |
| 22 | + * "tls":"not_checked". | |
| 23 | + * | |
| 24 | + * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang | |
| 25 | + * and x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 26 | + * scorpiox-server on the node. | |
| 27 | + * | |
| 28 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 29 | + */ | |
| 30 | + | |
| 31 | +/* Must come before every include: iphlpapi.h and ws2tcpip.h gate | |
| 32 | + * GetAdaptersAddresses and the IPv6 helpers on it, and MinGW defaults to 0x502 | |
| 33 | + * (Server 2003) which hides all of them. */ | |
| 34 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 35 | +# define _WIN32_WINNT 0x0601 | |
| 36 | +#endif | |
| 37 | + | |
| 38 | +#if !defined(_WIN32) | |
| 39 | +# define _POSIX_C_SOURCE 200809L | |
| 40 | +# define _DEFAULT_SOURCE 1 | |
| 41 | +# if defined(__APPLE__) | |
| 42 | +# define _DARWIN_C_SOURCE 1 | |
| 43 | +# endif | |
| 44 | +#endif | |
| 45 | + | |
| 46 | +#include <stdio.h> | |
| 47 | +#include <stdlib.h> | |
| 48 | +#include <string.h> | |
| 49 | +#include <ctype.h> | |
| 50 | +#include <errno.h> | |
| 51 | +#include <time.h> | |
| 52 | + | |
| 53 | +#if defined(_WIN32) | |
| 54 | +# define WIN32_LEAN_AND_MEAN | |
| 55 | +# include <winsock2.h> | |
| 56 | +# include <ws2tcpip.h> | |
| 57 | +# include <windows.h> | |
| 58 | +# include <iphlpapi.h> | |
| 59 | +# define sx_popen _popen | |
| 60 | +# define sx_pclose _pclose | |
| 61 | +# define sx_close_socket closesocket | |
| 62 | +# define SX_SOCK_T SOCKET | |
| 63 | +# define SX_SOCK_INVALID INVALID_SOCKET | |
| 64 | +#else | |
| 65 | +# include <unistd.h> | |
| 66 | +# include <ifaddrs.h> | |
| 67 | +# include <net/if.h> | |
| 68 | +# include <netdb.h> | |
| 69 | +# include <sys/types.h> | |
| 70 | +# include <sys/socket.h> | |
| 71 | +# include <sys/select.h> | |
| 72 | +# include <sys/time.h> | |
| 73 | +# include <netinet/in.h> | |
| 74 | +# include <arpa/inet.h> | |
| 75 | +# include <fcntl.h> | |
| 76 | +# include <pthread.h> | |
| 77 | +# define sx_popen popen | |
| 78 | +# define sx_pclose pclose | |
| 79 | +# define sx_close_socket close | |
| 80 | +# define SX_SOCK_T int | |
| 81 | +# define SX_SOCK_INVALID (-1) | |
| 82 | +#endif | |
| 83 | + | |
| 84 | +#include "bot_theme_plugin.h" | |
| 85 | +#include "ui_html.h" | |
| 86 | + | |
| 87 | +#define PLUGIN_SLUG "netcheck" | |
| 88 | +#define PLUGIN_ID "plugin_netcheck" | |
| 89 | +#define PLUGIN_VER "1.0.0" | |
| 90 | + | |
| 91 | +#define MAX_IFACES 128 | |
| 92 | +#define MAX_LINE 1024 | |
| 93 | +#define MAX_HOST 256 | |
| 94 | +#define MAX_PATHZ 256 | |
| 95 | +#define MAX_SAMPLES 3 | |
| 96 | +#define MAX_RES 16 | |
| 97 | + | |
| 98 | +/* Hard ceilings so a typed host cannot make the plugin hang forever. Each | |
| 99 | + * phase (resolve, connect, read) gets its own budget. */ | |
| 100 | +#define DNS_MS 3000 | |
| 101 | +#define TCP_MS 3000 | |
| 102 | +#define READ_MS 2000 | |
| 103 | + | |
| 104 | +/* ------------------------------------------------------------------ */ | |
| 105 | +/* Small utilities */ | |
| 106 | +/* ------------------------------------------------------------------ */ | |
| 107 | + | |
| 108 | +static void url_decode(char *s) | |
| 109 | +{ | |
| 110 | + char *o = s; | |
| 111 | + if (!s) return; | |
| 112 | + while (*s) { | |
| 113 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 114 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 115 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 116 | + *o++ = (char)((hi << 4) | lo); | |
| 117 | + s += 3; | |
| 118 | + } else if (*s == '+') { | |
| 119 | + *o++ = ' '; | |
| 120 | + s++; | |
| 121 | + } else { | |
| 122 | + *o++ = *s++; | |
| 123 | + } | |
| 124 | + } | |
| 125 | + *o = '\0'; | |
| 126 | +} | |
| 127 | + | |
| 128 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 129 | +{ | |
| 130 | + size_t klen; | |
| 131 | + const char *p; | |
| 132 | + | |
| 133 | + if (!out || outsz == 0) return 0; | |
| 134 | + out[0] = '\0'; | |
| 135 | + if (!qs) return 0; | |
| 136 | + klen = strlen(key); | |
| 137 | + p = qs; | |
| 138 | + while (*p) { | |
| 139 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 140 | + const char *v = p + klen + 1; | |
| 141 | + size_t i = 0; | |
| 142 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 143 | + out[i++] = *v++; | |
| 144 | + out[i] = '\0'; | |
| 145 | + url_decode(out); | |
| 146 | + return 1; | |
| 147 | + } | |
| 148 | + p = strchr(p, '&'); | |
| 149 | + if (!p) break; | |
| 150 | + p++; | |
| 151 | + } | |
| 152 | + return 0; | |
| 153 | +} | |
| 154 | + | |
| 155 | +static void json_str(const char *s) | |
| 156 | +{ | |
| 157 | + putchar('"'); | |
| 158 | + for (; s && *s; s++) { | |
| 159 | + unsigned char c = (unsigned char)*s; | |
| 160 | + switch (c) { | |
| 161 | + case '"': fputs("\\\"", stdout); break; | |
| 162 | + case '\\': fputs("\\\\", stdout); break; | |
| 163 | + case '\n': fputs("\\n", stdout); break; | |
| 164 | + case '\r': fputs("\\r", stdout); break; | |
| 165 | + case '\t': fputs("\\t", stdout); break; | |
| 166 | + default: | |
| 167 | + if (c < 0x20) printf("\\u%04x", c); | |
| 168 | + else putchar(c); | |
| 169 | + } | |
| 170 | + } | |
| 171 | + putchar('"'); | |
| 172 | +} | |
| 173 | + | |
| 174 | +static void str_copy(char *dst, size_t sz, const char *src) | |
| 175 | +{ | |
| 176 | + size_t n; | |
| 177 | + if (!dst || sz == 0) return; | |
| 178 | + if (!src) { dst[0] = '\0'; return; } | |
| 179 | + n = strlen(src); | |
| 180 | + if (n >= sz) n = sz - 1; | |
| 181 | + memcpy(dst, src, n); | |
| 182 | + dst[n] = '\0'; | |
| 183 | +} | |
| 184 | + | |
| 185 | +static void str_trim(char *s) | |
| 186 | +{ | |
| 187 | + char *p; | |
| 188 | + size_t n; | |
| 189 | + if (!s) return; | |
| 190 | + p = s; | |
| 191 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 192 | + if (p != s) memmove(s, p, strlen(p) + 1); | |
| 193 | + n = strlen(s); | |
| 194 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | |
| 195 | +} | |
| 196 | + | |
| 197 | +static void str_lower(char *s) | |
| 198 | +{ | |
| 199 | + for (; s && *s; s++) *s = (char)tolower((unsigned char)*s); | |
| 200 | +} | |
| 201 | + | |
| 202 | +static long long now_ms(void) | |
| 203 | +{ | |
| 204 | +#if defined(_WIN32) | |
| 205 | + FILETIME ft; | |
| 206 | + ULARGE_INTEGER u; | |
| 207 | + GetSystemTimeAsFileTime(&ft); | |
| 208 | + u.LowPart = ft.dwLowDateTime; | |
| 209 | + u.HighPart = ft.dwHighDateTime; | |
| 210 | + return (long long)(u.QuadPart / 10000ULL); | |
| 211 | +#else | |
| 212 | + struct timeval tv; | |
| 213 | + gettimeofday(&tv, NULL); | |
| 214 | + return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); | |
| 215 | +#endif | |
| 216 | +} | |
| 217 | + | |
| 218 | +static void utc_stamp(time_t t, char *buf, size_t sz) | |
| 219 | +{ | |
| 220 | + struct tm tmv; | |
| 221 | +#if defined(_WIN32) | |
| 222 | + gmtime_s(&tmv, &t); | |
| 223 | +#else | |
| 224 | + gmtime_r(&t, &tmv); | |
| 225 | +#endif | |
| 226 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | |
| 227 | +} | |
| 228 | + | |
| 229 | +/* ------------------------------------------------------------------ */ | |
| 230 | +/* Node authentication */ | |
| 231 | +/* ------------------------------------------------------------------ */ | |
| 232 | + | |
| 233 | +static void require_node_auth(void) | |
| 234 | +{ | |
| 235 | + const char *np = getenv("BOT_PASSWORD"); | |
| 236 | + const char *xp; | |
| 237 | + const char *auth; | |
| 238 | + const char *qs; | |
| 239 | + char qpwd[256]; | |
| 240 | + | |
| 241 | + if (!np || !*np) return; | |
| 242 | + | |
| 243 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 244 | + if (xp && strcmp(xp, np) == 0) return; | |
| 245 | + | |
| 246 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 247 | + if (auth) { | |
| 248 | + while (*auth == ' ') auth++; | |
| 249 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 250 | + auth += 7; | |
| 251 | + while (*auth == ' ') auth++; | |
| 252 | + if (strcmp(auth, np) == 0) return; | |
| 253 | + } | |
| 254 | + } | |
| 255 | + | |
| 256 | + qs = getenv("QUERY_STRING"); | |
| 257 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 258 | + return; | |
| 259 | + | |
| 260 | + fputs("Status: 401 Unauthorized\r\n" | |
| 261 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 262 | + "Cache-Control: no-store\r\n" | |
| 263 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 264 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 265 | + exit(0); | |
| 266 | +} | |
| 267 | + | |
| 268 | +/* ------------------------------------------------------------------ */ | |
| 269 | +/* Address formatting */ | |
| 270 | +/* ------------------------------------------------------------------ */ | |
| 271 | + | |
| 272 | +/* Render a sockaddr into a printable address string. Returns the family | |
| 273 | + * (AF_INET / AF_INET6) or 0 when the address cannot be rendered. */ | |
| 274 | +static int addr_text(const struct sockaddr *sa, char *out, size_t outsz) | |
| 275 | +{ | |
| 276 | + if (!sa || !out || outsz == 0) return 0; | |
| 277 | + out[0] = '\0'; | |
| 278 | + | |
| 279 | + switch (sa->sa_family) { | |
| 280 | + case AF_INET: { | |
| 281 | + const struct sockaddr_in *in = (const struct sockaddr_in *)sa; | |
| 282 | + if (inet_ntop(AF_INET, &in->sin_addr, out, (unsigned int)outsz)) | |
| 283 | + return AF_INET; | |
| 284 | + return 0; | |
| 285 | + } | |
| 286 | + case AF_INET6: { | |
| 287 | + const struct sockaddr_in6 *in6 = (const struct sockaddr_in6 *)sa; | |
| 288 | + if (inet_ntop(AF_INET6, &in6->sin6_addr, out, (unsigned int)outsz)) | |
| 289 | + return AF_INET6; | |
| 290 | + return 0; | |
| 291 | + } | |
| 292 | + default: | |
| 293 | + return 0; | |
| 294 | + } | |
| 295 | +} | |
| 296 | + | |
| 297 | +static int netmask_text(const struct sockaddr *sa, char *out, size_t outsz) | |
| 298 | +{ | |
| 299 | + if (!sa || sa->sa_family != AF_INET || !out || outsz == 0) return 0; | |
| 300 | + return inet_ntop(AF_INET, | |
| 301 | + &((const struct sockaddr_in *)sa)->sin_addr, | |
| 302 | + out, (unsigned int)outsz) ? 1 : 0; | |
| 303 | +} | |
| 304 | + | |
| 305 | +/* ------------------------------------------------------------------ */ | |
| 306 | +/* Interface collection */ | |
| 307 | +/* ------------------------------------------------------------------ */ | |
| 308 | +typedef struct { | |
| 309 | + char name[64]; | |
| 310 | + char addr[64]; | |
| 311 | + char mask[64]; | |
| 312 | + char broad[64]; | |
| 313 | + int family; /* 4 or 6 */ | |
| 314 | + int loopback; | |
| 315 | + int up; | |
| 316 | + int running; | |
| 317 | +} iface_t; | |
| 318 | + | |
| 319 | +static iface_t g_ifaces[MAX_IFACES]; | |
| 320 | +static int g_iface_count; | |
| 321 | + | |
| 322 | +static int is_loopback_text(const char *a) | |
| 323 | +{ | |
| 324 | + if (!a) return 0; | |
| 325 | + if (strncmp(a, "127.", 4) == 0) return 1; | |
| 326 | + if (strcmp(a, "::1") == 0) return 1; | |
| 327 | + return 0; | |
| 328 | +} | |
| 329 | + | |
| 330 | +static void iface_add(const char *name, const struct sockaddr *sa, | |
| 331 | + const struct sockaddr *mask, const struct sockaddr *broad, | |
| 332 | + int up, int running) | |
| 333 | +{ | |
| 334 | + iface_t *f; | |
| 335 | + char a[64]; | |
| 336 | + int fam; | |
| 337 | + | |
| 338 | + if (g_iface_count >= MAX_IFACES) return; | |
| 339 | + fam = addr_text(sa, a, sizeof a); | |
| 340 | + if (!fam) return; | |
| 341 | + | |
| 342 | + f = &g_ifaces[g_iface_count++]; | |
| 343 | + memset(f, 0, sizeof *f); | |
| 344 | + str_copy(f->name, sizeof f->name, name ? name : "?"); | |
| 345 | + str_copy(f->addr, sizeof f->addr, a); | |
| 346 | + f->family = (fam == AF_INET6) ? 6 : 4; | |
| 347 | + f->loopback = is_loopback_text(f->addr); | |
| 348 | + f->up = up; | |
| 349 | + f->running = running; | |
| 350 | + if (mask) netmask_text(mask, f->mask, sizeof f->mask); | |
| 351 | + if (broad) addr_text(broad, f->broad, sizeof f->broad); | |
| 352 | +} | |
| 353 | + | |
| 354 | +#if defined(_WIN32) | |
| 355 | +/* ASCII-fold a wide adapter name; Windows adapter names are alphanumeric with | |
| 356 | + * spaces, dashes and dots, so a byte-per-wchar fold is lossless in practice. */ | |
| 357 | +static void wide_to_ascii(const wchar_t *w, char *out, size_t outsz) | |
| 358 | +{ | |
| 359 | + size_t i = 0; | |
| 360 | + if (outsz) out[0] = '\0'; | |
| 361 | + if (!w || !out || outsz == 0) return; | |
| 362 | + for (i = 0; i + 1 < outsz && w[i]; i++) | |
| 363 | + out[i] = (char)((unsigned char)w[i]); | |
| 364 | + out[i] = '\0'; | |
| 365 | +} | |
| 366 | + | |
| 367 | +static PIP_ADAPTER_ADDRESSES fetch_adapters(ULONG flags) | |
| 368 | +{ | |
| 369 | + ULONG want = 0; | |
| 370 | + ULONG rc; | |
| 371 | + PIP_ADAPTER_ADDRESSES adapters; | |
| 372 | + | |
| 373 | + rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &want); | |
| 374 | + if (rc != ERROR_SUCCESS && rc != ERROR_BUFFER_OVERFLOW) return NULL; | |
| 375 | + if (want < 2048) want = 2048; | |
| 376 | + adapters = (PIP_ADAPTER_ADDRESSES)malloc(want + 1024); | |
| 377 | + if (!adapters) return NULL; | |
| 378 | + rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapters, &want); | |
| 379 | + if (rc != ERROR_SUCCESS) { free(adapters); return NULL; } | |
| 380 | + return adapters; | |
| 381 | +} | |
| 382 | + | |
| 383 | +static void collect_ifaces_windows(void) | |
| 384 | +{ | |
| 385 | + PIP_ADAPTER_ADDRESSES adapters; | |
| 386 | + PIP_ADAPTER_ADDRESSES a; | |
| 387 | + PIP_ADAPTER_UNICAST_ADDRESS u; | |
| 388 | + | |
| 389 | + adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX | | |
| 390 | + GAA_FLAG_SKIP_ANYCAST | | |
| 391 | + GAA_FLAG_SKIP_MULTICAST | | |
| 392 | + GAA_FLAG_SKIP_DNS_SERVER); | |
| 393 | + if (!adapters) return; | |
| 394 | + | |
| 395 | + for (a = adapters; a; a = a->Next) { | |
| 396 | + char ascii[64]; | |
| 397 | + const wchar_t *friendly = a->FriendlyName ? a->FriendlyName : NULL; | |
| 398 | + int up = (a->OperStatus == MIF_OPER_UP); | |
| 399 | + | |
| 400 | + if (friendly) wide_to_ascii(friendly, ascii, sizeof ascii); | |
| 401 | + else if (a->AdapterName) str_copy(ascii, sizeof ascii, a->AdapterName); | |
| 402 | + else str_copy(ascii, sizeof ascii, "adapter"); | |
| 403 | + | |
| 404 | + for (u = a->FirstUnicastAddress; u; u = u->Next) { | |
| 405 | + struct sockaddr_storage nm; | |
| 406 | + struct sockaddr *nmp = NULL; | |
| 407 | + | |
| 408 | + /* OnLinkPrefixLength is a CIDR length, not a dotted mask. Expand it | |
| 409 | + * into a dotted netmask so the table has something familiar to show. */ | |
| 410 | + memset(&nm, 0, sizeof nm); | |
| 411 | + if (u->Address.sa_family == AF_INET && u->OnLinkPrefixLength < 32) { | |
| 412 | + struct sockaddr_in *in4 = (struct sockaddr_in *)&nm; | |
| 413 | + in4->sin_family = AF_INET; | |
| 414 | + in4->sin_addr.s_addr = | |
| 415 | + htonl(0xFFFFFFFFUL << (32 - u->OnLinkPrefixLength)); | |
| 416 | + nmp = (struct sockaddr *)in4; | |
| 417 | + } | |
| 418 | + iface_add(ascii, (const struct sockaddr *)&u->Address, nmp, NULL, | |
| 419 | + up, up); | |
| 420 | + } | |
| 421 | + } | |
| 422 | + free(adapters); | |
| 423 | +} | |
| 424 | +#else | |
| 425 | +static void collect_ifaces_posix(void) | |
| 426 | +{ | |
| 427 | + struct ifaddrs *list = NULL; | |
| 428 | + struct ifaddrs *i; | |
| 429 | + | |
| 430 | + if (getifaddrs(&list) != 0 || !list) return; | |
| 431 | + for (i = list; i; i = i->ifa_next) { | |
| 432 | + int up, running; | |
| 433 | + | |
| 434 | + if (!i->ifa_addr) continue; | |
| 435 | + up = (i->ifa_flags & IFF_UP) != 0; | |
| 436 | + running = (i->ifa_flags & IFF_RUNNING) != 0; | |
| 437 | + iface_add(i->ifa_name, i->ifa_addr, i->ifa_netmask, i->ifa_broadaddr, | |
| 438 | + up, running); | |
| 439 | + } | |
| 440 | + freeifaddrs(list); | |
| 441 | +} | |
| 442 | +#endif | |
| 443 | + | |
| 444 | + | |
| 445 | +/* ------------------------------------------------------------------ */ | |
| 446 | +/* Host validation */ | |
| 447 | +/* ------------------------------------------------------------------ */ | |
| 448 | + | |
| 449 | +/* A host is accepted only as a DNS hostname label sequence or a literal IPv4 / | |
| 450 | + * IPv6 address. That keeps typed input from smuggling a URL, a path, or a | |
| 451 | + * shell metacharacter into anything we do with it. */ | |
| 452 | +static int valid_hostname(const char *s) | |
| 453 | +{ | |
| 454 | + size_t i, n = strlen(s); | |
| 455 | + | |
| 456 | + if (n == 0 || n > 253) return 0; | |
| 457 | + if (s[0] == '.' || s[n - 1] == '.') return 0; | |
| 458 | + for (i = 0; i < n; i++) { | |
| 459 | + unsigned char c = (unsigned char)s[i]; | |
| 460 | + if (c == '.') { | |
| 461 | + if (i == 0 || s[i - 1] == '.') return 0; | |
| 462 | + continue; | |
| 463 | + } | |
| 464 | + if (!isalnum(c) && c != '-' && c != '_') return 0; | |
| 465 | + } | |
| 466 | + return 1; | |
| 467 | +} | |
| 468 | + | |
| 469 | +static int looks_ipv4(const char *s) | |
| 470 | +{ | |
| 471 | + struct sockaddr_in in; | |
| 472 | + return inet_pton(AF_INET, s, &in.sin_addr) == 1; | |
| 473 | +} | |
| 474 | + | |
| 475 | +static int looks_ipv6(const char *s) | |
| 476 | +{ | |
| 477 | + struct sockaddr_in6 in6; | |
| 478 | + return inet_pton(AF_INET6, s, &in6.sin6_addr) == 1; | |
| 479 | +} | |
| 480 | + | |
| 481 | +static int valid_host(const char *s) | |
| 482 | +{ | |
| 483 | + if (!s || !*s) return 0; | |
| 484 | + if (looks_ipv4(s) || looks_ipv6(s)) return 1; | |
| 485 | + return valid_hostname(s); | |
| 486 | +} | |
| 487 | + | |
| 488 | +/* ------------------------------------------------------------------ */ | |
| 489 | +/* Test hooks */ | |
| 490 | +/* ------------------------------------------------------------------ */ | |
| 491 | + | |
| 492 | +/* The offline suite needs deterministic, network-free answers, so three | |
| 493 | + * environment hooks exist. They are only consulted when the variable is set, | |
| 494 | + * which is never the case on a real node, and they let the suite exercise the | |
| 495 | + * timeout and the multi-address paths without a live resolver. | |
| 496 | + * | |
| 497 | + * NETCHECK_MOCK_IFACES "lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,eth0|..." | |
| 498 | + * name|address|netmask|broadcast|family|up | |
| 499 | + * NETCHECK_MOCK_DNS "host=addr,addr;host2=addr" (family inferred) | |
| 500 | + * NETCHECK_MOCK_TIMEOUT 1 -> every resolution reports a deadline miss | |
| 501 | + */ | |
| 502 | +static int mock_timeout_enabled(void) | |
| 503 | +{ | |
| 504 | + const char *v = getenv("NETCHECK_MOCK_TIMEOUT"); | |
| 505 | + return v && v[0] == '1'; | |
| 506 | +} | |
| 507 | + | |
| 508 | +/* Fill *res with a synthetic addrinfo chain for host. Returns 0 on success. */ | |
| 509 | +static int mock_resolve(const char *host, const char *port, struct addrinfo **res) | |
| 510 | +{ | |
| 511 | + const char *map = getenv("NETCHECK_MOCK_DNS"); | |
| 512 | + char entry[512]; | |
| 513 | + char addrs[512]; | |
| 514 | + size_t hl, el, i; | |
| 515 | + struct addrinfo *head = NULL, *tail = NULL; | |
| 516 | + int count = 0; | |
| 517 | + | |
| 518 | + int mock_port = 0; | |
| 519 | + | |
| 520 | + if (!map || !host) return -1; | |
| 521 | + if (port) { | |
| 522 | + long v = strtol(port, NULL, 10); | |
| 523 | + if (v >= 1 && v <= 65535) mock_port = (int)v; | |
| 524 | + } | |
| 525 | + hl = strlen(host); | |
| 526 | + | |
| 527 | + i = 0; | |
| 528 | + for (;;) { | |
| 529 | + size_t j = i; | |
| 530 | + char *eq; | |
| 531 | + size_t k, al; | |
| 532 | + struct addrinfo *ai; | |
| 533 | + | |
| 534 | + while (map[j] && map[j] != ';') j++; | |
| 535 | + el = j - i; | |
| 536 | + if (el > 0 && el < sizeof entry) { | |
| 537 | + memcpy(entry, map + i, el); | |
| 538 | + entry[el] = 0; | |
| 539 | + eq = strchr(entry, '='); | |
| 540 | + if (eq && (size_t)(eq - entry) == hl && strncmp(entry, host, hl) == 0) { | |
| 541 | + str_copy(addrs, sizeof addrs, eq + 1); | |
| 542 | + al = strlen(addrs); | |
| 543 | + k = 0; | |
| 544 | + while (k < al) { | |
| 545 | + char tok[128]; | |
| 546 | + size_t tl = 0; | |
| 547 | + struct sockaddr_in *in4; | |
| 548 | + struct sockaddr_in6 *in6; | |
| 549 | + | |
| 550 | + while (k < al && addrs[k] != ',') { | |
| 551 | + if (tl < sizeof tok - 1) tok[tl++] = addrs[k]; | |
| 552 | + k++; | |
| 553 | + } | |
| 554 | + tok[tl] = 0; | |
| 555 | + if (k < al) k++; /* skip the comma */ | |
| 556 | + while (tl > 0 && isspace((unsigned char)tok[tl - 1])) tok[--tl] = 0; | |
| 557 | + if (tl == 0) continue; | |
| 558 | + | |
| 559 | + ai = (struct addrinfo *)calloc(1, sizeof *ai); | |
| 560 | + if (!ai) return -2; | |
| 561 | + if (looks_ipv4(tok)) { | |
| 562 | + in4 = (struct sockaddr_in *)calloc(1, sizeof *in4); | |
| 563 | + if (!in4) { free(ai); return -2; } | |
| 564 | + in4->sin_family = AF_INET; | |
| 565 | + in4->sin_port = htons((unsigned short)mock_port); | |
| 566 | + inet_pton(AF_INET, tok, &in4->sin_addr); | |
| 567 | + ai->ai_family = AF_INET; | |
| 568 | + ai->ai_socktype = SOCK_STREAM; | |
| 569 | + ai->ai_addr = (struct sockaddr *)in4; | |
| 570 | + ai->ai_addrlen = sizeof *in4; | |
| 571 | + } else if (looks_ipv6(tok)) { | |
| 572 | + in6 = (struct sockaddr_in6 *)calloc(1, sizeof *in6); | |
| 573 | + if (!in6) { free(ai); return -2; } | |
| 574 | + in6->sin6_family = AF_INET6; | |
| 575 | + in6->sin6_port = htons((unsigned short)mock_port); | |
| 576 | + inet_pton(AF_INET6, tok, &in6->sin6_addr); | |
| 577 | + ai->ai_family = AF_INET6; | |
| 578 | + ai->ai_socktype = SOCK_STREAM; | |
| 579 | + ai->ai_addr = (struct sockaddr *)in6; | |
| 580 | + ai->ai_addrlen = sizeof *in6; | |
| 581 | + } else { | |
| 582 | + free(ai); | |
| 583 | + continue; | |
| 584 | + } | |
| 585 | + if (tail) tail->ai_next = ai; else head = ai; | |
| 586 | + tail = ai; | |
| 587 | + if (++count >= MAX_RES) break; | |
| 588 | + } | |
| 589 | + *res = head; | |
| 590 | + return 0; | |
| 591 | + } | |
| 592 | + } | |
| 593 | + if (map[j] == ';') { i = j + 1; continue; } | |
| 594 | + break; | |
| 595 | + } | |
| 596 | + return -1; | |
| 597 | +} | |
| 598 | + | |
| 599 | +/* Synthetic interface table for the offline suite. | |
| 600 | + * Format: name|address|netmask|broadcast|family|up (entries separated by ','). | |
| 601 | + * A pipe is used between fields because an IPv6 address is full of colons. */ | |
| 602 | +static int mock_ifaces(void) | |
| 603 | +{ | |
| 604 | + const char *spec = getenv("NETCHECK_MOCK_IFACES"); | |
| 605 | + char tok[256]; | |
| 606 | + char *parts[6]; | |
| 607 | + size_t i = 0, n; | |
| 608 | + | |
| 609 | + if (!spec) return 0; | |
| 610 | + n = strlen(spec); | |
| 611 | + i = 0; | |
| 612 | + while (i < n) { | |
| 613 | + size_t tl = 0, pi; | |
| 614 | + iface_t *f; | |
| 615 | + struct sockaddr_storage sa; | |
| 616 | + struct sockaddr_storage nm; | |
| 617 | + struct sockaddr *nmp = NULL; | |
| 618 | + char *pp; | |
| 619 | + int fam = 0; | |
| 620 | + | |
| 621 | + while (i < n && spec[i] != ',') { | |
| 622 | + if (tl < sizeof tok - 1) tok[tl++] = spec[i]; | |
| 623 | + i++; | |
| 624 | + } | |
| 625 | + tok[tl] = 0; | |
| 626 | + if (i < n) i++; /* skip the comma */ | |
| 627 | + if (tl == 0) continue; | |
| 628 | + | |
| 629 | + for (pi = 0; pi < 6; pi++) parts[pi] = (char *)""; | |
| 630 | + parts[0] = tok; | |
| 631 | + pi = 1; | |
| 632 | + pp = tok; | |
| 633 | + while (pp && pi < 6) { | |
| 634 | + char *nx = strchr(pp, '|'); | |
| 635 | + if (!nx) break; | |
| 636 | + *nx = 0; | |
| 637 | + parts[pi++] = nx + 1; | |
| 638 | + pp = nx + 1; | |
| 639 | + } | |
| 640 | + for (; pi < 6; pi++) parts[pi] = (char *)""; | |
| 641 | + | |
| 642 | + memset(&sa, 0, sizeof sa); | |
| 643 | + memset(&nm, 0, sizeof nm); | |
| 644 | + if (looks_ipv4(parts[1])) { | |
| 645 | + struct sockaddr_in *in4 = (struct sockaddr_in *)&sa; | |
| 646 | + in4->sin_family = AF_INET; | |
| 647 | + inet_pton(AF_INET, parts[1], &in4->sin_addr); | |
| 648 | + fam = 4; | |
| 649 | + if (parts[2][0] && looks_ipv4(parts[2])) { | |
| 650 | + struct sockaddr_in *m4 = (struct sockaddr_in *)&nm; | |
| 651 | + m4->sin_family = AF_INET; | |
| 652 | + inet_pton(AF_INET, parts[2], &m4->sin_addr); | |
| 653 | + nmp = (struct sockaddr *)m4; | |
| 654 | + } | |
| 655 | + } else if (looks_ipv6(parts[1])) { | |
| 656 | + struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&sa; | |
| 657 | + in6->sin6_family = AF_INET6; | |
| 658 | + inet_pton(AF_INET6, parts[1], &in6->sin6_addr); | |
| 659 | + fam = 6; | |
| 660 | + } else { | |
| 661 | + continue; | |
| 662 | + } | |
| 663 | + | |
| 664 | + if (g_iface_count >= MAX_IFACES) break; | |
| 665 | + f = &g_ifaces[g_iface_count++]; | |
| 666 | + memset(f, 0, sizeof *f); | |
| 667 | + str_copy(f->name, sizeof f->name, parts[0]); | |
| 668 | + str_copy(f->addr, sizeof f->addr, parts[1]); | |
| 669 | + f->family = fam; | |
| 670 | + f->loopback = is_loopback_text(f->addr); | |
| 671 | + f->up = parts[5][0] == '1'; | |
| 672 | + f->running = f->up; | |
| 673 | + if (nmp) netmask_text(nmp, f->mask, sizeof f->mask); | |
| 674 | + if (parts[3][0]) str_copy(f->broad, sizeof f->broad, parts[3]); | |
| 675 | + } | |
| 676 | + return 1; | |
| 677 | +} | |
| 678 | + | |
| 679 | + | |
| 680 | +static void collect_ifaces(void) | |
| 681 | +{ | |
| 682 | + g_iface_count = 0; | |
| 683 | + if (mock_ifaces()) return; | |
| 684 | +#if defined(_WIN32) | |
| 685 | + collect_ifaces_windows(); | |
| 686 | +#else | |
| 687 | + collect_ifaces_posix(); | |
| 688 | +#endif | |
| 689 | +} | |
| 690 | + | |
| 691 | +/* ------------------------------------------------------------------ */ | |
| 692 | +/* DNS server discovery */ | |
| 693 | +/* ------------------------------------------------------------------ */ | |
| 694 | + | |
| 695 | +#define MAX_NS 16 | |
| 696 | +static char g_ns[MAX_NS][64]; | |
| 697 | +static int g_ns_count; | |
| 698 | + | |
| 699 | +static void ns_add(const char *s) | |
| 700 | +{ | |
| 701 | + char buf[64]; | |
| 702 | + int i; | |
| 703 | + | |
| 704 | + if (!s) return; | |
| 705 | + str_copy(buf, sizeof buf, s); | |
| 706 | + str_trim(buf); | |
| 707 | + if (!buf[0]) return; | |
| 708 | + for (i = 0; i < g_ns_count; i++) | |
| 709 | + if (strcmp(g_ns[i], buf) == 0) return; | |
| 710 | + if (g_ns_count >= MAX_NS) return; | |
| 711 | + str_copy(g_ns[g_ns_count++], sizeof g_ns[0], buf); | |
| 712 | +} | |
| 713 | + | |
| 714 | +static void discover_nameservers(void) | |
| 715 | +{ | |
| 716 | + g_ns_count = 0; | |
| 717 | + | |
| 718 | +#if defined(_WIN32) | |
| 719 | + { | |
| 720 | + /* The interface query above deliberately skipped the DNS server list, | |
| 721 | + * so re-query with the flag left on rather than parsing a text tool. */ | |
| 722 | + PIP_ADAPTER_ADDRESSES adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX); | |
| 723 | + PIP_ADAPTER_ADDRESSES a; | |
| 724 | + PIP_ADAPTER_DNS_SERVER_ADDRESS_XP d; | |
| 725 | + | |
| 726 | + if (adapters) { | |
| 727 | + for (a = adapters; a; a = a->Next) | |
| 728 | + for (d = a->FirstDnsServerAddress; d; d = d->Next) { | |
| 729 | + char txt[64]; | |
| 730 | + if (addr_text((const struct sockaddr *)&d->Address, | |
| 731 | + txt, sizeof txt)) | |
| 732 | + ns_add(txt); | |
| 733 | + } | |
| 734 | + free(adapters); | |
| 735 | + } | |
| 736 | + } | |
| 737 | +#else | |
| 738 | + { | |
| 739 | + FILE *f = fopen("/etc/resolv.conf", "r"); | |
| 740 | + char line[MAX_LINE]; | |
| 741 | + if (f) { | |
| 742 | + while (fgets(line, sizeof line, f)) { | |
| 743 | + char *p = line; | |
| 744 | + if (*p == '#') continue; | |
| 745 | + if (strncmp(p, "nameserver", 10) == 0) { | |
| 746 | + p += 10; | |
| 747 | + while (*p == ' ' || *p == '\t') p++; | |
| 748 | + ns_add(p); | |
| 749 | + } | |
| 750 | + } | |
| 751 | + fclose(f); | |
| 752 | + } | |
| 753 | + } | |
| 754 | +#endif | |
| 755 | + | |
| 756 | +#if defined(__APPLE__) | |
| 757 | + /* macOS keeps /etc/resolv.conf as a symlink to a rotating stub; scutil is | |
| 758 | + * the authoritative source. Fixed argv - no user input reaches the shell. */ | |
| 759 | + { | |
| 760 | + FILE *f = sx_popen("/usr/bin/scutil --dns", "r"); | |
| 761 | + char line[MAX_LINE]; | |
| 762 | + if (f) { | |
| 763 | + while (fgets(line, sizeof line, f)) { | |
| 764 | + const char *p = strstr(line, "nameserver["); | |
| 765 | + char srv[64]; | |
| 766 | + size_t i = 0; | |
| 767 | + if (!p) continue; | |
| 768 | + p += 11; | |
| 769 | + while (*p && *p != ']' && i < sizeof srv - 1) srv[i++] = *p++; | |
| 770 | + srv[i] = '\0'; | |
| 771 | + str_trim(srv); | |
| 772 | + if (srv[0]) ns_add(srv); | |
| 773 | + } | |
| 774 | + sx_pclose(f); | |
| 775 | + } | |
| 776 | + } | |
| 777 | +#endif | |
| 778 | +} | |
| 779 | + | |
| 780 | +/* ------------------------------------------------------------------ */ | |
| 781 | +/* Deadline-guarded DNS */ | |
| 782 | +/* ------------------------------------------------------------------ */ | |
| 783 | + | |
| 784 | +/* getaddrinfo is blocking and has no timeout argument, so the deadline lives | |
| 785 | + * in a worker thread. On timeout the thread is left running: this process is a | |
| 786 | + * CGI child that exits as soon as the request is answered, so the leak is | |
| 787 | + * bounded by the request itself. */ | |
| 788 | +typedef struct { | |
| 789 | + const char *host; | |
| 790 | + const char *port; | |
| 791 | + struct addrinfo *res; | |
| 792 | + int rc; | |
| 793 | + int done; | |
| 794 | +} resolve_job; | |
| 795 | + | |
| 796 | +#if defined(_WIN32) | |
| 797 | +static DWORD WINAPI resolve_thread(LPVOID arg) | |
| 798 | +{ | |
| 799 | + resolve_job *j = (resolve_job *)arg; | |
| 800 | + struct addrinfo hints; | |
| 801 | + | |
| 802 | + memset(&hints, 0, sizeof hints); | |
| 803 | + hints.ai_family = AF_UNSPEC; | |
| 804 | + hints.ai_socktype = SOCK_STREAM; | |
| 805 | + j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); | |
| 806 | + j->done = 1; | |
| 807 | + return 0; | |
| 808 | +} | |
| 809 | + | |
| 810 | +static int resolve_with_deadline(const char *host, const char *port, | |
| 811 | + struct addrinfo **res, int timeout_ms) | |
| 812 | +{ | |
| 813 | + resolve_job job; | |
| 814 | + HANDLE th; | |
| 815 | + DWORD wait; | |
| 816 | + | |
| 817 | + if (mock_timeout_enabled()) return -1; | |
| 818 | + if (mock_resolve(host, port, res) == 0) return 0; | |
| 819 | + job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; | |
| 820 | + th = CreateThread(NULL, 0, resolve_thread, &job, 0, NULL); | |
| 821 | + if (!th) return -4; | |
| 822 | + wait = WaitForSingleObject(th, (DWORD)timeout_ms); | |
| 823 | + if (wait == WAIT_TIMEOUT) { CloseHandle(th); return -1; } | |
| 824 | + CloseHandle(th); | |
| 825 | + *res = job.res; | |
| 826 | + return job.rc; | |
| 827 | +} | |
| 828 | +#else | |
| 829 | +static void *resolve_thread(void *arg) | |
| 830 | +{ | |
| 831 | + resolve_job *j = (resolve_job *)arg; | |
| 832 | + struct addrinfo hints; | |
| 833 | + | |
| 834 | + memset(&hints, 0, sizeof hints); | |
| 835 | + hints.ai_family = AF_UNSPEC; | |
| 836 | + hints.ai_socktype = SOCK_STREAM; | |
| 837 | + j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); | |
| 838 | + j->done = 1; | |
| 839 | + return NULL; | |
| 840 | +} | |
| 841 | + | |
| 842 | +static int resolve_with_deadline(const char *host, const char *port, | |
| 843 | + struct addrinfo **res, int timeout_ms) | |
| 844 | +{ | |
| 845 | + resolve_job job; | |
| 846 | + pthread_t th; | |
| 847 | + long long deadline = now_ms() + timeout_ms; | |
| 848 | + | |
| 849 | + if (mock_timeout_enabled()) return -1; | |
| 850 | + if (mock_resolve(host, port, res) == 0) return 0; | |
| 851 | + job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; | |
| 852 | + if (pthread_create(&th, NULL, resolve_thread, &job) != 0) return -4; | |
| 853 | + while (!job.done) { | |
| 854 | + if (now_ms() >= deadline) return -1; /* thread keeps running; process exits soon */ | |
| 855 | + usleep(20000); | |
| 856 | + } | |
| 857 | + pthread_join(th, NULL); | |
| 858 | + *res = job.res; | |
| 859 | + return job.rc; | |
| 860 | +} | |
| 861 | +#endif | |
| 862 | + | |
| 863 | +/* ------------------------------------------------------------------ */ | |
| 864 | +/* TCP connect with a deadline */ | |
| 865 | +/* ------------------------------------------------------------------ */ | |
| 866 | + | |
| 867 | +/* Returns >=0 connect latency in ms, -1 timeout, -2 connect failed/refused, | |
| 868 | + * -3 resolution failed, -4 socket/thread failure. Writes the resolved address | |
| 869 | + * into addr_out when available. */ | |
| 870 | +static int tcp_connect_ms(const struct addrinfo *rp, int timeout_ms, | |
| 871 | + char *addr_out, size_t addr_sz) | |
| 872 | +{ | |
| 873 | + SX_SOCK_T s; | |
| 874 | + long long start; | |
| 875 | + int rc; | |
| 876 | + | |
| 877 | + if (addr_out && addr_sz) addr_out[0] = '\0'; | |
| 878 | + | |
| 879 | + s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
| 880 | + if (s == SX_SOCK_INVALID) return -4; | |
| 881 | + | |
| 882 | + /* Non-blocking so connect() returns immediately and select() enforces the | |
| 883 | + * deadline. A blocking connect on some stacks ignores the deadline. */ | |
| 884 | +#if defined(_WIN32) | |
| 885 | + { | |
| 886 | + u_long nb = 1; | |
| 887 | + ioctlsocket(s, FIONBIO, &nb); | |
| 888 | + } | |
| 889 | +#else | |
| 890 | + { | |
| 891 | + int fl = fcntl(s, F_GETFL, 0); | |
| 892 | + if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); | |
| 893 | + } | |
| 894 | +#endif | |
| 895 | + | |
| 896 | + start = now_ms(); | |
| 897 | + rc = connect(s, rp->ai_addr, rp->ai_addrlen); | |
| 898 | + if (rc != 0) { | |
| 899 | +#if defined(_WIN32) | |
| 900 | + int inprogress = (WSAGetLastError() == WSAEINPROGRESS || | |
| 901 | + WSAGetLastError() == WSAEWOULDBLOCK || | |
| 902 | + WSAGetLastError() == WSAEALREADY); | |
| 903 | +#else | |
| 904 | + int inprogress = (errno == EINPROGRESS || errno == EALREADY || | |
| 905 | + errno == EWOULDBLOCK); | |
| 906 | +#endif | |
| 907 | + if (!inprogress) { sx_close_socket(s); return -2; } | |
| 908 | + | |
| 909 | + { | |
| 910 | + fd_set wfds; | |
| 911 | + struct timeval tv; | |
| 912 | + int sr; | |
| 913 | + | |
| 914 | + FD_ZERO(&wfds); | |
| 915 | + FD_SET(s, &wfds); | |
| 916 | + tv.tv_sec = timeout_ms / 1000; | |
| 917 | + tv.tv_usec = (timeout_ms % 1000) * 1000; | |
| 918 | + sr = select((int)s + 1, NULL, &wfds, NULL, &tv); | |
| 919 | + if (sr <= 0) { sx_close_socket(s); return -1; } | |
| 920 | + { | |
| 921 | + int soerr = 0; | |
| 922 | +#if defined(_WIN32) | |
| 923 | + int sl = sizeof soerr; | |
| 924 | +#else | |
| 925 | + socklen_t sl = sizeof soerr; | |
| 926 | +#endif | |
| 927 | + if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &sl) != 0 || soerr != 0) { | |
| 928 | + sx_close_socket(s); | |
| 929 | + return -2; | |
| 930 | + } | |
| 931 | + } | |
| 932 | + } | |
| 933 | + } | |
| 934 | + | |
| 935 | + rc = (int)(now_ms() - start); | |
| 936 | + if (rc < 0) rc = 0; | |
| 937 | + addr_text(rp->ai_addr, addr_out, addr_sz); | |
| 938 | + sx_close_socket(s); | |
| 939 | + return rc; | |
| 940 | +} | |
| 941 | + | |
| 942 | +/* ------------------------------------------------------------------ */ | |
| 943 | +/* URL parsing for the http action */ | |
| 944 | +/* ------------------------------------------------------------------ */ | |
| 945 | + | |
| 946 | +typedef struct { | |
| 947 | + char scheme[8]; | |
| 948 | + char host[MAX_HOST]; /* bracketed when it is an IPv6 literal */ | |
| 949 | + char host_plain[MAX_HOST];/* bare address, for getaddrinfo */ | |
| 950 | + int port; | |
| 951 | + char path[MAX_PATHZ]; | |
| 952 | + int tls; | |
| 953 | +} url_t; | |
| 954 | + | |
| 955 | +static int parse_url(const char *in, url_t *u) | |
| 956 | +{ | |
| 957 | + const char *p = in; | |
| 958 | + const char *hs, *he, *ps; | |
| 959 | + size_t n; | |
| 960 | + | |
| 961 | + memset(u, 0, sizeof *u); | |
| 962 | + if (!in || !*in) return 0; | |
| 963 | + | |
| 964 | + if (strncmp(p, "http://", 7) == 0) { | |
| 965 | + str_copy(u->scheme, sizeof u->scheme, "http"); | |
| 966 | + u->tls = 0; | |
| 967 | + p += 7; | |
| 968 | + } else if (strncmp(p, "https://", 8) == 0) { | |
| 969 | + str_copy(u->scheme, sizeof u->scheme, "https"); | |
| 970 | + u->tls = 1; | |
| 971 | + p += 8; | |
| 972 | + } else { | |
| 973 | + return 0; | |
| 974 | + } | |
| 975 | + | |
| 976 | + hs = p; | |
| 977 | + he = p; | |
| 978 | + while (*he && *he != '/' && *he != '?' && *he != '#') he++; | |
| 979 | + ps = he; /* the path starts at the first '/', not at the port */ | |
| 980 | + | |
| 981 | + /* strip userinfo */ | |
| 982 | + { | |
| 983 | + const char *at = NULL, *q; | |
| 984 | + for (q = hs; q < he; q++) if (*q == '@') at = q; | |
| 985 | + if (at) hs = at + 1; | |
| 986 | + } | |
| 987 | + | |
| 988 | + /* split an optional :port. Scan right-to-left for the last colon outside | |
| 989 | + * IPv6 brackets: an unbracketed IPv6 literal (127.0.0.1:80 style aside) | |
| 990 | + * contains several colons, and the port is always the final one. */ | |
| 991 | + { | |
| 992 | + const char *col = NULL; | |
| 993 | + intptr_t qi = (intptr_t)(he - hs) - 1; | |
| 994 | + while (qi >= 0) { | |
| 995 | + char c = hs[qi]; | |
| 996 | + if (c == ']') { qi--; continue; } | |
| 997 | + if (c == '[') break; /* bracketed IPv6, no plain port colon */ | |
| 998 | + if (c == ':') { col = hs + qi; break; } | |
| 999 | + if (c == '/' || c == '?' || c == '#') break; | |
| 1000 | + qi--; | |
| 1001 | + } | |
| 1002 | + if (col) { | |
| 1003 | + long v; | |
| 1004 | + char pbuf[16]; | |
| 1005 | + size_t pn = (size_t)(he - col - 1); | |
| 1006 | + size_t k; | |
| 1007 | + if (pn == 0 || pn >= sizeof pbuf) return 0; | |
| 1008 | + memcpy(pbuf, col + 1, pn); | |
| 1009 | + pbuf[pn] = '\0'; | |
| 1010 | + for (k = 0; k < pn; k++) if (!isdigit((unsigned char)pbuf[k])) return 0; | |
| 1011 | + v = strtol(pbuf, NULL, 10); | |
| 1012 | + if (v < 1 || v > 65535) return 0; | |
| 1013 | + u->port = (int)v; | |
| 1014 | + he = col; | |
| 1015 | + } else { | |
| 1016 | + u->port = u->tls ? 443 : 80; | |
| 1017 | + } | |
| 1018 | + } | |
| 1019 | + | |
| 1020 | + n = (size_t)(he - hs); | |
| 1021 | + if (n == 0 || n >= sizeof u->host) return 0; | |
| 1022 | + memcpy(u->host, hs, n); | |
| 1023 | + u->host[n] = '\0'; | |
| 1024 | + | |
| 1025 | + /* bare address for the resolver */ | |
| 1026 | + if (u->host[0] == '[' && u->host[n - 1] == ']') { | |
| 1027 | + if (n < 3 || n - 2 >= sizeof u->host_plain) return 0; | |
| 1028 | + memcpy(u->host_plain, u->host + 1, n - 2); | |
| 1029 | + u->host_plain[n - 2] = '\0'; | |
| 1030 | + if (!looks_ipv6(u->host_plain)) return 0; | |
| 1031 | + } else { | |
| 1032 | + str_copy(u->host_plain, sizeof u->host_plain, u->host); | |
| 1033 | + if (!valid_host(u->host_plain)) return 0; | |
| 1034 | + } | |
| 1035 | + | |
| 1036 | + /* path */ | |
| 1037 | + { | |
| 1038 | + const char *e = ps; | |
| 1039 | + while (*e && *e != '?' && *e != '#') e++; | |
| 1040 | + n = (size_t)(e - ps); | |
| 1041 | + if (n == 0) { str_copy(u->path, sizeof u->path, "/"); } | |
| 1042 | + else { | |
| 1043 | + if (n >= sizeof u->path) n = sizeof u->path - 1; | |
| 1044 | + memcpy(u->path, ps, n); | |
| 1045 | + u->path[n] = '\0'; | |
| 1046 | + if (u->path[0] != '/') return 0; | |
| 1047 | + } | |
| 1048 | + } | |
| 1049 | + return 1; | |
| 1050 | +} | |
| 1051 | + | |
| 1052 | +/* ------------------------------------------------------------------ */ | |
| 1053 | +/* JSON helpers */ | |
| 1054 | +/* ------------------------------------------------------------------ */ | |
| 1055 | + | |
| 1056 | +static void emit_json_head(void) | |
| 1057 | +{ | |
| 1058 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1059 | + "Cache-Control: no-store\r\n" | |
| 1060 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1061 | +} | |
| 1062 | + | |
| 1063 | +static void err_json(int status, const char *msg) | |
| 1064 | +{ | |
| 1065 | + printf("Status: %d %s\r\n" | |
| 1066 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 1067 | + "Cache-Control: no-store\r\n" | |
| 1068 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 1069 | + "{\"ok\":false,\"error\":", | |
| 1070 | + status, status == 400 ? "Bad Request" : "Internal Error"); | |
| 1071 | + json_str(msg); | |
| 1072 | + puts("}"); | |
| 1073 | +} | |
| 1074 | + | |
| 1075 | +/* ------------------------------------------------------------------ */ | |
| 1076 | +/* action=ifaces */ | |
| 1077 | +/* ------------------------------------------------------------------ */ | |
| 1078 | + | |
| 1079 | +static void action_ifaces(void) | |
| 1080 | +{ | |
| 1081 | + int i; | |
| 1082 | + char stamp[32]; | |
| 1083 | + | |
| 1084 | + collect_ifaces(); | |
| 1085 | + discover_nameservers(); | |
| 1086 | + | |
| 1087 | + emit_json_head(); | |
| 1088 | + utc_stamp(time(NULL), stamp, sizeof stamp); | |
| 1089 | + printf("{\"ok\":true,\"action\":\"ifaces\",\"generated_at\":"); | |
| 1090 | + json_str(stamp); | |
| 1091 | + printf(",\"count\":%d,\"interfaces\":[", g_iface_count); | |
| 1092 | + for (i = 0; i < g_iface_count; i++) { | |
| 1093 | + const iface_t *f = &g_ifaces[i]; | |
| 1094 | + if (i) putchar(','); | |
| 1095 | + printf("{\"name\":"); | |
| 1096 | + json_str(f->name); | |
| 1097 | + printf(",\"address\":"); | |
| 1098 | + json_str(f->addr); | |
| 1099 | + printf(",\"family\":%d,\"netmask\":", f->family); | |
| 1100 | + if (f->mask[0]) json_str(f->mask); else fputs("null", stdout); | |
| 1101 | + printf(",\"broadcast\":"); | |
| 1102 | + if (f->broad[0]) json_str(f->broad); else fputs("null", stdout); | |
| 1103 | + printf(",\"loopback\":%s,\"up\":%s,\"running\":%s}", | |
| 1104 | + f->loopback ? "true" : "false", | |
| 1105 | + f->up ? "true" : "false", | |
| 1106 | + f->running ? "true" : "false"); | |
| 1107 | + } | |
| 1108 | + printf("],\"nameservers\":["); | |
| 1109 | + for (i = 0; i < g_ns_count; i++) { | |
| 1110 | + if (i) putchar(','); | |
| 1111 | + json_str(g_ns[i]); | |
| 1112 | + } | |
| 1113 | + printf("],\"nameserver_count\":%d}", g_ns_count); | |
| 1114 | +} | |
| 1115 | + | |
| 1116 | +/* ------------------------------------------------------------------ */ | |
| 1117 | +/* action=dns */ | |
| 1118 | +/* ------------------------------------------------------------------ */ | |
| 1119 | + | |
| 1120 | +static void action_dns(const char *host_in) | |
| 1121 | +{ | |
| 1122 | + struct addrinfo *res = NULL; | |
| 1123 | + struct addrinfo *rp; | |
| 1124 | + char stamp[32]; | |
| 1125 | + char target[MAX_HOST]; | |
| 1126 | + int n = 0; | |
| 1127 | + long long t0, t1; | |
| 1128 | + int rc; | |
| 1129 | + | |
| 1130 | + str_copy(target, sizeof target, host_in); | |
| 1131 | + str_lower(target); | |
| 1132 | + if (!target[0]) { err_json(400, "host required"); return; } | |
| 1133 | + if (!valid_host(target)) { err_json(400, "invalid host"); return; } | |
| 1134 | + | |
| 1135 | + emit_json_head(); | |
| 1136 | + utc_stamp(time(NULL), stamp, sizeof stamp); | |
| 1137 | + | |
| 1138 | + t0 = now_ms(); | |
| 1139 | + rc = resolve_with_deadline(target, NULL, &res, DNS_MS); | |
| 1140 | + t1 = now_ms(); | |
| 1141 | + | |
| 1142 | + printf("{\"ok\":true,\"action\":\"dns\",\"host\":"); | |
| 1143 | + json_str(target); | |
| 1144 | + printf(",\"generated_at\":"); | |
| 1145 | + json_str(stamp); | |
| 1146 | + printf(",\"timeout_ms\":%d", DNS_MS); | |
| 1147 | + | |
| 1148 | + if (rc == -1) { | |
| 1149 | + printf(",\"resolved\":false,\"timeout\":true,\"code\":null," | |
| 1150 | + "\"latency_ms\":%lld,\"results\":[],\"count\":0}", | |
| 1151 | + (long long)(t1 - t0)); | |
| 1152 | + return; | |
| 1153 | + } | |
| 1154 | + if (rc != 0 || !res) { | |
| 1155 | + printf(",\"resolved\":false,\"timeout\":false,\"code\":%d," | |
| 1156 | + "\"latency_ms\":%lld,\"results\":[],\"count\":0}", | |
| 1157 | + rc, (long long)(t1 - t0)); | |
| 1158 | + return; | |
| 1159 | + } | |
| 1160 | + | |
| 1161 | + printf(",\"resolved\":true,\"timeout\":false,\"code\":0," | |
| 1162 | + "\"latency_ms\":%lld,\"results\":[", (long long)(t1 - t0)); | |
| 1163 | + for (rp = res; rp; rp = rp->ai_next) { | |
| 1164 | + char txt[64]; | |
| 1165 | + if (!addr_text(rp->ai_addr, txt, sizeof txt)) continue; | |
| 1166 | + if (n) putchar(','); | |
| 1167 | + n++; | |
| 1168 | + printf("{\"address\":"); | |
| 1169 | + json_str(txt); | |
| 1170 | + printf(",\"family\":%s", rp->ai_family == AF_INET6 ? "\"inet6\"" : "\"inet\""); | |
| 1171 | + printf(",\"canonical\":"); | |
| 1172 | + if (rp->ai_canonname && *rp->ai_canonname) json_str(rp->ai_canonname); | |
| 1173 | + else fputs("null", stdout); | |
| 1174 | + putchar('}'); | |
| 1175 | + if (n >= MAX_RES) break; | |
| 1176 | + } | |
| 1177 | + freeaddrinfo(res); | |
| 1178 | + printf("],\"count\":%d}", n); | |
| 1179 | +} | |
| 1180 | + | |
| 1181 | +/* ------------------------------------------------------------------ */ | |
| 1182 | +/* action=tcp */ | |
| 1183 | +/* ------------------------------------------------------------------ */ | |
| 1184 | + | |
| 1185 | +static void action_tcp(const char *host_in, const char *port_s) | |
| 1186 | +{ | |
| 1187 | + long long samples[MAX_SAMPLES]; | |
| 1188 | + int nsamp = 0; | |
| 1189 | + int i; | |
| 1190 | + long long best = -1, worst = -1, sum = 0, cnt = 0; | |
| 1191 | + int status = 0; /* 0 failed, 1 open, 2 timeout */ | |
| 1192 | + char addr[64]; | |
| 1193 | + char stamp[32]; | |
| 1194 | + char target[MAX_HOST]; | |
| 1195 | + char pbuf[16]; | |
| 1196 | + struct addrinfo *res = NULL; | |
| 1197 | + struct addrinfo *rp; | |
| 1198 | + int rc; | |
| 1199 | + int port; | |
| 1200 | + | |
| 1201 | + str_copy(target, sizeof target, host_in); | |
| 1202 | + str_lower(target); | |
| 1203 | + if (!valid_host(target)) { err_json(400, "invalid host"); return; } | |
| 1204 | + | |
| 1205 | + port = atoi(port_s); | |
| 1206 | + if (port < 1 || port > 65535) { err_json(400, "invalid port"); return; } | |
| 1207 | + snprintf(pbuf, sizeof pbuf, "%d", port); | |
| 1208 | + | |
| 1209 | + emit_json_head(); | |
| 1210 | + utc_stamp(time(NULL), stamp, sizeof stamp); | |
| 1211 | + | |
| 1212 | + rc = resolve_with_deadline(target, pbuf, &res, DNS_MS); | |
| 1213 | + addr[0] = '\0'; | |
| 1214 | + | |
| 1215 | + if (rc == -1) { status = 2; samples[nsamp++] = -1; } | |
| 1216 | + else if (rc != 0 || !res) { status = 0; samples[nsamp++] = -2; } | |
| 1217 | + else { | |
| 1218 | + for (i = 0; i < MAX_SAMPLES; i++) { | |
| 1219 | + long long r; | |
| 1220 | + for (rp = res; rp; rp = rp->ai_next) { | |
| 1221 | + r = tcp_connect_ms(rp, TCP_MS, addr, sizeof addr); | |
| 1222 | + if (r >= 0 || r == -2) break; /* try the next family only on socket failure */ | |
| 1223 | + } | |
| 1224 | + if (r == -1) { samples[nsamp++] = -1; status = 2; break; } | |
| 1225 | + samples[nsamp++] = r; | |
| 1226 | + if (r >= 0) { status = 1; } | |
| 1227 | + else if (status != 1) { status = 0; } | |
| 1228 | + } | |
| 1229 | + freeaddrinfo(res); | |
| 1230 | + } | |
| 1231 | + | |
| 1232 | + for (i = 0; i < nsamp; i++) { | |
| 1233 | + if (samples[i] >= 0) { | |
| 1234 | + if (best < 0 || samples[i] < best) best = samples[i]; | |
| 1235 | + if (worst < 0 || samples[i] > worst) worst = samples[i]; | |
| 1236 | + sum += samples[i]; | |
| 1237 | + cnt++; | |
| 1238 | + } | |
| 1239 | + } | |
| 1240 | + | |
| 1241 | + printf("{\"ok\":true,\"action\":\"tcp\",\"host\":"); | |
| 1242 | + json_str(target); | |
| 1243 | + printf(",\"port\":%d,\"generated_at\":", port); | |
| 1244 | + json_str(stamp); | |
| 1245 | + printf(",\"open\":%s,\"status\":", status == 1 ? "true" : "false"); | |
| 1246 | + json_str(status == 1 ? "open" : (status == 2 ? "timeout" : "closed")); | |
| 1247 | + fputs(",\"address\":", stdout); | |
| 1248 | + if (addr[0]) json_str(addr); else fputs("null", stdout); | |
| 1249 | + printf(",\"samples\":["); | |
| 1250 | + for (i = 0; i < nsamp; i++) { | |
| 1251 | + if (i) putchar(','); | |
| 1252 | + if (samples[i] >= 0) printf("%lld", samples[i]); else fputs("null", stdout); | |
| 1253 | + } | |
| 1254 | + printf("],\"avg_ms\":"); | |
| 1255 | + if (cnt) printf("%.2f", (double)sum / (double)cnt); else fputs("null", stdout); | |
| 1256 | + printf(",\"min_ms\":"); | |
| 1257 | + if (best >= 0) printf("%lld", best); else fputs("null", stdout); | |
| 1258 | + printf(",\"max_ms\":"); | |
| 1259 | + if (worst >= 0) printf("%lld", worst); else fputs("null", stdout); | |
| 1260 | + printf(",\"timeout_ms\":%d}", TCP_MS); | |
| 1261 | +} | |
| 1262 | + | |
| 1263 | +/* ------------------------------------------------------------------ */ | |
| 1264 | +/* action=http */ | |
| 1265 | +/* ------------------------------------------------------------------ */ | |
| 1266 | + | |
| 1267 | +/* Plain HTTP reachability. Sends one HEAD request, reads only the status line | |
| 1268 | + * and the header block, never a body, and follows no redirects. There is no | |
| 1269 | + * TLS library in this binary, so an https:// target is reported as a TCP | |
| 1270 | + * connect to 443 with tls:"not_checked". */ | |
| 1271 | +static void action_http(const char *url_in) | |
| 1272 | +{ | |
| 1273 | + url_t u; | |
| 1274 | + SX_SOCK_T s = SX_SOCK_INVALID; | |
| 1275 | + struct addrinfo *res = NULL; | |
| 1276 | + struct addrinfo *rp; | |
| 1277 | + char req[768]; | |
| 1278 | + char buf[2048]; | |
| 1279 | + size_t have = 0; | |
| 1280 | + int status = 0; | |
| 1281 | + int header_lines = 0; | |
| 1282 | + int got_headers = 0; | |
| 1283 | + long long t0, t1, t2; | |
| 1284 | + char stamp[32]; | |
| 1285 | + char pbuf[16]; | |
| 1286 | + int rc; | |
| 1287 | + | |
| 1288 | + if (!parse_url(url_in, &u)) { err_json(400, "invalid url"); return; } | |
| 1289 | + | |
| 1290 | + snprintf(pbuf, sizeof pbuf, "%d", u.port); | |
| 1291 | + rc = resolve_with_deadline(u.host_plain, pbuf, &res, DNS_MS); | |
| 1292 | + | |
| 1293 | + emit_json_head(); | |
| 1294 | + utc_stamp(time(NULL), stamp, sizeof stamp); | |
| 1295 | + | |
| 1296 | + printf("{\"ok\":true,\"action\":\"http\",\"url\":"); | |
| 1297 | + json_str(url_in); | |
| 1298 | + printf(",\"host\":"); | |
| 1299 | + json_str(u.host); | |
| 1300 | + printf(",\"port\":%d,\"path\":", u.port); | |
| 1301 | + json_str(u.path); | |
| 1302 | + printf(",\"tls\":"); | |
| 1303 | + if (u.tls) fputs("\"not_checked\"", stdout); else fputs("false", stdout); | |
| 1304 | + printf(",\"generated_at\":"); | |
| 1305 | + json_str(stamp); | |
| 1306 | + | |
| 1307 | + if (rc == -1) { | |
| 1308 | + printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," | |
| 1309 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | |
| 1310 | + "\"note\":\"dns resolution timed out\"}"); | |
| 1311 | + return; | |
| 1312 | + } | |
| 1313 | + if (rc != 0 || !res) { | |
| 1314 | + printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," | |
| 1315 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | |
| 1316 | + "\"note\":\"host does not resolve\"}"); | |
| 1317 | + return; | |
| 1318 | + } | |
| 1319 | + | |
| 1320 | + t0 = now_ms(); | |
| 1321 | + for (rp = res; rp; rp = rp->ai_next) { | |
| 1322 | + s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
| 1323 | + if (s == SX_SOCK_INVALID) continue; | |
| 1324 | + rc = connect(s, rp->ai_addr, rp->ai_addrlen); | |
| 1325 | + if (rc == 0) break; | |
| 1326 | + sx_close_socket(s); | |
| 1327 | + s = SX_SOCK_INVALID; | |
| 1328 | + } | |
| 1329 | + freeaddrinfo(res); | |
| 1330 | + t1 = now_ms(); | |
| 1331 | + | |
| 1332 | + if (s == SX_SOCK_INVALID) { | |
| 1333 | + printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," | |
| 1334 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | |
| 1335 | + "\"note\":\"tcp connect failed\""); | |
| 1336 | + if (u.tls) | |
| 1337 | + fputs(",\"tls_note\":\"no TLS library: only the TCP connect to 443 was attempted\"", | |
| 1338 | + stdout); | |
| 1339 | + puts("}"); | |
| 1340 | + return; | |
| 1341 | + } | |
| 1342 | + | |
| 1343 | + if (u.tls) { | |
| 1344 | + /* No TLS: report the connect and stop. */ | |
| 1345 | + sx_close_socket(s); | |
| 1346 | + printf(",\"reachable\":true,\"connect_ms\":%lld,\"status\":null," | |
| 1347 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | |
| 1348 | + "\"note\":\"tcp connect succeeded; the TLS handshake was not attempted\"", | |
| 1349 | + (long long)(t1 - t0)); | |
| 1350 | + puts("}"); | |
| 1351 | + return; | |
| 1352 | + } | |
| 1353 | + | |
| 1354 | + /* Read timeout so a server that accepts but never answers cannot hang us. */ | |
| 1355 | +#if defined(_WIN32) | |
| 1356 | + { | |
| 1357 | + DWORD tv = (DWORD)READ_MS; | |
| 1358 | + setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv); | |
| 1359 | + } | |
| 1360 | +#else | |
| 1361 | + { | |
| 1362 | + struct timeval tv; | |
| 1363 | + tv.tv_sec = READ_MS / 1000; | |
| 1364 | + tv.tv_usec = (READ_MS % 1000) * 1000; | |
| 1365 | + setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); | |
| 1366 | + } | |
| 1367 | +#endif | |
| 1368 | + | |
| 1369 | + snprintf(req, sizeof req, | |
| 1370 | + "HEAD %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: scorpiox-bot-netcheck/1.0\r\n" | |
| 1371 | + "Accept: */*\r\nConnection: close\r\n\r\n", | |
| 1372 | + u.path, u.host); | |
| 1373 | + | |
| 1374 | + { | |
| 1375 | + size_t wl = strlen(req), sent = 0; | |
| 1376 | + while (sent < wl) { | |
| 1377 | + int w; | |
| 1378 | +#if defined(_WIN32) | |
| 1379 | + w = (int)send(s, req + sent, (int)(wl - sent), 0); | |
| 1380 | +#else | |
| 1381 | + w = (int)send(s, req + sent, wl - sent, 0); | |
| 1382 | +#endif | |
| 1383 | + if (w <= 0) break; | |
| 1384 | + sent += (size_t)w; | |
| 1385 | + } | |
| 1386 | + } | |
| 1387 | + | |
| 1388 | + t2 = now_ms(); | |
| 1389 | + while (have < sizeof buf - 1) { | |
| 1390 | + int r = (int)recv(s, buf + have, 1, 0); | |
| 1391 | + if (r <= 0) break; | |
| 1392 | + have += (size_t)r; | |
| 1393 | + if (have >= 4 && memcmp(buf + have - 4, "\r\n\r\n", 4) == 0) { got_headers = 1; break; } | |
| 1394 | + if (have >= 2 && memcmp(buf + have - 2, "\n\n", 2) == 0) { got_headers = 1; break; } | |
| 1395 | + if (now_ms() - t2 > READ_MS) break; | |
| 1396 | + } | |
| 1397 | + t2 = now_ms(); | |
| 1398 | + sx_close_socket(s); | |
| 1399 | + buf[have] = '\0'; | |
| 1400 | + | |
| 1401 | + printf(",\"reachable\":true,\"connect_ms\":%lld", (long long)(t1 - t0)); | |
| 1402 | + | |
| 1403 | + if (have >= 5 && strncmp(buf, "HTTP/", 5) == 0) { | |
| 1404 | + const char *sp = strchr(buf, ' '); | |
| 1405 | + if (sp) { | |
| 1406 | + const char *nl = strchr(sp, '\r'); | |
| 1407 | + char txt[64]; | |
| 1408 | + size_t n; | |
| 1409 | + if (!nl) nl = strchr(sp, '\n'); | |
| 1410 | + const char *rs; | |
| 1411 | + status = atoi(sp + 1); | |
| 1412 | + /* the reason phrase starts after the code and its single space */ | |
| 1413 | + rs = sp + 1; | |
| 1414 | + while (isdigit((unsigned char)*rs)) rs++; | |
| 1415 | + while (*rs == ' ' || *rs == '\t') rs++; | |
| 1416 | + n = nl ? (size_t)(nl - rs) : 0; | |
| 1417 | + if (n >= sizeof txt) n = sizeof txt - 1; | |
| 1418 | + memcpy(txt, rs, n); | |
| 1419 | + txt[n] = '\0'; | |
| 1420 | + str_trim(txt); | |
| 1421 | + printf(",\"status\":%d,\"status_text\":", status); | |
| 1422 | + json_str(txt); | |
| 1423 | + } else { | |
| 1424 | + fputs(",\"status\":null,\"status_text\":null", stdout); | |
| 1425 | + } | |
| 1426 | + } else { | |
| 1427 | + fputs(",\"status\":null,\"status_text\":null", stdout); | |
| 1428 | + } | |
| 1429 | + | |
| 1430 | + /* count header lines: everything after the status line up to the blank line */ | |
| 1431 | + { | |
| 1432 | + const char *p = strchr(buf, '\n'); | |
| 1433 | + if (p) { | |
| 1434 | + p++; | |
| 1435 | + for (;;) { | |
| 1436 | + const char *nl; | |
| 1437 | + while (*p == '\r' || *p == '\n') { | |
| 1438 | + /* a line that is only a terminator ends the header block */ | |
| 1439 | + if (*p == '\n') { p++; break; } | |
| 1440 | + p++; | |
| 1441 | + } | |
| 1442 | + if (!*p || *p == '\n') break; /* blank line = end of headers */ | |
| 1443 | + nl = strchr(p, '\n'); | |
| 1444 | + header_lines++; | |
| 1445 | + if (!nl) break; | |
| 1446 | + p = nl + 1; | |
| 1447 | + } | |
| 1448 | + } | |
| 1449 | + } | |
| 1450 | + | |
| 1451 | + printf(",\"header_lines\":%d,\"body_bytes_read\":0,\"read_ms\":%lld," | |
| 1452 | + "\"headers_complete\":%s", | |
| 1453 | + header_lines, (long long)(t2 - t1), got_headers ? "true" : "false"); | |
| 1454 | + if (status >= 300 && status < 400) | |
| 1455 | + fputs(",\"redirect\":\"not_followed\"", stdout); | |
| 1456 | + puts("}"); | |
| 1457 | +} | |
| 1458 | + | |
| 1459 | +/* ------------------------------------------------------------------ */ | |
| 1460 | +/* action=info */ | |
| 1461 | +/* ------------------------------------------------------------------ */ | |
| 1462 | + | |
| 1463 | +static void action_info(void) | |
| 1464 | +{ | |
| 1465 | + char stamp[32]; | |
| 1466 | + emit_json_head(); | |
| 1467 | + utc_stamp(time(NULL), stamp, sizeof stamp); | |
| 1468 | + printf("{\"ok\":true,\"plugin\":"); | |
| 1469 | + json_str(PLUGIN_ID); | |
| 1470 | + printf(",\"slug\":"); | |
| 1471 | + json_str(PLUGIN_SLUG); | |
| 1472 | + printf(",\"version\":"); | |
| 1473 | + json_str(PLUGIN_VER); | |
| 1474 | + printf(",\"generated_at\":"); | |
| 1475 | + json_str(stamp); | |
| 1476 | + printf(",\"actions\":[\"ifaces\",\"dns\",\"tcp\",\"http\",\"info\"]"); | |
| 1477 | + printf(",\"tls_library\":false,\"max_samples\":%d", MAX_SAMPLES); | |
| 1478 | + printf(",\"dns_timeout_ms\":%d,\"tcp_timeout_ms\":%d,\"read_timeout_ms\":%d", | |
| 1479 | + DNS_MS, TCP_MS, READ_MS); | |
| 1480 | + puts("}"); | |
| 1481 | +} | |
| 1482 | + | |
| 1483 | +static int is_post_request(void) | |
| 1484 | +{ | |
| 1485 | + const char *m = getenv("REQUEST_METHOD"); | |
| 1486 | + return m && (strcmp(m, "POST") == 0 || strcmp(m, "PUT") == 0); | |
| 1487 | +} | |
| 1488 | + | |
| 1489 | +static int mode_meta(void) | |
| 1490 | +{ | |
| 1491 | + puts("{\"name\":\"netcheck\",\"desc\":\"Net checks\"}"); | |
| 1492 | + return 0; | |
| 1493 | +} | |
| 1494 | + | |
| 1495 | +static int mode_json(const char *qs) | |
| 1496 | +{ | |
| 1497 | + char action[64]; | |
| 1498 | + char host[MAX_HOST]; | |
| 1499 | + char port_s[16]; | |
| 1500 | + char url_s[MAX_LINE]; | |
| 1501 | + | |
| 1502 | + get_query_val(qs, "action", action, sizeof action); | |
| 1503 | + str_lower(action); | |
| 1504 | + | |
| 1505 | + if (action[0] == '\0') { action_info(); return 0; } | |
| 1506 | + | |
| 1507 | + if (strcmp(action, "ifaces") == 0) { action_ifaces(); return 0; } | |
| 1508 | + | |
| 1509 | + if (strcmp(action, "dns") == 0) { | |
| 1510 | + if (!get_query_val(qs, "host", host, sizeof host)) { | |
| 1511 | + err_json(400, "host required"); return 0; | |
| 1512 | + } | |
| 1513 | + action_dns(host); | |
| 1514 | + return 0; | |
| 1515 | + } | |
| 1516 | + | |
| 1517 | + if (strcmp(action, "tcp") == 0) { | |
| 1518 | + if (!get_query_val(qs, "host", host, sizeof host)) { | |
| 1519 | + err_json(400, "host required"); return 0; | |
| 1520 | + } | |
| 1521 | + if (!get_query_val(qs, "port", port_s, sizeof port_s)) { | |
| 1522 | + err_json(400, "port required"); return 0; | |
| 1523 | + } | |
| 1524 | + action_tcp(host, port_s); | |
| 1525 | + return 0; | |
| 1526 | + } | |
| 1527 | + | |
| 1528 | + if (strcmp(action, "http") == 0) { | |
| 1529 | + if (!get_query_val(qs, "url", url_s, sizeof url_s)) { | |
| 1530 | + err_json(400, "url required"); return 0; | |
| 1531 | + } | |
| 1532 | + action_http(url_s); | |
| 1533 | + return 0; | |
| 1534 | + } | |
| 1535 | + | |
| 1536 | + if (strcmp(action, "info") == 0) { action_info(); return 0; } | |
| 1537 | + | |
| 1538 | + err_json(400, "unknown action"); | |
| 1539 | + return 0; | |
| 1540 | +} | |
| 1541 | + | |
| 1542 | +/* ------------------------------------------------------------------ */ | |
| 1543 | +/* HTML mode */ | |
| 1544 | +/* ------------------------------------------------------------------ */ | |
| 1545 | + | |
| 1546 | +/* Split UI_HTML on the two control-byte placeholders and expand them into the | |
| 1547 | + * theme macros, so the page and the bot palette can never drift. */ | |
| 1548 | +static void emit_ui(void) | |
| 1549 | +{ | |
| 1550 | + const char *p = UI_HTML; | |
| 1551 | + | |
| 1552 | + while (*p) { | |
| 1553 | + if (*p == '\001') { | |
| 1554 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | |
| 1555 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" | |
| 1556 | + "</style>", stdout); | |
| 1557 | + p++; | |
| 1558 | + } else if (*p == '\002') { | |
| 1559 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1560 | + p++; | |
| 1561 | + } else { | |
| 1562 | + putchar(*p++); | |
| 1563 | + } | |
| 1564 | + } | |
| 1565 | +} | |
| 1566 | + | |
| 1567 | +static int mode_html(int embed) | |
| 1568 | +{ | |
| 1569 | + (void)embed; | |
| 1570 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1571 | + "Cache-Control: no-store\r\n" | |
| 1572 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1573 | + "X-Frame-Options: SAMEORIGIN\r\n" | |
| 1574 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 1575 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | |
| 1576 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | |
| 1577 | + emit_ui(); | |
| 1578 | + return 0; | |
| 1579 | +} | |
| 1580 | + | |
| 1581 | +int main(int argc, char **argv) | |
| 1582 | +{ | |
| 1583 | + const char *qs; | |
| 1584 | + int embed; | |
| 1585 | + | |
| 1586 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || | |
| 1587 | + (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) | |
| 1588 | + return mode_meta(); | |
| 1589 | + | |
| 1590 | +#if defined(_WIN32) | |
| 1591 | + { | |
| 1592 | + WSADATA wsa; | |
| 1593 | + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) | |
| 1594 | + return mode_meta(); | |
| 1595 | + } | |
| 1596 | +#endif | |
| 1597 | + | |
| 1598 | + require_node_auth(); | |
| 1599 | + | |
| 1600 | + qs = getenv("QUERY_STRING"); | |
| 1601 | + if (!qs) qs = ""; | |
| 1602 | + | |
| 1603 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) | |
| 1604 | + return mode_json(qs); | |
| 1605 | + | |
| 1606 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | |
| 1607 | + return mode_html(embed); | |
| 1608 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..0349de1 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,446 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="en"><head><meta charset="utf-8"> | |
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 4 | +<title>netcheck</title> | |
| 5 | +<!--TOKENS--> | |
| 6 | +<style> | |
| 7 | +*{box-sizing:border-box} | |
| 8 | +html,body{margin:0;height:100%} | |
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font); | |
| 10 | + font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased} | |
| 11 | +.wrap{max-width:1080px;margin:0 auto;padding:16px 16px 32px} | |
| 12 | +.top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap} | |
| 13 | +.title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em} | |
| 14 | +.pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px; | |
| 15 | + background:var(--surface-2);color:var(--text-2);border:1px solid var(--line); | |
| 16 | + white-space:nowrap} | |
| 17 | +.sp{flex:1} | |
| 18 | +.icon{display:inline-flex;align-items:center;justify-content:center;gap:6px; | |
| 19 | + background:var(--surface-2);border:1px solid var(--line);color:var(--text); | |
| 20 | + border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit; | |
| 21 | + font-size:12px;font-weight:600} | |
| 22 | +.icon:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 23 | +.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor; | |
| 24 | + stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} | |
| 25 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:8px 16px; | |
| 26 | + font-weight:600;font-size:13px;cursor:pointer;font-family:inherit} | |
| 27 | +.btn:disabled{opacity:.55;cursor:default} | |
| 28 | +.btn.gh{background:transparent;color:var(--text);border:1px solid var(--line)} | |
| 29 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | |
| 30 | + padding:16px;margin-bottom:14px;box-shadow:var(--shadow)} | |
| 31 | +.card h2{margin:0 0 10px;font-size:11.5px;letter-spacing:.07em;text-transform:uppercase; | |
| 32 | + color:var(--text-2);font-weight:600} | |
| 33 | +.hint{color:var(--text-2);font-size:12px;margin:0 0 10px} | |
| 34 | +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px} | |
| 35 | +.kpi{background:var(--surface-2);border:1px solid var(--line);border-radius:10px; | |
| 36 | + padding:10px 12px} | |
| 37 | +.kpi .k{font-size:10.5px;color:var(--text-2);text-transform:uppercase;letter-spacing:.05em} | |
| 38 | +.kpi .v{font-size:15px;font-weight:700;font-family:var(--mono);margin-top:3px; | |
| 39 | + word-break:break-word} | |
| 40 | +.tb{width:100%;overflow-x:auto} | |
| 41 | +table{width:100%;border-collapse:collapse;font-size:13px} | |
| 42 | +th{text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em; | |
| 43 | + color:var(--text-2);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line); | |
| 44 | + white-space:nowrap} | |
| 45 | +td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle; | |
| 46 | + word-break:break-word} | |
| 47 | +tr:last-child td{border-bottom:0} | |
| 48 | +.mo{font-family:var(--mono);font-size:12.5px} | |
| 49 | +.tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap; | |
| 50 | + background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)} | |
| 51 | +.tag.ok{background:rgba(48,209,88,.16);color:var(--green)} | |
| 52 | +.tag.warn{background:rgba(255,159,10,.16);color:var(--orange)} | |
| 53 | +.tag.bad{background:rgba(255,69,58,.16);color:var(--red)} | |
| 54 | +.tag.blue{background:rgba(10,132,255,.16);color:var(--blue)} | |
| 55 | +.tabs{display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap} | |
| 56 | +.tab{background:var(--surface-2);border:1px solid var(--line);color:var(--text-2); | |
| 57 | + border-radius:980px;padding:6px 14px;font-size:12.5px;font-weight:600;cursor:pointer; | |
| 58 | + font-family:inherit} | |
| 59 | +.tab.on{background:var(--blue);color:#fff;border-color:var(--blue)} | |
| 60 | +.inp{flex:1 1 240px;min-width:0;background:var(--input-bg);border:1px solid var(--line); | |
| 61 | + border-radius:10px;padding:10px 12px;color:var(--text);font-size:13.5px; | |
| 62 | + font-family:inherit} | |
| 63 | +.inp:focus{outline:2px solid var(--blue);outline-offset:-1px} | |
| 64 | +.inp.mo{font-family:var(--mono)} | |
| 65 | +.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap} | |
| 66 | +.res{border-top:1px solid var(--line);padding-top:12px;margin-top:12px} | |
| 67 | +.res .hd{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px} | |
| 68 | +.res .big{font-size:16px;font-weight:700;font-family:var(--mono)} | |
| 69 | +.kv{display:grid;grid-template-columns:auto 1fr;gap:4px 12px;font-size:12.5px} | |
| 70 | +.kv .k{color:var(--text-2)} | |
| 71 | +.kv .v{font-family:var(--mono);word-break:break-all} | |
| 72 | +ul.hist{list-style:none;margin:0;padding:0} | |
| 73 | +ul.hist li{display:flex;align-items:center;gap:8px;padding:7px 2px; | |
| 74 | + border-bottom:1px solid var(--line);font-size:12.5px;flex-wrap:wrap} | |
| 75 | +ul.hist li:last-child{border-bottom:0} | |
| 76 | +ul.hist .t{font-family:var(--mono);flex:1 1 200px;min-width:0;word-break:break-all} | |
| 77 | +ul.hist .ms{font-family:var(--mono);color:var(--text-2);font-size:11.5px} | |
| 78 | +.spark{width:100%;height:56px;display:block;margin-top:10px} | |
| 79 | +.spark[hidden]{display:none} | |
| 80 | +.spark .ln{fill:none;stroke:var(--blue);stroke-width:1.6; | |
| 81 | + stroke-linecap:round;stroke-linejoin:round} | |
| 82 | +.spark .ax{stroke:var(--line);stroke-width:1} | |
| 83 | +.spark .dot{fill:var(--blue)} | |
| 84 | +.spark .dot.bad{fill:var(--red)} | |
| 85 | +.empty{color:var(--text-2);font-size:12.5px;padding:10px 0} | |
| 86 | +[hidden]{display:none!important} | |
| 87 | +.err{color:var(--red);font-size:12.5px} | |
| 88 | +.note{color:var(--text-2);font-size:12px;margin-top:8px} | |
| 89 | +.foot{color:var(--text-2);font-size:11.5px;margin-top:18px;line-height:1.6} | |
| 90 | +.foot code{font-family:var(--mono);font-size:11px;background:var(--surface-2); | |
| 91 | + padding:1px 5px;border-radius:5px;border:1px solid var(--line)} | |
| 92 | +@media(max-width:700px){.wrap{padding:10px 10px 24px}.card{padding:12px;border-radius:12px} | |
| 93 | + .title{font-size:17px}} | |
| 94 | +</style></head><body><div class="wrap"> | |
| 95 | + | |
| 96 | +<div class="top"> | |
| 97 | + <a href="/" class="embed-hide" style="color:var(--blue);text-decoration:none;font-weight:600">←</a> | |
| 98 | + <h1 class="title">netcheck</h1> | |
| 99 | + <span class="pill" id="srcPill">this node</span> | |
| 100 | + <span class="sp"></span> | |
| 101 | + <button class="icon embed-hide" id="thBtn" title="Toggle appearance" aria-label="Toggle appearance"> | |
| 102 | + <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.5"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/></svg> | |
| 103 | + </button> | |
| 104 | + <button class="icon" id="rfBtn" title="Refresh interfaces" aria-label="Refresh interfaces"> | |
| 105 | + <svg viewBox="0 0 24 24"><path d="M20 11a8 8 0 1 0-2.3 5.7"/><path d="M20 5v6h-6"/></svg> | |
| 106 | + </button> | |
| 107 | +</div> | |
| 108 | + | |
| 109 | +<div class="card"> | |
| 110 | + <h2>Interfaces on this node</h2> | |
| 111 | + <p class="hint">Addresses read from the node's own interface table. Nothing leaves the machine for this view.</p> | |
| 112 | + <div class="grid" id="kpis"></div> | |
| 113 | + <div class="tb" style="margin-top:12px"> | |
| 114 | + <table> | |
| 115 | + <thead><tr><th>Interface</th><th>Address</th><th>Netmask</th><th>State</th></tr></thead> | |
| 116 | + <tbody id="ifrows"></tbody> | |
| 117 | + </table> | |
| 118 | + </div> | |
| 119 | + <div class="empty" id="ifEmpty" hidden>No interfaces found.</div> | |
| 120 | + <div class="res"> | |
| 121 | + <h2 style="margin-top:0">Configured DNS servers</h2> | |
| 122 | + <div class="row" id="nsList"></div> | |
| 123 | + </div> | |
| 124 | +</div> | |
| 125 | + | |
| 126 | +<div class="card"> | |
| 127 | + <h2>Run a check</h2> | |
| 128 | + <div class="tabs" role="tablist"> | |
| 129 | + <button class="tab on" id="tabDns" role="tab" data-tab="dns">DNS</button> | |
| 130 | + <button class="tab" id="tabTcp" role="tab" data-tab="tcp">TCP</button> | |
| 131 | + <button class="tab" id="tabHttp" role="tab" data-tab="http">HTTP</button> | |
| 132 | + </div> | |
| 133 | + <div class="row"> | |
| 134 | + <input id="inp" class="inp mo" placeholder="example.com" autocomplete="off" spellcheck="false" aria-label="Target"> | |
| 135 | + <input id="port" class="inp mo" type="number" min="1" max="65535" step="1" | |
| 136 | + value="443" style="width:110px;display:none" placeholder="port" aria-label="Port"> | |
| 137 | + <button class="btn" id="goBtn">Check</button> | |
| 138 | + </div> | |
| 139 | + <p class="note" id="tabNote">Resolves a name to its addresses. Uses the node's resolver with a 3 second deadline.</p> | |
| 140 | + <div class="res" id="resBox"> | |
| 141 | + <div class="hd"><span class="big" id="resState">idle</span><span id="resTag"></span></div> | |
| 142 | + <div class="kv" id="resKv"></div> | |
| 143 | + <div class="note" id="resNote"></div> | |
| 144 | + <svg class="spark" id="spark" viewBox="0 0 320 56" preserveAspectRatio="none" | |
| 145 | + aria-label="TCP latency history" hidden></svg> | |
| 146 | + </div> | |
| 147 | +</div> | |
| 148 | + | |
| 149 | +<div class="card"> | |
| 150 | + <h2>History <span class="pill" id="histCount">0</span></h2> | |
| 151 | + <p class="hint">Kept in this page only — nothing is written to disk.</p> | |
| 152 | + <ul class="hist" id="hist"><li class="empty">No checks yet this session.</li></ul> | |
| 153 | +</div> | |
| 154 | + | |
| 155 | +<p class="foot"> | |
| 156 | + netcheck runs on the node and makes only the outbound connections you ask for: a DNS lookup, | |
| 157 | + a TCP connect, or one <code>HEAD</code> request over plain HTTP. There is no TLS library in the | |
| 158 | + binary, so an <code>https://</code> target is checked as a TCP connect to port 443 and reported | |
| 159 | + as <code>tls: not_checked</code>. Response bodies are never read, and redirects are never followed. | |
| 160 | + Every action sits behind node authentication. | |
| 161 | +</p> | |
| 162 | +</div> | |
| 163 | +<script> | |
| 164 | +(function(){ | |
| 165 | +"use strict"; | |
| 166 | +var q=new URLSearchParams(location.search); | |
| 167 | +var node=q.get('node')||''; | |
| 168 | +var sid=q.get('id')||''; | |
| 169 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | |
| 170 | + localStorage.getItem('bot_active_pwd')||''; | |
| 171 | +var HUB=q.get('plugin')||''; | |
| 172 | + | |
| 173 | +/* Two call routes, and getting this wrong is the most common plugin bug: | |
| 174 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_netcheck&node=..) | |
| 175 | + * -> call the hub proxy back: /plugins?plugin=plugin_netcheck&action=.. | |
| 176 | + * opened directly on the node | |
| 177 | + * -> the plugin itself is the route: /plugin_netcheck?action=.. | |
| 178 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | |
| 179 | +function api(action,params){ | |
| 180 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_netcheck') | |
| 181 | + +'?action='+encodeURIComponent(action) | |
| 182 | + +(params||'') | |
| 183 | + +(node?'&node='+encodeURIComponent(node):'') | |
| 184 | + +(sid?'&id='+encodeURIComponent(sid):'') | |
| 185 | + +(pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 186 | + return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}) | |
| 187 | + .then(function(r){return r.json().then(function(d){if(!r.ok)throw new Error('HTTP '+r.status);return d;});}); | |
| 188 | +} | |
| 189 | + | |
| 190 | +function esc(v){return String(v==null?'':v).replace(/[&<>"']/g,function(c){ | |
| 191 | + return({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c];});} | |
| 192 | +function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;} | |
| 193 | +function $(id){return document.getElementById(id);} | |
| 194 | + | |
| 195 | +var TAB='dns'; | |
| 196 | +var HIST=[]; /* last 20 checks, in-page only */ | |
| 197 | +var TCPMS=[]; /* tcp latency samples for the sparkline */ | |
| 198 | + | |
| 199 | +var NOTE={ | |
| 200 | + dns:'Resolves a name to its addresses. Uses the node\'s resolver with a 3 second deadline.', | |
| 201 | + tcp:'Measures a TCP connect. Three samples, 3 second deadline each, reported as min/avg/max.', | |
| 202 | + http:'Sends one HEAD request over plain TCP. Status line and headers only, body never read, no redirects.' | |
| 203 | +}; | |
| 204 | +var PH={dns:'example.com',tcp:'example.com',http:'http://example.com'}; | |
| 205 | + | |
| 206 | +function setTab(t){ | |
| 207 | + TAB=t; | |
| 208 | + ['dns','tcp','http'].forEach(function(k){ | |
| 209 | + var b=$('tab'+k.charAt(0).toUpperCase()+k.slice(1)); | |
| 210 | + if(b)b.className='tab'+(k===t?' on':''); | |
| 211 | + }); | |
| 212 | + $('port').style.display=(t==='tcp')?'':'none'; | |
| 213 | + $('inp').placeholder=PH[t]; | |
| 214 | + txt('tabNote',NOTE[t]); | |
| 215 | +} | |
| 216 | + | |
| 217 | +/* ---------- interfaces ---------- */ | |
| 218 | +function renderIfaces(d){ | |
| 219 | + var rows=$('ifrows'),kp=$('kpis'),ns=$('nsList'); | |
| 220 | + var list=(d&&d.interfaces)||[]; | |
| 221 | + var upn=0,glob=0,lo=0,i; | |
| 222 | + var h=''; | |
| 223 | + for(i=0;i<list.length;i++){ | |
| 224 | + var f=list[i]; | |
| 225 | + if(f.up)upn++; | |
| 226 | + if(!f.loopback&&(f.family===4||f.addr!=='::1'))glob++; | |
| 227 | + if(f.loopback)lo++; | |
| 228 | + h+='<tr><td class="mo">'+esc(f.name)+'</td>' | |
| 229 | + +'<td class="mo">'+esc(f.address)+'</td>' | |
| 230 | + +'<td class="mo">'+esc(f.netmask||'-')+'</td>' | |
| 231 | + +'<td>'+(f.up?'<span class="tag ok">up</span>':'<span class="tag bad">down</span>') | |
| 232 | + +(f.loopback?' <span class="tag">loopback</span>':'') | |
| 233 | + +(f.family===6?' <span class="tag">ipv6</span>':'')+'</td></tr>'; | |
| 234 | + } | |
| 235 | + rows.innerHTML=h; | |
| 236 | + /* show the empty message only when there really are no rows */ | |
| 237 | + if(list.length){$('ifEmpty').setAttribute('hidden','');} | |
| 238 | + else{$('ifEmpty').removeAttribute('hidden');} | |
| 239 | + var nsr=(d&&d.nameservers)||[]; | |
| 240 | + var kh=''; | |
| 241 | + kh+='<div class="kpi"><div class="k">Interfaces</div><div class="v">'+list.length+'</div></div>'; | |
| 242 | + kh+='<div class="kpi"><div class="k">Up</div><div class="v">'+upn+'</div></div>'; | |
| 243 | + kh+='<div class="kpi"><div class="k">Loopback</div><div class="v">'+lo+'</div></div>'; | |
| 244 | + kh+='<div class="kpi"><div class="k">DNS servers</div><div class="v">'+nsr.length+'</div></div>'; | |
| 245 | + kp.innerHTML=kh; | |
| 246 | + if(!nsr.length){ns.innerHTML='<span class="empty">None configured.</span>';} | |
| 247 | + else{var nh='';for(i=0;i<nsr.length;i++)nh+='<span class="tag blue">'+esc(nsr[i])+'</span>';ns.innerHTML=nh;} | |
| 248 | + txt('srcPill',(d&&d.count!=null)?(list.length+' iface'+(list.length===1?'':'s')):'this node'); | |
| 249 | +} | |
| 250 | + | |
| 251 | +function loadIfaces(){ | |
| 252 | + api('ifaces','').then(renderIfaces).catch(function(e){ | |
| 253 | + $('ifrows').innerHTML=''; | |
| 254 | + $('kpis').innerHTML='<div class="kpi"><div class="k">Error</div><div class="v">'+esc(String(e.message||e))+'</div></div>'; | |
| 255 | + $('ifEmpty').removeAttribute('hidden'); | |
| 256 | + }); | |
| 257 | +} | |
| 258 | + | |
| 259 | +/* ---------- sparkline ---------- */ | |
| 260 | +function drawSpark(){ | |
| 261 | + var svg=$('spark'); | |
| 262 | + /* `hidden` is an HTMLElement property, not an SVGElement one, so it has to | |
| 263 | + * be set as an attribute or the browser keeps the one from the markup. */ | |
| 264 | + if(TAB!=='tcp'||TCPMS.length<2){svg.setAttribute('hidden','');return;} | |
| 265 | + svg.removeAttribute('hidden'); | |
| 266 | + var W=320,H=56,PAD=6; | |
| 267 | + var vals=TCPMS.slice(-20); | |
| 268 | + var good=vals.filter(function(v){return v>=0;}); | |
| 269 | + var mx=good.length?Math.max.apply(null,good):0; | |
| 270 | + var mn=good.length?Math.min.apply(null,good):0; | |
| 271 | + /* A flat series has no range to normalise against. Plot it on the middle | |
| 272 | + * line instead of the floor, otherwise "every connect was instant" reads | |
| 273 | + * like "every connect hit the deadline". */ | |
| 274 | + var flat=(mx-mn)<1; | |
| 275 | + var scale=flat?1:(mx-mn); | |
| 276 | + var n=vals.length; | |
| 277 | + var pts=[],i,x,y; | |
| 278 | + for(i=0;i<n;i++){ | |
| 279 | + x=PAD+(i*(W-2*PAD))/(n-1); | |
| 280 | + var v=vals[i]; | |
| 281 | + if(v<0){y=H-PAD;} | |
| 282 | + else if(flat){y=(H-2*PAD)/2+PAD;} | |
| 283 | + else{y=H-PAD-((H-2*PAD)*((v-mn)/scale));} | |
| 284 | + pts.push([x,y,v]); | |
| 285 | + } | |
| 286 | + var out='<line class="ax" x1="0" y1="'+(H-PAD)+'" x2="'+W+'" y2="'+(H-PAD)+'"/>'; | |
| 287 | + var d=''; | |
| 288 | + for(i=0;i<pts.length;i++){ | |
| 289 | + if(pts[i][2]<0)continue; | |
| 290 | + d+=(d?'L':'M')+pts[i][0].toFixed(1)+' '+pts[i][1].toFixed(1); | |
| 291 | + } | |
| 292 | + if(d)out+='<path class="ln" d="'+d+'"/>'; | |
| 293 | + for(i=0;i<pts.length;i++){ | |
| 294 | + out+='<circle class="dot'+(pts[i][2]<0?' bad':'')+'" cx="'+pts[i][0].toFixed(1) | |
| 295 | + +'" cy="'+pts[i][1].toFixed(1)+'" r="2.4"/>'; | |
| 296 | + } | |
| 297 | + svg.innerHTML=out; | |
| 298 | +} | |
| 299 | + | |
| 300 | +/* ---------- history ---------- */ | |
| 301 | +function pushHist(item){ | |
| 302 | + HIST.unshift(item); | |
| 303 | + if(HIST.length>20)HIST.pop(); | |
| 304 | + renderHist(); | |
| 305 | +} | |
| 306 | +function renderHist(){ | |
| 307 | + var ul=$('hist'); | |
| 308 | + txt('histCount',String(HIST.length)); | |
| 309 | + if(!HIST.length){ul.innerHTML='<li class="empty">No checks yet this session.</li>';return;} | |
| 310 | + var h=''; | |
| 311 | + for(var i=0;i<HIST.length;i++){ | |
| 312 | + var it=HIST[i]; | |
| 313 | + h+='<li><span class="tag '+(it.ok?'ok':'bad')+'">'+esc(it.kind)+'</span>' | |
| 314 | + +'<span class="t">'+esc(it.label)+'</span>' | |
| 315 | + +'<span class="ms">'+esc(it.detail)+'</span>' | |
| 316 | + +'<span class="ms">'+esc(it.at)+'</span></li>'; | |
| 317 | + } | |
| 318 | + ul.innerHTML=h; | |
| 319 | +} | |
| 320 | + | |
| 321 | +/* ---------- result rendering ---------- */ | |
| 322 | +function kv(pairs){ | |
| 323 | + var h=''; | |
| 324 | + for(var i=0;i<pairs.length;i++){ | |
| 325 | + h+='<div class="k"><span class="k">'+esc(pairs[i][0])+'</span></div>' | |
| 326 | + +'<div class="v">'+esc(pairs[i][1]==null?'-':String(pairs[i][1]))+'</div>'; | |
| 327 | + } | |
| 328 | + $('resKv').innerHTML=h; | |
| 329 | +} | |
| 330 | + | |
| 331 | +function showDns(d,target){ | |
| 332 | + var ok=d.resolved===true; | |
| 333 | + txt('resState',ok?'resolved':'not resolved'); | |
| 334 | + $('resTag').innerHTML=ok?'<span class="tag ok">ok</span>':'<span class="tag bad">'+esc(d.timeout?'timeout':'fail')+'</span>'; | |
| 335 | + var pairs=[['host',d.host],['latency',(d.latency_ms==null?'-':d.latency_ms+' ms')], | |
| 336 | + ['answers',d.count],['deadline',d.timeout_ms+' ms']]; | |
| 337 | + if(d.results&&d.results.length){ | |
| 338 | + var addrs=[]; | |
| 339 | + for(var i=0;i<d.results.length;i++)addrs.push(d.results[i].address); | |
| 340 | + pairs.push(['addresses',addrs.join(', ')]); | |
| 341 | + } | |
| 342 | + kv(pairs); | |
| 343 | + txt('resNote',ok?'':'The resolver returned no record for this name.'); | |
| 344 | + pushHist({kind:'dns',label:target,ok:ok,detail:(d.count||0)+' addr',at:clock()}); | |
| 345 | +} | |
| 346 | + | |
| 347 | +function showTcp(d,target){ | |
| 348 | + var open=d.open===true; | |
| 349 | + var last=(d.samples&&d.samples.length)?d.samples[d.samples.length-1]:null; | |
| 350 | + TCPMS.push(typeof last==='number'?last:-1); | |
| 351 | + if(TCPMS.length>20)TCPMS.shift(); | |
| 352 | + txt('resState',open?'open':(d.status==='timeout'?'timeout':'closed')); | |
| 353 | + $('resTag').innerHTML=open?'<span class="tag ok">reachable</span>' | |
| 354 | + :'<span class="tag bad">'+esc(d.status||'closed')+'</span>'; | |
| 355 | + var pairs=[['target',d.host+':'+d.port],['resolved to',d.address], | |
| 356 | + ['avg',(d.avg_ms==null?'-':d.avg_ms+' ms')], | |
| 357 | + ['min',(d.min_ms==null?'-':d.min_ms+' ms')], | |
| 358 | + ['max',(d.max_ms==null?'-':d.max_ms+' ms')], | |
| 359 | + ['samples',(d.samples||[]).map(function(s){return s==null?'timeout':s+' ms';}).join(', ')]]; | |
| 360 | + kv(pairs); | |
| 361 | + txt('resNote',open?'Three connects succeeded against the first resolved address.' | |
| 362 | + :'The connect did not complete inside the deadline.'); | |
| 363 | + drawSpark(); | |
| 364 | + pushHist({kind:'tcp',label:d.host+':'+d.port,ok:open, | |
| 365 | + detail:open?((d.avg_ms==null?'-':d.avg_ms+' ms avg')):d.status,at:clock()}); | |
| 366 | +} | |
| 367 | + | |
| 368 | +function showHttp(d,target){ | |
| 369 | + var ok=d.reachable===true&&d.status!=null&&d.status<400; | |
| 370 | + txt('resState',d.status==null?(d.reachable?'connected':'unreachable'):('HTTP '+d.status)); | |
| 371 | + $('resTag').innerHTML=d.status==null | |
| 372 | + ?(d.reachable?'<span class="tag warn">no status line</span>':'<span class="tag bad">unreachable</span>') | |
| 373 | + :(ok?'<span class="tag ok">reachable</span>':'<span class="tag bad">status '+esc(d.status)+'</span>'); | |
| 374 | + var pairs=[['url',d.url],['host',d.host+':'+d.port],['path',d.path], | |
| 375 | + ['connect',(d.connect_ms==null?'-':d.connect_ms+' ms')], | |
| 376 | + ['status',(d.status==null?'-':d.status+' '+(d.status_text||''))], | |
| 377 | + ['headers',d.header_lines],['body','0 bytes (HEAD)'], | |
| 378 | + ['tls',d.tls]]; | |
| 379 | + kv(pairs); | |
| 380 | + txt('resNote',d.note||''); | |
| 381 | + pushHist({kind:'http',label:d.url,ok:ok,detail:(d.status==null?'no status':String(d.status)),at:clock()}); | |
| 382 | +} | |
| 383 | + | |
| 384 | +function clock(){ | |
| 385 | + var d=new Date(); | |
| 386 | + return d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit',second:'2-digit'}); | |
| 387 | +} | |
| 388 | + | |
| 389 | +function run(){ | |
| 390 | + var v=$('inp').value.trim(); | |
| 391 | + if(!v){txt('resState','enter a target');return;} | |
| 392 | + txt('resState','running...'); | |
| 393 | + $('resKv').innerHTML=''; | |
| 394 | + $('resNote').textContent=''; | |
| 395 | + $('goBtn').disabled=true; | |
| 396 | + var p=''; | |
| 397 | + var call; | |
| 398 | + if(TAB==='dns'){call=api('dns','&host='+encodeURIComponent(v));} | |
| 399 | + else if(TAB==='tcp'){ | |
| 400 | + var pt=$('port').value.trim(); | |
| 401 | + if(!pt){$('goBtn').disabled=false;txt('resState','port required');return;} | |
| 402 | + call=api('tcp','&host='+encodeURIComponent(v)+'&port='+encodeURIComponent(pt)); | |
| 403 | + } else { | |
| 404 | + var uv=v; | |
| 405 | + if(!/^https?:\/\//i.test(uv))uv='http://'+uv; | |
| 406 | + call=api('http','&url='+encodeURIComponent(uv)); | |
| 407 | + } | |
| 408 | + call.then(function(d){ | |
| 409 | + $('goBtn').disabled=false; | |
| 410 | + if(!d||d.ok!==true){ | |
| 411 | + txt('resState','error'); | |
| 412 | + kv([['error',(d&&d.error)||'request failed']]); | |
| 413 | + pushHist({kind:TAB,label:v,ok:false,detail:(d&&d.error)||'error',at:clock()}); | |
| 414 | + return; | |
| 415 | + } | |
| 416 | + if(TAB==='dns')showDns(d,v); | |
| 417 | + else if(TAB==='tcp')showTcp(d,v); | |
| 418 | + else showHttp(d,v); | |
| 419 | + }).catch(function(e){ | |
| 420 | + $('goBtn').disabled=false; | |
| 421 | + txt('resState','error'); | |
| 422 | + kv([['error',String(e.message||e)]]); | |
| 423 | + pushHist({kind:TAB,label:v,ok:false,detail:String(e.message||e),at:clock()}); | |
| 424 | + }); | |
| 425 | +} | |
| 426 | + | |
| 427 | +/* ---------- theme toggle (standalone only) ---------- */ | |
| 428 | +function toggleTheme(){ | |
| 429 | + var cur=(document.documentElement.getAttribute('data-theme')||'dark')==='light'?'dark':'light'; | |
| 430 | + document.documentElement.setAttribute('data-theme',cur); | |
| 431 | + try{localStorage.setItem('bot_theme',cur);}catch(e){} | |
| 432 | + try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:cur}));}catch(e){} | |
| 433 | +} | |
| 434 | + | |
| 435 | +$('goBtn').addEventListener('click',run); | |
| 436 | +$('inp').addEventListener('keydown',function(e){if(e.key==='Enter'){e.preventDefault();run();}}); | |
| 437 | +$('rfBtn').addEventListener('click',loadIfaces); | |
| 438 | +$('thBtn').addEventListener('click',toggleTheme); | |
| 439 | +$('tabDns').addEventListener('click',function(){setTab('dns');}); | |
| 440 | +$('tabTcp').addEventListener('click',function(){setTab('tcp');}); | |
| 441 | +$('tabHttp').addEventListener('click',function(){setTab('http');}); | |
| 442 | + | |
| 443 | +setTab('dns'); | |
| 444 | +loadIfaces(); | |
| 445 | +})(); | |
| 446 | +</script></body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..f705717 | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,454 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_NETCHECK_UI_HTML_H | |
| 3 | +#define SX_NETCHECK_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | |
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 9 | + "<title>netcheck</title>\n" | |
| 10 | + "\001\n" | |
| 11 | + "<style>\n" | |
| 12 | + "*{box-sizing:border-box}\n" | |
| 13 | + "html,body{margin:0;height:100%}\n" | |
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);\n" | |
| 15 | + " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}\n" | |
| 16 | + ".wrap{max-width:1080px;margin:0 auto;padding:16px 16px 32px}\n" | |
| 17 | + ".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}\n" | |
| 18 | + ".title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em}\n" | |
| 19 | + ".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;\n" | |
| 20 | + " background:var(--surface-2);color:var(--text-2);border:1px solid var(--line);\n" | |
| 21 | + " white-space:nowrap}\n" | |
| 22 | + ".sp{flex:1}\n" | |
| 23 | + ".icon{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | |
| 24 | + " background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | |
| 25 | + " border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit;\n" | |
| 26 | + " font-size:12px;font-weight:600}\n" | |
| 27 | + ".icon:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 28 | + ".icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;\n" | |
| 29 | + " stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}\n" | |
| 30 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:8px 16px;\n" | |
| 31 | + " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}\n" | |
| 32 | + ".btn:disabled{opacity:.55;cursor:default}\n" | |
| 33 | + ".btn.gh{background:transparent;color:var(--text);border:1px solid var(--line)}\n" | |
| 34 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | |
| 35 | + " padding:16px;margin-bottom:14px;box-shadow:var(--shadow)}\n" | |
| 36 | + ".card h2{margin:0 0 10px;font-size:11.5px;letter-spacing:.07em;text-transform:uppercase;\n" | |
| 37 | + " color:var(--text-2);font-weight:600}\n" | |
| 38 | + ".hint{color:var(--text-2);font-size:12px;margin:0 0 10px}\n" | |
| 39 | + ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px}\n" | |
| 40 | + ".kpi{background:var(--surface-2);border:1px solid var(--line);border-radius:10px;\n" | |
| 41 | + " padding:10px 12px}\n" | |
| 42 | + ".kpi .k{font-size:10.5px;color:var(--text-2);text-transform:uppercase;letter-spacing:.05em}\n" | |
| 43 | + ".kpi .v{font-size:15px;font-weight:700;font-family:var(--mono);margin-top:3px;\n" | |
| 44 | + " word-break:break-word}\n" | |
| 45 | + ".tb{width:100%;overflow-x:auto}\n" | |
| 46 | + "table{width:100%;border-collapse:collapse;font-size:13px}\n" | |
| 47 | + "th{text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em;\n" | |
| 48 | + " color:var(--text-2);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);\n" | |
| 49 | + " white-space:nowrap}\n" | |
| 50 | + "td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle;\n" | |
| 51 | + " word-break:break-word}\n" | |
| 52 | + "tr:last-child td{border-bottom:0}\n" | |
| 53 | + ".mo{font-family:var(--mono);font-size:12.5px}\n" | |
| 54 | + ".tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap;\n" | |
| 55 | + " background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)}\n" | |
| 56 | + ".tag.ok{background:rgba(48,209,88,.16);color:var(--green)}\n" | |
| 57 | + ".tag.warn{background:rgba(255,159,10,.16);color:var(--orange)}\n" | |
| 58 | + ".tag.bad{background:rgba(255,69,58,.16);color:var(--red)}\n" | |
| 59 | + ".tag.blue{background:rgba(10,132,255,.16);color:var(--blue)}\n" | |
| 60 | + ".tabs{display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap}\n" | |
| 61 | + ".tab{background:var(--surface-2);border:1px solid var(--line);color:var(--text-2);\n" | |
| 62 | + " border-radius:980px;padding:6px 14px;font-size:12.5px;font-weight:600;cursor:pointer;\n" | |
| 63 | + " font-family:inherit}\n" | |
| 64 | + ".tab.on{background:var(--blue);color:#fff;border-color:var(--blue)}\n" | |
| 65 | + ".inp{flex:1 1 240px;min-width:0;background:var(--input-bg);border:1px solid var(--line);\n" | |
| 66 | + " border-radius:10px;padding:10px 12px;color:var(--text);font-size:13.5px;\n" | |
| 67 | + " font-family:inherit}\n" | |
| 68 | + ".inp:focus{outline:2px solid var(--blue);outline-offset:-1px}\n" | |
| 69 | + ".inp.mo{font-family:var(--mono)}\n" | |
| 70 | + ".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}\n" | |
| 71 | + ".res{border-top:1px solid var(--line);padding-top:12px;margin-top:12px}\n" | |
| 72 | + ".res .hd{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px}\n" | |
| 73 | + ".res .big{font-size:16px;font-weight:700;font-family:var(--mono)}\n" | |
| 74 | + ".kv{display:grid;grid-template-columns:auto 1fr;gap:4px 12px;font-size:12.5px}\n" | |
| 75 | + ".kv .k{color:var(--text-2)}\n" | |
| 76 | + ".kv .v{font-family:var(--mono);word-break:break-all}\n" | |
| 77 | + "ul.hist{list-style:none;margin:0;padding:0}\n" | |
| 78 | + "ul.hist li{display:flex;align-items:center;gap:8px;padding:7px 2px;\n" | |
| 79 | + " border-bottom:1px solid var(--line);font-size:12.5px;flex-wrap:wrap}\n" | |
| 80 | + "ul.hist li:last-child{border-bottom:0}\n" | |
| 81 | + "ul.hist .t{font-family:var(--mono);flex:1 1 200px;min-width:0;word-break:break-all}\n" | |
| 82 | + "ul.hist .ms{font-family:var(--mono);color:var(--text-2);font-size:11.5px}\n" | |
| 83 | + ".spark{width:100%;height:56px;display:block;margin-top:10px}\n" | |
| 84 | + ".spark[hidden]{display:none}\n" | |
| 85 | + ".spark .ln{fill:none;stroke:var(--blue);stroke-width:1.6;\n" | |
| 86 | + " stroke-linecap:round;stroke-linejoin:round}\n" | |
| 87 | + ".spark .ax{stroke:var(--line);stroke-width:1}\n" | |
| 88 | + ".spark .dot{fill:var(--blue)}\n" | |
| 89 | + ".spark .dot.bad{fill:var(--red)}\n" | |
| 90 | + ".empty{color:var(--text-2);font-size:12.5px;padding:10px 0}\n" | |
| 91 | + "[hidden]{display:none!important}\n" | |
| 92 | + ".err{color:var(--red);font-size:12.5px}\n" | |
| 93 | + ".note{color:var(--text-2);font-size:12px;margin-top:8px}\n" | |
| 94 | + ".foot{color:var(--text-2);font-size:11.5px;margin-top:18px;line-height:1.6}\n" | |
| 95 | + ".foot code{font-family:var(--mono);font-size:11px;background:var(--surface-2);\n" | |
| 96 | + " padding:1px 5px;border-radius:5px;border:1px solid var(--line)}\n" | |
| 97 | + "@media(max-width:700px){.wrap{padding:10px 10px 24px}.card{padding:12px;border-radius:12px}\n" | |
| 98 | + " .title{font-size:17px}}\n" | |
| 99 | + "</style></head><body><div class=\"wrap\">\n" | |
| 100 | + "\n" | |
| 101 | + "<div class=\"top\">\n" | |
| 102 | + " <a href=\"/\" class=\"embed-hide\" style=\"color:var(--blue);text-decoration:none;font-weight:600\">←</a>\n" | |
| 103 | + " <h1 class=\"title\">netcheck</h1>\n" | |
| 104 | + " <span class=\"pill\" id=\"srcPill\">this node</span>\n" | |
| 105 | + " <span class=\"sp\"></span>\n" | |
| 106 | + " <button class=\"icon embed-hide\" id=\"thBtn\" title=\"Toggle appearance\" aria-label=\"Toggle appearance\">\n" | |
| 107 | + " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4.5\"/><path d=\"M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4\"/></svg>\n" | |
| 108 | + " </button>\n" | |
| 109 | + " <button class=\"icon\" id=\"rfBtn\" title=\"Refresh interfaces\" aria-label=\"Refresh interfaces\">\n" | |
| 110 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M20 11a8 8 0 1 0-2.3 5.7\"/><path d=\"M20 5v6h-6\"/></svg>\n" | |
| 111 | + " </button>\n" | |
| 112 | + "</div>\n" | |
| 113 | + "\n" | |
| 114 | + "<div class=\"card\">\n" | |
| 115 | + " <h2>Interfaces on this node</h2>\n" | |
| 116 | + " <p class=\"hint\">Addresses read from the node's own interface table. Nothing leaves the machine for this view.</p>\n" | |
| 117 | + " <div class=\"grid\" id=\"kpis\"></div>\n" | |
| 118 | + " <div class=\"tb\" style=\"margin-top:12px\">\n" | |
| 119 | + " <table>\n" | |
| 120 | + " <thead><tr><th>Interface</th><th>Address</th><th>Netmask</th><th>State</th></tr></thead>\n" | |
| 121 | + " <tbody id=\"ifrows\"></tbody>\n" | |
| 122 | + " </table>\n" | |
| 123 | + " </div>\n" | |
| 124 | + " <div class=\"empty\" id=\"ifEmpty\" hidden>No interfaces found.</div>\n" | |
| 125 | + " <div class=\"res\">\n" | |
| 126 | + " <h2 style=\"margin-top:0\">Configured DNS servers</h2>\n" | |
| 127 | + " <div class=\"row\" id=\"nsList\"></div>\n" | |
| 128 | + " </div>\n" | |
| 129 | + "</div>\n" | |
| 130 | + "\n" | |
| 131 | + "<div class=\"card\">\n" | |
| 132 | + " <h2>Run a check</h2>\n" | |
| 133 | + " <div class=\"tabs\" role=\"tablist\">\n" | |
| 134 | + " <button class=\"tab on\" id=\"tabDns\" role=\"tab\" data-tab=\"dns\">DNS</button>\n" | |
| 135 | + " <button class=\"tab\" id=\"tabTcp\" role=\"tab\" data-tab=\"tcp\">TCP</button>\n" | |
| 136 | + " <button class=\"tab\" id=\"tabHttp\" role=\"tab\" data-tab=\"http\">HTTP</button>\n" | |
| 137 | + " </div>\n" | |
| 138 | + " <div class=\"row\">\n" | |
| 139 | + " <input id=\"inp\" class=\"inp mo\" placeholder=\"example.com\" autocomplete=\"off\" spellcheck=\"false\" aria-label=\"Target\">\n" | |
| 140 | + " <input id=\"port\" class=\"inp mo\" type=\"number\" min=\"1\" max=\"65535\" step=\"1\"\n" | |
| 141 | + " value=\"443\" style=\"width:110px;display:none\" placeholder=\"port\" aria-label=\"Port\">\n" | |
| 142 | + " <button class=\"btn\" id=\"goBtn\">Check</button>\n" | |
| 143 | + " </div>\n" | |
| 144 | + " <p class=\"note\" id=\"tabNote\">Resolves a name to its addresses. Uses the node's resolver with a 3 second deadline.</p>\n" | |
| 145 | + " <div class=\"res\" id=\"resBox\">\n" | |
| 146 | + " <div class=\"hd\"><span class=\"big\" id=\"resState\">idle</span><span id=\"resTag\"></span></div>\n" | |
| 147 | + " <div class=\"kv\" id=\"resKv\"></div>\n" | |
| 148 | + " <div class=\"note\" id=\"resNote\"></div>\n" | |
| 149 | + " <svg class=\"spark\" id=\"spark\" viewBox=\"0 0 320 56\" preserveAspectRatio=\"none\"\n" | |
| 150 | + " aria-label=\"TCP latency history\" hidden></svg>\n" | |
| 151 | + " </div>\n" | |
| 152 | + "</div>\n" | |
| 153 | + "\n" | |
| 154 | + "<div class=\"card\">\n" | |
| 155 | + " <h2>History <span class=\"pill\" id=\"histCount\">0</span></h2>\n" | |
| 156 | + " <p class=\"hint\">Kept in this page only — nothing is written to disk.</p>\n" | |
| 157 | + " <ul class=\"hist\" id=\"hist\"><li class=\"empty\">No checks yet this session.</li></ul>\n" | |
| 158 | + "</div>\n" | |
| 159 | + "\n" | |
| 160 | + "<p class=\"foot\">\n" | |
| 161 | + " netcheck runs on the node and makes only the outbound connections you ask for: a DNS lookup,\n" | |
| 162 | + " a TCP connect, or one <code>HEAD</code> request over plain HTTP. There is no TLS library in the\n" | |
| 163 | + " binary, so an <code>https://</code> target is checked as a TCP connect to port 443 and reported\n" | |
| 164 | + " as <code>tls: not_checked</code>. Response bodies are never read, and redirects are never followed.\n" | |
| 165 | + " Every action sits behind node authentication.\n" | |
| 166 | + "</p>\n" | |
| 167 | + "</div>\n" | |
| 168 | + "<script>\n" | |
| 169 | + "(function(){\n" | |
| 170 | + "\"use strict\";\n" | |
| 171 | + "var q=new URLSearchParams(location.search);\n" | |
| 172 | + "var node=q.get('node')||'';\n" | |
| 173 | + "var sid=q.get('id')||'';\n" | |
| 174 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | |
| 175 | + " localStorage.getItem('bot_active_pwd')||'';\n" | |
| 176 | + "var HUB=q.get('plugin')||'';\n" | |
| 177 | + "\n" | |
| 178 | + "/* Two call routes, and getting this wrong is the most common plugin bug:\n" | |
| 179 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_netcheck&node=..)\n" | |
| 180 | + " * -> call the hub proxy back: /plugins?plugin=plugin_netcheck&action=..\n" | |
| 181 | + " * opened directly on the node\n" | |
| 182 | + " * -> the plugin itself is the route: /plugin_netcheck?action=..\n" | |
| 183 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | |
| 184 | + "function api(action,params){\n" | |
| 185 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_netcheck')\n" | |
| 186 | + " +'?action='+encodeURIComponent(action)\n" | |
| 187 | + " +(params||'')\n" | |
| 188 | + " +(node?'&node='+encodeURIComponent(node):'')\n" | |
| 189 | + " +(sid?'&id='+encodeURIComponent(sid):'')\n" | |
| 190 | + " +(pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | |
| 191 | + " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}})\n" | |
| 192 | + " .then(function(r){return r.json().then(function(d){if(!r.ok)throw new Error('HTTP '+r.status);return d;});});\n" | |
| 193 | + "}\n" | |
| 194 | + "\n" | |
| 195 | + "function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){\n" | |
| 196 | + " return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}\n" | |
| 197 | + "function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;}\n" | |
| 198 | + "function $(id){return document.getElementById(id);}\n" | |
| 199 | + "\n" | |
| 200 | + "var TAB='dns';\n" | |
| 201 | + "var HIST=[]; /* last 20 checks, in-page only */\n" | |
| 202 | + "var TCPMS=[]; /* tcp latency samples for the sparkline */\n" | |
| 203 | + "\n" | |
| 204 | + "var NOTE={\n" | |
| 205 | + " dns:'Resolves a name to its addresses. Uses the node\\'s resolver with a 3 second deadline.',\n" | |
| 206 | + " tcp:'Measures a TCP connect. Three samples, 3 second deadline each, reported as min/avg/max.',\n" | |
| 207 | + " http:'Sends one HEAD request over plain TCP. Status line and headers only, body never read, no redirects.'\n" | |
| 208 | + "};\n" | |
| 209 | + "var PH={dns:'example.com',tcp:'example.com',http:'http://example.com'};\n" | |
| 210 | + "\n" | |
| 211 | + "function setTab(t){\n" | |
| 212 | + " TAB=t;\n" | |
| 213 | + " ['dns','tcp','http'].forEach(function(k){\n" | |
| 214 | + " var b=$('tab'+k.charAt(0).toUpperCase()+k.slice(1));\n" | |
| 215 | + " if(b)b.className='tab'+(k===t?' on':'');\n" | |
| 216 | + " });\n" | |
| 217 | + " $('port').style.display=(t==='tcp')?'':'none';\n" | |
| 218 | + " $('inp').placeholder=PH[t];\n" | |
| 219 | + " txt('tabNote',NOTE[t]);\n" | |
| 220 | + "}\n" | |
| 221 | + "\n" | |
| 222 | + "/* ---------- interfaces ---------- */\n" | |
| 223 | + "function renderIfaces(d){\n" | |
| 224 | + " var rows=$('ifrows'),kp=$('kpis'),ns=$('nsList');\n" | |
| 225 | + " var list=(d&&d.interfaces)||[];\n" | |
| 226 | + " var upn=0,glob=0,lo=0,i;\n" | |
| 227 | + " var h='';\n" | |
| 228 | + " for(i=0;i<list.length;i++){\n" | |
| 229 | + " var f=list[i];\n" | |
| 230 | + " if(f.up)upn++;\n" | |
| 231 | + " if(!f.loopback&&(f.family===4||f.addr!=='::1'))glob++;\n" | |
| 232 | + " if(f.loopback)lo++;\n" | |
| 233 | + " h+='<tr><td class=\"mo\">'+esc(f.name)+'</td>'\n" | |
| 234 | + " +'<td class=\"mo\">'+esc(f.address)+'</td>'\n" | |
| 235 | + " +'<td class=\"mo\">'+esc(f.netmask||'-')+'</td>'\n" | |
| 236 | + " +'<td>'+(f.up?'<span class=\"tag ok\">up</span>':'<span class=\"tag bad\">down</span>')\n" | |
| 237 | + " +(f.loopback?' <span class=\"tag\">loopback</span>':'')\n" | |
| 238 | + " +(f.family===6?' <span class=\"tag\">ipv6</span>':'')+'</td></tr>';\n" | |
| 239 | + " }\n" | |
| 240 | + " rows.innerHTML=h;\n" | |
| 241 | + " /* show the empty message only when there really are no rows */\n" | |
| 242 | + " if(list.length){$('ifEmpty').setAttribute('hidden','');}\n" | |
| 243 | + " else{$('ifEmpty').removeAttribute('hidden');}\n" | |
| 244 | + " var nsr=(d&&d.nameservers)||[];\n" | |
| 245 | + " var kh='';\n" | |
| 246 | + " kh+='<div class=\"kpi\"><div class=\"k\">Interfaces</div><div class=\"v\">'+list.length+'</div></div>';\n" | |
| 247 | + " kh+='<div class=\"kpi\"><div class=\"k\">Up</div><div class=\"v\">'+upn+'</div></div>';\n" | |
| 248 | + " kh+='<div class=\"kpi\"><div class=\"k\">Loopback</div><div class=\"v\">'+lo+'</div></div>';\n" | |
| 249 | + " kh+='<div class=\"kpi\"><div class=\"k\">DNS servers</div><div class=\"v\">'+nsr.length+'</div></div>';\n" | |
| 250 | + " kp.innerHTML=kh;\n" | |
| 251 | + " if(!nsr.length){ns.innerHTML='<span class=\"empty\">None configured.</span>';}\n" | |
| 252 | + " else{var nh='';for(i=0;i<nsr.length;i++)nh+='<span class=\"tag blue\">'+esc(nsr[i])+'</span>';ns.innerHTML=nh;}\n" | |
| 253 | + " txt('srcPill',(d&&d.count!=null)?(list.length+' iface'+(list.length===1?'':'s')):'this node');\n" | |
| 254 | + "}\n" | |
| 255 | + "\n" | |
| 256 | + "function loadIfaces(){\n" | |
| 257 | + " api('ifaces','').then(renderIfaces).catch(function(e){\n" | |
| 258 | + " $('ifrows').innerHTML='';\n" | |
| 259 | + " $('kpis').innerHTML='<div class=\"kpi\"><div class=\"k\">Error</div><div class=\"v\">'+esc(String(e.message||e))+'</div></div>';\n" | |
| 260 | + " $('ifEmpty').removeAttribute('hidden');\n" | |
| 261 | + " });\n" | |
| 262 | + "}\n" | |
| 263 | + "\n" | |
| 264 | + "/* ---------- sparkline ---------- */\n" | |
| 265 | + "function drawSpark(){\n" | |
| 266 | + " var svg=$('spark');\n" | |
| 267 | + " /* `hidden` is an HTMLElement property, not an SVGElement one, so it has to\n" | |
| 268 | + " * be set as an attribute or the browser keeps the one from the markup. */\n" | |
| 269 | + " if(TAB!=='tcp'||TCPMS.length<2){svg.setAttribute('hidden','');return;}\n" | |
| 270 | + " svg.removeAttribute('hidden');\n" | |
| 271 | + " var W=320,H=56,PAD=6;\n" | |
| 272 | + " var vals=TCPMS.slice(-20);\n" | |
| 273 | + " var good=vals.filter(function(v){return v>=0;});\n" | |
| 274 | + " var mx=good.length?Math.max.apply(null,good):0;\n" | |
| 275 | + " var mn=good.length?Math.min.apply(null,good):0;\n" | |
| 276 | + " /* A flat series has no range to normalise against. Plot it on the middle\n" | |
| 277 | + " * line instead of the floor, otherwise \"every connect was instant\" reads\n" | |
| 278 | + " * like \"every connect hit the deadline\". */\n" | |
| 279 | + " var flat=(mx-mn)<1;\n" | |
| 280 | + " var scale=flat?1:(mx-mn);\n" | |
| 281 | + " var n=vals.length;\n" | |
| 282 | + " var pts=[],i,x,y;\n" | |
| 283 | + " for(i=0;i<n;i++){\n" | |
| 284 | + " x=PAD+(i*(W-2*PAD))/(n-1);\n" | |
| 285 | + " var v=vals[i];\n" | |
| 286 | + " if(v<0){y=H-PAD;}\n" | |
| 287 | + " else if(flat){y=(H-2*PAD)/2+PAD;}\n" | |
| 288 | + " else{y=H-PAD-((H-2*PAD)*((v-mn)/scale));}\n" | |
| 289 | + " pts.push([x,y,v]);\n" | |
| 290 | + " }\n" | |
| 291 | + " var out='<line class=\"ax\" x1=\"0\" y1=\"'+(H-PAD)+'\" x2=\"'+W+'\" y2=\"'+(H-PAD)+'\"/>';\n" | |
| 292 | + " var d='';\n" | |
| 293 | + " for(i=0;i<pts.length;i++){\n" | |
| 294 | + " if(pts[i][2]<0)continue;\n" | |
| 295 | + " d+=(d?'L':'M')+pts[i][0].toFixed(1)+' '+pts[i][1].toFixed(1);\n" | |
| 296 | + " }\n" | |
| 297 | + " if(d)out+='<path class=\"ln\" d=\"'+d+'\"/>';\n" | |
| 298 | + " for(i=0;i<pts.length;i++){\n" | |
| 299 | + " out+='<circle class=\"dot'+(pts[i][2]<0?' bad':'')+'\" cx=\"'+pts[i][0].toFixed(1)\n" | |
| 300 | + " +'\" cy=\"'+pts[i][1].toFixed(1)+'\" r=\"2.4\"/>';\n" | |
| 301 | + " }\n" | |
| 302 | + " svg.innerHTML=out;\n" | |
| 303 | + "}\n" | |
| 304 | + "\n" | |
| 305 | + "/* ---------- history ---------- */\n" | |
| 306 | + "function pushHist(item){\n" | |
| 307 | + " HIST.unshift(item);\n" | |
| 308 | + " if(HIST.length>20)HIST.pop();\n" | |
| 309 | + " renderHist();\n" | |
| 310 | + "}\n" | |
| 311 | + "function renderHist(){\n" | |
| 312 | + " var ul=$('hist');\n" | |
| 313 | + " txt('histCount',String(HIST.length));\n" | |
| 314 | + " if(!HIST.length){ul.innerHTML='<li class=\"empty\">No checks yet this session.</li>';return;}\n" | |
| 315 | + " var h='';\n" | |
| 316 | + " for(var i=0;i<HIST.length;i++){\n" | |
| 317 | + " var it=HIST[i];\n" | |
| 318 | + " h+='<li><span class=\"tag '+(it.ok?'ok':'bad')+'\">'+esc(it.kind)+'</span>'\n" | |
| 319 | + " +'<span class=\"t\">'+esc(it.label)+'</span>'\n" | |
| 320 | + " +'<span class=\"ms\">'+esc(it.detail)+'</span>'\n" | |
| 321 | + " +'<span class=\"ms\">'+esc(it.at)+'</span></li>';\n" | |
| 322 | + " }\n" | |
| 323 | + " ul.innerHTML=h;\n" | |
| 324 | + "}\n" | |
| 325 | + "\n" | |
| 326 | + "/* ---------- result rendering ---------- */\n" | |
| 327 | + "function kv(pairs){\n" | |
| 328 | + " var h='';\n" | |
| 329 | + " for(var i=0;i<pairs.length;i++){\n" | |
| 330 | + " h+='<div class=\"k\"><span class=\"k\">'+esc(pairs[i][0])+'</span></div>'\n" | |
| 331 | + " +'<div class=\"v\">'+esc(pairs[i][1]==null?'-':String(pairs[i][1]))+'</div>';\n" | |
| 332 | + " }\n" | |
| 333 | + " $('resKv').innerHTML=h;\n" | |
| 334 | + "}\n" | |
| 335 | + "\n" | |
| 336 | + "function showDns(d,target){\n" | |
| 337 | + " var ok=d.resolved===true;\n" | |
| 338 | + " txt('resState',ok?'resolved':'not resolved');\n" | |
| 339 | + " $('resTag').innerHTML=ok?'<span class=\"tag ok\">ok</span>':'<span class=\"tag bad\">'+esc(d.timeout?'timeout':'fail')+'</span>';\n" | |
| 340 | + " var pairs=[['host',d.host],['latency',(d.latency_ms==null?'-':d.latency_ms+' ms')],\n" | |
| 341 | + " ['answers',d.count],['deadline',d.timeout_ms+' ms']];\n" | |
| 342 | + " if(d.results&&d.results.length){\n" | |
| 343 | + " var addrs=[];\n" | |
| 344 | + " for(var i=0;i<d.results.length;i++)addrs.push(d.results[i].address);\n" | |
| 345 | + " pairs.push(['addresses',addrs.join(', ')]);\n" | |
| 346 | + " }\n" | |
| 347 | + " kv(pairs);\n" | |
| 348 | + " txt('resNote',ok?'':'The resolver returned no record for this name.');\n" | |
| 349 | + " pushHist({kind:'dns',label:target,ok:ok,detail:(d.count||0)+' addr',at:clock()});\n" | |
| 350 | + "}\n" | |
| 351 | + "\n" | |
| 352 | + "function showTcp(d,target){\n" | |
| 353 | + " var open=d.open===true;\n" | |
| 354 | + " var last=(d.samples&&d.samples.length)?d.samples[d.samples.length-1]:null;\n" | |
| 355 | + " TCPMS.push(typeof last==='number'?last:-1);\n" | |
| 356 | + " if(TCPMS.length>20)TCPMS.shift();\n" | |
| 357 | + " txt('resState',open?'open':(d.status==='timeout'?'timeout':'closed'));\n" | |
| 358 | + " $('resTag').innerHTML=open?'<span class=\"tag ok\">reachable</span>'\n" | |
| 359 | + " :'<span class=\"tag bad\">'+esc(d.status||'closed')+'</span>';\n" | |
| 360 | + " var pairs=[['target',d.host+':'+d.port],['resolved to',d.address],\n" | |
| 361 | + " ['avg',(d.avg_ms==null?'-':d.avg_ms+' ms')],\n" | |
| 362 | + " ['min',(d.min_ms==null?'-':d.min_ms+' ms')],\n" | |
| 363 | + " ['max',(d.max_ms==null?'-':d.max_ms+' ms')],\n" | |
| 364 | + " ['samples',(d.samples||[]).map(function(s){return s==null?'timeout':s+' ms';}).join(', ')]];\n" | |
| 365 | + " kv(pairs);\n" | |
| 366 | + " txt('resNote',open?'Three connects succeeded against the first resolved address.'\n" | |
| 367 | + " :'The connect did not complete inside the deadline.');\n" | |
| 368 | + " drawSpark();\n" | |
| 369 | + " pushHist({kind:'tcp',label:d.host+':'+d.port,ok:open,\n" | |
| 370 | + " detail:open?((d.avg_ms==null?'-':d.avg_ms+' ms avg')):d.status,at:clock()});\n" | |
| 371 | + "}\n" | |
| 372 | + "\n" | |
| 373 | + "function showHttp(d,target){\n" | |
| 374 | + " var ok=d.reachable===true&&d.status!=null&&d.status<400;\n" | |
| 375 | + " txt('resState',d.status==null?(d.reachable?'connected':'unreachable'):('HTTP '+d.status));\n" | |
| 376 | + " $('resTag').innerHTML=d.status==null\n" | |
| 377 | + " ?(d.reachable?'<span class=\"tag warn\">no status line</span>':'<span class=\"tag bad\">unreachable</span>')\n" | |
| 378 | + " :(ok?'<span class=\"tag ok\">reachable</span>':'<span class=\"tag bad\">status '+esc(d.status)+'</span>');\n" | |
| 379 | + " var pairs=[['url',d.url],['host',d.host+':'+d.port],['path',d.path],\n" | |
| 380 | + " ['connect',(d.connect_ms==null?'-':d.connect_ms+' ms')],\n" | |
| 381 | + " ['status',(d.status==null?'-':d.status+' '+(d.status_text||''))],\n" | |
| 382 | + " ['headers',d.header_lines],['body','0 bytes (HEAD)'],\n" | |
| 383 | + " ['tls',d.tls]];\n" | |
| 384 | + " kv(pairs);\n" | |
| 385 | + " txt('resNote',d.note||'');\n" | |
| 386 | + " pushHist({kind:'http',label:d.url,ok:ok,detail:(d.status==null?'no status':String(d.status)),at:clock()});\n" | |
| 387 | + "}\n" | |
| 388 | + "\n" | |
| 389 | + "function clock(){\n" | |
| 390 | + " var d=new Date();\n" | |
| 391 | + " return d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit',second:'2-digit'});\n" | |
| 392 | + "}\n" | |
| 393 | + "\n" | |
| 394 | + "function run(){\n" | |
| 395 | + " var v=$('inp').value.trim();\n" | |
| 396 | + " if(!v){txt('resState','enter a target');return;}\n" | |
| 397 | + " txt('resState','running...');\n" | |
| 398 | + " $('resKv').innerHTML='';\n" | |
| 399 | + " $('resNote').textContent='';\n" | |
| 400 | + " $('goBtn').disabled=true;\n" | |
| 401 | + " var p='';\n" | |
| 402 | + " var call;\n" | |
| 403 | + " if(TAB==='dns'){call=api('dns','&host='+encodeURIComponent(v));}\n" | |
| 404 | + " else if(TAB==='tcp'){\n" | |
| 405 | + " var pt=$('port').value.trim();\n" | |
| 406 | + " if(!pt){$('goBtn').disabled=false;txt('resState','port required');return;}\n" | |
| 407 | + " call=api('tcp','&host='+encodeURIComponent(v)+'&port='+encodeURIComponent(pt));\n" | |
| 408 | + " } else {\n" | |
| 409 | + " var uv=v;\n" | |
| 410 | + " if(!/^https?:\\/\\//i.test(uv))uv='http://'+uv;\n" | |
| 411 | + " call=api('http','&url='+encodeURIComponent(uv));\n" | |
| 412 | + " }\n" | |
| 413 | + " call.then(function(d){\n" | |
| 414 | + " $('goBtn').disabled=false;\n" | |
| 415 | + " if(!d||d.ok!==true){\n" | |
| 416 | + " txt('resState','error');\n" | |
| 417 | + " kv([['error',(d&&d.error)||'request failed']]);\n" | |
| 418 | + " pushHist({kind:TAB,label:v,ok:false,detail:(d&&d.error)||'error',at:clock()});\n" | |
| 419 | + " return;\n" | |
| 420 | + " }\n" | |
| 421 | + " if(TAB==='dns')showDns(d,v);\n" | |
| 422 | + " else if(TAB==='tcp')showTcp(d,v);\n" | |
| 423 | + " else showHttp(d,v);\n" | |
| 424 | + " }).catch(function(e){\n" | |
| 425 | + " $('goBtn').disabled=false;\n" | |
| 426 | + " txt('resState','error');\n" | |
| 427 | + " kv([['error',String(e.message||e)]]);\n" | |
| 428 | + " pushHist({kind:TAB,label:v,ok:false,detail:String(e.message||e),at:clock()});\n" | |
| 429 | + " });\n" | |
| 430 | + "}\n" | |
| 431 | + "\n" | |
| 432 | + "/* ---------- theme toggle (standalone only) ---------- */\n" | |
| 433 | + "function toggleTheme(){\n" | |
| 434 | + " var cur=(document.documentElement.getAttribute('data-theme')||'dark')==='light'?'dark':'light';\n" | |
| 435 | + " document.documentElement.setAttribute('data-theme',cur);\n" | |
| 436 | + " try{localStorage.setItem('bot_theme',cur);}catch(e){}\n" | |
| 437 | + " try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:cur}));}catch(e){}\n" | |
| 438 | + "}\n" | |
| 439 | + "\n" | |
| 440 | + "$('goBtn').addEventListener('click',run);\n" | |
| 441 | + "$('inp').addEventListener('keydown',function(e){if(e.key==='Enter'){e.preventDefault();run();}});\n" | |
| 442 | + "$('rfBtn').addEventListener('click',loadIfaces);\n" | |
| 443 | + "$('thBtn').addEventListener('click',toggleTheme);\n" | |
| 444 | + "$('tabDns').addEventListener('click',function(){setTab('dns');});\n" | |
| 445 | + "$('tabTcp').addEventListener('click',function(){setTab('tcp');});\n" | |
| 446 | + "$('tabHttp').addEventListener('click',function(){setTab('http');});\n" | |
| 447 | + "\n" | |
| 448 | + "setTab('dns');\n" | |
| 449 | + "loadIfaces();\n" | |
| 450 | + "})();\n" | |
| 451 | + "</script>\002</body></html>\n" | |
| 452 | + ; | |
| 453 | + | |
| 454 | +#endif /* SX_NETCHECK_UI_HTML_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..3e14562 | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,320 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport checks for the plugin_netcheck panel. | |
| 3 | + | |
| 4 | +Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts | |
| 5 | +the throwaway TCP/HTTP listeners from tests/mockd.py so the panel has something | |
| 6 | +real to talk to, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in | |
| 7 | +both themes, and asserts: | |
| 8 | + | |
| 9 | + * no console error and no page error at any viewport | |
| 10 | + * scrollWidth <= innerWidth (no horizontal overflow) | |
| 11 | + * the interface table renders from the fixture and the DNS row appears | |
| 12 | + * a DNS / TCP / HTTP check each produce a result and land in the history | |
| 13 | + * the TCP sparkline appears once there are two or more samples | |
| 14 | + * screenshots land in docs/ for the README | |
| 15 | + | |
| 16 | +Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays | |
| 17 | +dependency-free. | |
| 18 | + | |
| 19 | + python3 tests/e2e.py # run if Playwright is available | |
| 20 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 21 | +""" | |
| 22 | + | |
| 23 | +import argparse | |
| 24 | +import http.server | |
| 25 | +import os | |
| 26 | +import socketserver | |
| 27 | +import subprocess | |
| 28 | +import sys | |
| 29 | +import threading | |
| 30 | +import time | |
| 31 | +from urllib.parse import urlparse | |
| 32 | + | |
| 33 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 34 | +BIN = os.path.join(ROOT, "plugin_netcheck") | |
| 35 | +DOCS = os.path.join(ROOT, "docs") | |
| 36 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 37 | +THEMES = ["dark", "light"] | |
| 38 | + | |
| 39 | +IF_FIX = ("lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1," | |
| 40 | + "lo|::1|||6|1," | |
| 41 | + "tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1," | |
| 42 | + "wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0") | |
| 43 | +DNS_FIX = "example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1" | |
| 44 | + | |
| 45 | +MOCK_BASE = 18090 | |
| 46 | + | |
| 47 | + | |
| 48 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 49 | + def _run(self, method): | |
| 50 | + u = urlparse(self.path) | |
| 51 | + length = int(self.headers.get("Content-Length") or 0) | |
| 52 | + body = self.rfile.read(length) if length else b"" | |
| 53 | + env = dict(os.environ) | |
| 54 | + env["QUERY_STRING"] = u.query | |
| 55 | + env["REQUEST_METHOD"] = method | |
| 56 | + env["NETCHECK_MOCK_IFACES"] = IF_FIX | |
| 57 | + env["NETCHECK_MOCK_DNS"] = DNS_FIX | |
| 58 | + env.pop("BOT_PASSWORD", None) | |
| 59 | + env["CONTENT_LENGTH"] = str(len(body)) | |
| 60 | + out = subprocess.run( | |
| 61 | + [BIN], input=body, capture_output=True, env=env, timeout=60 | |
| 62 | + ).stdout | |
| 63 | + sep = out.find(b"\r\n\r\n") | |
| 64 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 65 | + payload = out[sep + 4:] if sep >= 0 else out | |
| 66 | + status = 200 | |
| 67 | + ctype = "application/json; charset=utf-8" | |
| 68 | + for line in headers.splitlines(): | |
| 69 | + low = line.lower() | |
| 70 | + if low.startswith("content-type:"): | |
| 71 | + ctype = line.split(":", 1)[1].strip() | |
| 72 | + elif low.startswith("status:"): | |
| 73 | + try: | |
| 74 | + status = int(line.split(":", 1)[1].strip().split()[0]) | |
| 75 | + except (IndexError, ValueError): | |
| 76 | + status = 200 | |
| 77 | + self.send_response(status) | |
| 78 | + self.send_header("Content-Type", ctype) | |
| 79 | + self.send_header("Cache-Control", "no-store") | |
| 80 | + self.send_header("Content-Length", str(len(payload))) | |
| 81 | + self.end_headers() | |
| 82 | + self.wfile.write(payload) | |
| 83 | + | |
| 84 | + def do_GET(self): # noqa: N802 | |
| 85 | + self._run("GET") | |
| 86 | + | |
| 87 | + def do_POST(self): # noqa: N802 | |
| 88 | + self._run("POST") | |
| 89 | + | |
| 90 | + def log_message(self, *_a): | |
| 91 | + pass | |
| 92 | + | |
| 93 | + | |
| 94 | +def main(): | |
| 95 | + ap = argparse.ArgumentParser() | |
| 96 | + ap.add_argument("--strict", action="store_true") | |
| 97 | + args = ap.parse_args() | |
| 98 | + | |
| 99 | + if not os.path.exists(BIN): | |
| 100 | + print("plugin_netcheck is not built; run make first", file=sys.stderr) | |
| 101 | + return 1 | |
| 102 | + | |
| 103 | + try: | |
| 104 | + from playwright.sync_api import sync_playwright | |
| 105 | + except Exception: | |
| 106 | + if args.strict: | |
| 107 | + print("playwright is not installed", file=sys.stderr) | |
| 108 | + return 2 | |
| 109 | + print("playwright not available - skipping e2e (offline suite still runs)") | |
| 110 | + return 0 | |
| 111 | + | |
| 112 | + os.makedirs(DOCS, exist_ok=True) | |
| 113 | + | |
| 114 | + # the listeners the panel will probe | |
| 115 | + mock = subprocess.Popen( | |
| 116 | + [sys.executable, os.path.join(ROOT, "tests", "mockd.py"), str(MOCK_BASE)], | |
| 117 | + stdout=subprocess.PIPE, stderr=subprocess.PIPE, | |
| 118 | + ) | |
| 119 | + ready = False | |
| 120 | + for _ in range(60): | |
| 121 | + line = mock.stdout.readline() | |
| 122 | + if b"READY" in line: | |
| 123 | + ready = True | |
| 124 | + break | |
| 125 | + time.sleep(0.05) | |
| 126 | + if not ready: | |
| 127 | + print("mock listeners never came up", file=sys.stderr) | |
| 128 | + mock.kill() | |
| 129 | + return 1 | |
| 130 | + | |
| 131 | + open_port = MOCK_BASE + 1 | |
| 132 | + | |
| 133 | + socketserver.TCPServer.allow_reuse_address = True | |
| 134 | + try: | |
| 135 | + httpd = socketserver.TCPServer(("127.0.0.1", 8099), Handler) | |
| 136 | + except OSError as exc: | |
| 137 | + print("could not bind 8099: %s" % exc, file=sys.stderr) | |
| 138 | + mock.kill() | |
| 139 | + return 1 | |
| 140 | + th = threading.Thread(target=httpd.serve_forever, daemon=True) | |
| 141 | + th.start() | |
| 142 | + | |
| 143 | + base = "http://127.0.0.1:8099/" | |
| 144 | + errors = [] | |
| 145 | + shots = 0 | |
| 146 | + | |
| 147 | + with sync_playwright() as p: | |
| 148 | + browser = p.chromium.launch() | |
| 149 | + for w, h in VIEWPORTS: | |
| 150 | + for theme in THEMES: | |
| 151 | + page = browser.new_page(viewport={"width": w, "height": h}) | |
| 152 | + console = [] | |
| 153 | + page.on("console", lambda m: console.append(m.type + ": " + m.text) | |
| 154 | + if m.type in ("error",) else None) | |
| 155 | + page.on("pageerror", lambda e: console.append("pageerror: %s" % e)) | |
| 156 | + page.goto(base + "?theme=" + theme, wait_until="networkidle") | |
| 157 | + page.wait_for_selector("#ifrows tr", timeout=15000) | |
| 158 | + | |
| 159 | + # the fixture must render four interface rows and one nameserver | |
| 160 | + rows = page.eval_on_selector_all("#ifrows tr", "els => els.length") | |
| 161 | + if rows != 4: | |
| 162 | + errors.append("%dx%d %s: expected 4 iface rows, got %s" | |
| 163 | + % (w, h, theme, rows)) | |
| 164 | + ns = page.eval_on_selector_all("#nsList .tag", "els => els.length") | |
| 165 | + if ns < 1: | |
| 166 | + errors.append("%dx%d %s: no nameserver chips" % (w, h, theme)) | |
| 167 | + | |
| 168 | + # --- DNS tab --- | |
| 169 | + page.fill("#inp", "example.com") | |
| 170 | + page.click("#goBtn") | |
| 171 | + page.wait_for_selector("#resKv .v", timeout=15000) | |
| 172 | + state = page.text_content("#resState") or "" | |
| 173 | + if "resolved" not in state: | |
| 174 | + errors.append("%dx%d %s: dns did not resolve (%s)" | |
| 175 | + % (w, h, theme, state.strip())) | |
| 176 | + | |
| 177 | + # --- TCP tab, three times so the sparkline has samples --- | |
| 178 | + page.click("#tabTcp") | |
| 179 | + page.fill("#inp", "target") | |
| 180 | + page.fill("#port", str(open_port)) | |
| 181 | + for _ in range(3): | |
| 182 | + page.click("#goBtn") | |
| 183 | + page.wait_for_selector("#resKv .v", timeout=15000) | |
| 184 | + disp = page.evaluate( | |
| 185 | + "() => getComputedStyle(document.getElementById('spark')).display") | |
| 186 | + if disp == "none": | |
| 187 | + errors.append("%dx%d %s: sparkline stayed hidden after 3 samples" | |
| 188 | + % (w, h, theme)) | |
| 189 | + dots = page.eval_on_selector_all("#spark circle", "els => els.length") | |
| 190 | + if dots < 2: | |
| 191 | + errors.append("%dx%d %s: sparkline has %s points" % (w, h, theme, dots)) | |
| 192 | + hist = page.eval_on_selector_all("#hist li", "els => els.length") | |
| 193 | + if hist < 4: | |
| 194 | + errors.append("%dx%d %s: history has %s entries, want >=4" | |
| 195 | + % (w, h, theme, hist)) | |
| 196 | + | |
| 197 | + # --- HTTP tab --- | |
| 198 | + page.click("#tabHttp") | |
| 199 | + page.fill("#inp", "http://target:%d/index.html" % open_port) | |
| 200 | + page.click("#goBtn") | |
| 201 | + page.wait_for_selector("#resKv .v", timeout=15000) | |
| 202 | + state = (page.text_content("#resState") or "").strip() | |
| 203 | + if "200" not in state: | |
| 204 | + errors.append("%dx%d %s: http did not report 200 (%s)" | |
| 205 | + % (w, h, theme, state)) | |
| 206 | + | |
| 207 | + # land on the TCP tab so the screenshot shows the sparkline with | |
| 208 | + # samples in it - a chart nobody can see proves nothing. One of | |
| 209 | + # the samples is taken against a closed port so the series is not | |
| 210 | + # perfectly flat: a flat line on a chart is ambiguous, and a | |
| 211 | + # screenshot that cannot be read is not evidence. | |
| 212 | + page.click("#tabTcp") | |
| 213 | + page.fill("#inp", "127.0.0.1") | |
| 214 | + page.fill("#port", "1") | |
| 215 | + page.click("#goBtn") | |
| 216 | + page.wait_for_selector("#resKv .v", timeout=15000) | |
| 217 | + page.fill("#inp", "target") | |
| 218 | + page.fill("#port", str(open_port)) | |
| 219 | + page.click("#goBtn") | |
| 220 | + page.wait_for_selector("#resKv .v", timeout=15000) | |
| 221 | + spark_disp = page.evaluate( | |
| 222 | + "() => getComputedStyle(document.getElementById('spark')).display") | |
| 223 | + if spark_disp == "none": | |
| 224 | + errors.append("%dx%d %s: sparkline hidden on the tcp tab" | |
| 225 | + % (w, h, theme)) | |
| 226 | + svg_h = page.evaluate( | |
| 227 | + "() => document.getElementById('spark').getBoundingClientRect().height") | |
| 228 | + if svg_h < 20: | |
| 229 | + errors.append("%dx%d %s: sparkline renders only %s px tall" | |
| 230 | + % (w, h, theme, svg_h)) | |
| 231 | + | |
| 232 | + # --- layout: no horizontal overflow anywhere --- | |
| 233 | + overflow = page.evaluate( | |
| 234 | + "() => document.documentElement.scrollWidth - window.innerWidth") | |
| 235 | + if overflow > 0: | |
| 236 | + errors.append("%dx%d %s: horizontal overflow %spx" | |
| 237 | + % (w, h, theme, overflow)) | |
| 238 | + body_over = page.evaluate( | |
| 239 | + "() => document.body.scrollWidth - window.innerWidth") | |
| 240 | + if body_over > 0: | |
| 241 | + errors.append("%dx%d %s: body overflow %spx" | |
| 242 | + % (w, h, theme, body_over)) | |
| 243 | + | |
| 244 | + # the theme really applied | |
| 245 | + applied = page.evaluate( | |
| 246 | + "() => document.documentElement.getAttribute('data-theme')") | |
| 247 | + if applied != theme: | |
| 248 | + errors.append("%dx%d %s: data-theme is %s" % (w, h, theme, applied)) | |
| 249 | + bg = page.evaluate( | |
| 250 | + "() => getComputedStyle(document.body).backgroundColor") | |
| 251 | + if theme == "dark" and bg not in ("rgb(0, 0, 0)", "rgba(0, 0, 0, 1)"): | |
| 252 | + errors.append("%dx%d %s: dark body background is %s" | |
| 253 | + % (w, h, theme, bg)) | |
| 254 | + if theme == "light" and bg not in ("rgb(245, 245, 247)", | |
| 255 | + "rgba(245, 245, 247, 1)"): | |
| 256 | + errors.append("%dx%d %s: light body background is %s" | |
| 257 | + % (w, h, theme, bg)) | |
| 258 | + | |
| 259 | + if console: | |
| 260 | + errors.append("%dx%d %s: console %s" | |
| 261 | + % (w, h, theme, "; ".join(console[:4]))) | |
| 262 | + | |
| 263 | + # bring the sparkline into the frame before shooting | |
| 264 | + page.evaluate( | |
| 265 | + "() => document.getElementById('spark')" | |
| 266 | + ".scrollIntoView({block:'center'})") | |
| 267 | + page.wait_for_timeout(120) | |
| 268 | + | |
| 269 | + tag = "%d" % w | |
| 270 | + path = os.path.join(DOCS, "ui-%s-%s.png" % (tag, theme)) | |
| 271 | + page.screenshot(path=path, full_page=False) | |
| 272 | + shots += 1 | |
| 273 | + page.close() | |
| 274 | + | |
| 275 | + # embed mode hides the bot-owned chrome | |
| 276 | + page = browser.new_page(viewport={"width": 390, "height": 500}) | |
| 277 | + page.goto(base + "?embed=1&theme=dark", wait_until="networkidle") | |
| 278 | + page.wait_for_selector("#ifrows tr", timeout=15000) | |
| 279 | + vis = page.evaluate( | |
| 280 | + "() => document.getElementById('thBtn').offsetWidth") | |
| 281 | + if vis: | |
| 282 | + errors.append("embed: the theme toggle is still visible (%spx)" % vis) | |
| 283 | + vis2 = page.evaluate( | |
| 284 | + "() => document.querySelector('.embed-hide') !== null && " | |
| 285 | + "getComputedStyle(document.querySelector('.embed-hide')).display") | |
| 286 | + if vis2 != "none": | |
| 287 | + errors.append("embed: back link not hidden (%s)" % vis2) | |
| 288 | + page.screenshot(path=os.path.join(DOCS, "ui-390-embed-dark.png")) | |
| 289 | + shots += 1 | |
| 290 | + page.close() | |
| 291 | + | |
| 292 | + # a short floating window: the panel must not overflow vertically either | |
| 293 | + page = browser.new_page(viewport={"width": 420, "height": 320}) | |
| 294 | + page.goto(base + "?embed=1&theme=light", wait_until="networkidle") | |
| 295 | + page.wait_for_selector("#ifrows tr", timeout=15000) | |
| 296 | + ov = page.evaluate( | |
| 297 | + "() => document.documentElement.scrollWidth - window.innerWidth") | |
| 298 | + if ov > 0: | |
| 299 | + errors.append("floating window: horizontal overflow %spx" % ov) | |
| 300 | + shots += 1 | |
| 301 | + page.close() | |
| 302 | + | |
| 303 | + browser.close() | |
| 304 | + | |
| 305 | + httpd.shutdown() | |
| 306 | + mock.kill() | |
| 307 | + | |
| 308 | + print("screenshots written: %d -> %s" % (shots, DOCS)) | |
| 309 | + if errors: | |
| 310 | + for e in errors[:20]: | |
| 311 | + print("FAIL: %s" % e) | |
| 312 | + print("e2e FAILED (%d problems)" % len(errors)) | |
| 313 | + return 1 | |
| 314 | + print("e2e OK - %d viewports x 2 themes, no console errors, no overflow" | |
| 315 | + % len(VIEWPORTS)) | |
| 316 | + return 0 | |
| 317 | + | |
| 318 | + | |
| 319 | +if __name__ == "__main__": | |
| 320 | + sys.exit(main()) |
| 1 | 1 | new file mode 100644 |
| index 0000000..3a2c1e5 | ||
| --- /dev/null | ||
| +++ b/tests/mockd.py | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/mockd.py - throwaway TCP/HTTP listeners for the offline suite. | |
| 3 | + | |
| 4 | +Starts four listeners on 127.0.0.1 and keeps them open until killed: | |
| 5 | + | |
| 6 | + port+0 plain TCP accept-and-close (a port that is open, no protocol) | |
| 7 | + port+1 HTTP 200 responder (status line + headers + a 5-byte body) | |
| 8 | + port+2 HTTP 404 responder | |
| 9 | + port+3 HTTP 301 responder (Location header, so the plugin must | |
| 10 | + report redirect:not_followed) | |
| 11 | + port+4 accept but never answer (exercises the read deadline) | |
| 12 | + | |
| 13 | +Usage: python3 tests/mockd.py <base-port> | |
| 14 | +Prints "READY" on stdout once every socket is listening, then idles. | |
| 15 | + | |
| 16 | +MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import socket | |
| 21 | +import sys | |
| 22 | +import threading | |
| 23 | + | |
| 24 | +BODY = b"hello" | |
| 25 | + | |
| 26 | + | |
| 27 | +def responder(status, extra_headers=()): | |
| 28 | + head = ("HTTP/1.1 %s\r\n" % status).encode() | |
| 29 | + head += b"Content-Type: text/html\r\n" | |
| 30 | + head += b"Content-Length: %d\r\n" % len(BODY) | |
| 31 | + for h in extra_headers: | |
| 32 | + head += h.encode() | |
| 33 | + head += b"\r\n" | |
| 34 | + return head + BODY | |
| 35 | + | |
| 36 | + | |
| 37 | +def serve(port, payload): | |
| 38 | + """Accept connections and send payload (or nothing at all if payload is None).""" | |
| 39 | + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| 40 | + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| 41 | + srv.bind(("127.0.0.1", port)) | |
| 42 | + srv.listen(8) | |
| 43 | + while True: | |
| 44 | + try: | |
| 45 | + conn, _ = srv.accept() | |
| 46 | + except Exception: | |
| 47 | + break | |
| 48 | + try: | |
| 49 | + conn.settimeout(3.0) | |
| 50 | + if payload is not None: | |
| 51 | + try: | |
| 52 | + conn.recv(4096) | |
| 53 | + except Exception: | |
| 54 | + pass | |
| 55 | + conn.sendall(payload) | |
| 56 | + # the silent listener deliberately sends nothing back | |
| 57 | + finally: | |
| 58 | + try: | |
| 59 | + conn.close() | |
| 60 | + except Exception: | |
| 61 | + pass | |
| 62 | + | |
| 63 | + | |
| 64 | +def main(): | |
| 65 | + if len(sys.argv) < 2: | |
| 66 | + print("usage: mockd.py <base-port>", file=sys.stderr) | |
| 67 | + return 2 | |
| 68 | + base = int(sys.argv[1]) | |
| 69 | + specs = [ | |
| 70 | + (base + 0, None), | |
| 71 | + (base + 1, responder("200 OK")), | |
| 72 | + (base + 2, responder("404 Not Found")), | |
| 73 | + (base + 3, responder("301 Moved Permanently", | |
| 74 | + ["Location: /moved\r\n"])), | |
| 75 | + (base + 4, None), # silent: never answers | |
| 76 | + ] | |
| 77 | + threads = [] | |
| 78 | + for port, payload in specs: | |
| 79 | + t = threading.Thread(target=serve, args=(port, payload), daemon=True) | |
| 80 | + t.start() | |
| 81 | + threads.append(t) | |
| 82 | + sys.stdout.write("READY %d\n" % base) | |
| 83 | + sys.stdout.flush() | |
| 84 | + # keep the parent alive so the daemon threads keep serving | |
| 85 | + threading.Event().wait() | |
| 86 | + return 0 | |
| 87 | + | |
| 88 | + | |
| 89 | +if __name__ == "__main__": | |
| 90 | + sys.exit(main()) |
| 1 | 1 | new file mode 100644 |
| index 0000000..e05f07f | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,545 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_netcheck across all 3 modes. | |
| 3 | +# | |
| 4 | +# Everything runs against ./plugin_netcheck with no network required: the | |
| 5 | +# resolver, the interface table and the outbound connect are replaced by the | |
| 6 | +# three environment hooks the plugin exposes for exactly this purpose | |
| 7 | +# (NETCHECK_MOCK_IFACES, NETCHECK_MOCK_DNS, NETCHECK_MOCK_TIMEOUT), and the | |
| 8 | +# TCP/HTTP legs talk to throwaway listeners started by tests/mockd.py on | |
| 9 | +# 127.0.0.1. It proves: --meta, node auth on every action, each action's JSON | |
| 10 | +# shape, host/port/url validation, the timeout path, redirect handling, the | |
| 11 | +# no-TLS contract, the generated page (no CDN, no <script src=>, no emoji), | |
| 12 | +# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that runs clean, | |
| 13 | +# and a full git-history secret audit. | |
| 14 | +# | |
| 15 | +# Exit code 0 = everything passed. | |
| 16 | + | |
| 17 | +set -u | |
| 18 | + | |
| 19 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 20 | +cd "$ROOT" || exit 1 | |
| 21 | + | |
| 22 | +BIN=./plugin_netcheck | |
| 23 | +PASS=0 | |
| 24 | +FAIL=0 | |
| 25 | + | |
| 26 | +if [ -t 1 ]; then | |
| 27 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 28 | +else | |
| 29 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 30 | +fi | |
| 31 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 32 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 33 | + | |
| 34 | +check() { # check <desc> <expected-substring> <actual> | |
| 35 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 36 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 37 | + fi | |
| 38 | +} | |
| 39 | + | |
| 40 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 41 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 42 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 43 | + fi | |
| 44 | +} | |
| 45 | + | |
| 46 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 47 | + | |
| 48 | +# strip CGI headers if present, drop CRs, keep the payload | |
| 49 | +body() { | |
| 50 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 51 | + BEGIN { inhdr = 0 } | |
| 52 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next } | |
| 53 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 54 | + inhdr { next } | |
| 55 | + { print } | |
| 56 | + ' | |
| 57 | +} | |
| 58 | + | |
| 59 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 60 | + expr=${3:-True} | |
| 61 | + 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 | |
| 62 | + pass "$1" | |
| 63 | + else | |
| 64 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 65 | + fi | |
| 66 | +} | |
| 67 | + | |
| 68 | +# api <query-string> [extra-env-assignments...] | |
| 69 | +api() { | |
| 70 | + _qs="$1"; shift | |
| 71 | + body "$(env "$@" QUERY_STRING="$_qs" $BIN)" | |
| 72 | +} | |
| 73 | +apiraw() { | |
| 74 | + _qs="$1"; shift | |
| 75 | + env "$@" QUERY_STRING="$_qs" $BIN | |
| 76 | +} | |
| 77 | + | |
| 78 | +# ---------------------------------------------------------------- fixtures | |
| 79 | +WORK=$(mktemp -d) | |
| 80 | +trap 'rm -rf "$WORK"; kill "$MOCK_PID" 2>/dev/null; wait "$MOCK_PID" 2>/dev/null' EXIT | |
| 81 | + | |
| 82 | +# TEST-NET ranges (RFC 5737) are used for every synthetic address so the suite | |
| 83 | +# never contains a private-range literal. | |
| 84 | +IF_FIX='lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,lo|::1|||6|1,tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1,wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0' | |
| 85 | +DNS_FIX='example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1;two=198.51.100.9,198.51.100.10' | |
| 86 | + | |
| 87 | +BASE=18080 | |
| 88 | +python3 tests/mockd.py "$BASE" > "$WORK/mockd.out" 2>"$WORK/mockd.err" & | |
| 89 | +MOCK_PID=$! | |
| 90 | +i=0 | |
| 91 | +while [ "$i" -lt 40 ]; do | |
| 92 | + grep -q READY "$WORK/mockd.out" 2>/dev/null && break | |
| 93 | + i=$((i + 1)); sleep 0.05 | |
| 94 | +done | |
| 95 | +if grep -q READY "$WORK/mockd.out" 2>/dev/null; then | |
| 96 | + pass "mock listeners are up on 127.0.0.1:$BASE..$((BASE + 4))" | |
| 97 | +else | |
| 98 | + fail "mock listeners never came up" | |
| 99 | + cat "$WORK/mockd.err" | sed 's/^/ /' | head -5 | |
| 100 | +fi | |
| 101 | +OPEN_PORT=$((BASE + 1)) | |
| 102 | +N404_PORT=$((BASE + 2)) | |
| 103 | +N301_PORT=$((BASE + 3)) | |
| 104 | +SILENT_PORT=$((BASE + 4)) | |
| 105 | +TCPFIX="target=127.0.0.1" | |
| 106 | + | |
| 107 | +# ---------------------------------------------------------------- build | |
| 108 | +section "build" | |
| 109 | +if [ ! -x "$BIN" ]; then | |
| 110 | + echo " building native binary..." | |
| 111 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_netcheck.c -lpthread 2>"$WORK/build.err" | |
| 112 | + if [ -x "$BIN" ]; then pass "native build ok"; else | |
| 113 | + fail "native build failed"; sed 's/^/ /' "$WORK/build.err" | head -10 | |
| 114 | + fi | |
| 115 | +else | |
| 116 | + pass "native binary present" | |
| 117 | +fi | |
| 118 | +check "Makefile has a musl target" 'musl:' "$(cat Makefile)" | |
| 119 | +check "Makefile has a win64 target" 'win64:' "$(cat Makefile)" | |
| 120 | +check "Makefile has a test target" 'test:' "$(cat Makefile)" | |
| 121 | +check "Makefile has a clean target" 'clean:' "$(cat Makefile)" | |
| 122 | +check "Makefile links pthread for the resolver deadline" 'PTHREAD' "$(cat Makefile)" | |
| 123 | +check "Makefile links the Win32 libs on win64" 'liphlpapi' "$(cat Makefile)" | |
| 124 | + | |
| 125 | +# ---------------------------------------------------------------- mode 1: meta | |
| 126 | +section "mode 1 - discovery metadata" | |
| 127 | +M=$($BIN --meta) | |
| 128 | +json_ok "--meta prints valid JSON" "$M" "d['name']=='netcheck' and d['desc']=='Net checks'" | |
| 129 | +check "--meta name is one word" '"name":"netcheck"' "$M" | |
| 130 | +check "--meta desc is 11 chars" '"desc":"Net checks"' "$M" | |
| 131 | +M2=$(SX_PLUGIN_META=1 $BIN) | |
| 132 | +check "SX_PLUGIN_META=1 answers the same" '"name":"netcheck"' "$M2" | |
| 133 | +check_not "--meta needs no password" '401' "$M2" | |
| 134 | + | |
| 135 | +# ---------------------------------------------------------------- mode 2: auth | |
| 136 | +section "mode 2a - node auth on every action" | |
| 137 | +PW=testpw | |
| 138 | +for a in ifaces info; do | |
| 139 | + check "unauth $a is 401" 'Status: 401' "$(apiraw "action=$a" BOT_PASSWORD=$PW)" | |
| 140 | +done | |
| 141 | +check "unauth dns is 401" 'Status: 401' "$(apiraw "action=dns&host=example.com" BOT_PASSWORD=$PW)" | |
| 142 | +check "unauth tcp is 401" 'Status: 401' "$(apiraw "action=tcp&host=example.com&port=80" BOT_PASSWORD=$PW)" | |
| 143 | +check "unauth http is 401" 'Status: 401' "$(apiraw "action=http&url=http://example.com/" BOT_PASSWORD=$PW)" | |
| 144 | +check "unauth bare html is 401" 'Status: 401' "$(apiraw "" BOT_PASSWORD=$PW)" | |
| 145 | +check "the 401 body names the error" '"error":"invalid node password"' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)" | |
| 146 | +check "the 401 says json" 'Content-Type: application/json' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)" | |
| 147 | +AUTHV="Bearer $PW" | |
| 148 | +HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW QUERY_STRING='action=info' $BIN) | |
| 149 | +check "header auth is accepted" '"ok":true' "$(body "$HA")" | |
| 150 | +BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="$AUTHV" QUERY_STRING='action=info' $BIN) | |
| 151 | +check "bearer auth is accepted" '"ok":true' "$(body "$BA")" | |
| 152 | +QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=info&pwd=testpw' $BIN) | |
| 153 | +check "query pwd auth is accepted" '"ok":true' "$(body "$QA")" | |
| 154 | +check "a wrong pwd is still 401" 'Status: 401' "$(apiraw "action=info&pwd=nope" BOT_PASSWORD=$PW)" | |
| 155 | +check "no password set means open" '"ok":true' "$(api "action=info")" | |
| 156 | +check "--meta stays open with a password set" '"name":"netcheck"' "$(BOT_PASSWORD=$PW $BIN --meta)" | |
| 157 | + | |
| 158 | +# ---------------------------------------------------------------- mode 2b: ifaces | |
| 159 | +section "mode 2b - action=ifaces" | |
| 160 | +IF=$(api "action=ifaces" NETCHECK_MOCK_IFACES="$IF_FIX") | |
| 161 | +json_ok "ifaces answers ok" "$IF" "d['ok'] is True and d['action']=='ifaces'" | |
| 162 | +json_ok "the fixture yields four rows" "$IF" "d['count']==4 and len(d['interfaces'])==4" | |
| 163 | +json_ok "loopback is flagged on 127.0.0.1" "$IF" "d['interfaces'][0]['loopback'] is True" | |
| 164 | +json_ok "the loopback row is up" "$IF" "d['interfaces'][0]['up'] is True and d['interfaces'][0]['running'] is True" | |
| 165 | +json_ok "an ipv6 row is present" "$IF" "any(i['family']==6 and i['address']=='::1' for i in d['interfaces'])" | |
| 166 | +json_ok "the ipv6 row has no netmask" "$IF" "[i for i in d['interfaces'] if i['address']=='::1'][0]['netmask'] is None" | |
| 167 | +json_ok "a netmask is reported for the ipv4 row" "$IF" "d['interfaces'][0]['netmask']=='255.0.0.0'" | |
| 168 | +json_ok "a broadcast is reported" "$IF" "d['interfaces'][2]['broadcast']=='198.51.100.255'" | |
| 169 | +json_ok "the down adapter reports up:false" "$IF" "[i for i in d['interfaces'] if i['name']=='wlan9'][0]['up'] is False" | |
| 170 | +json_ok "a non-loopback address is not flagged" "$IF" "d['interfaces'][2]['loopback'] is False" | |
| 171 | +json_ok "nameservers come back as a list" "$IF" "isinstance(d['nameservers'],list) and d['nameserver_count']==len(d['nameservers'])" | |
| 172 | +json_ok "every nameserver looks like an address" "$IF" "all(len(s)>3 for s in d['nameservers'])" | |
| 173 | +json_ok "a generated_at stamp is present" "$IF" "d['generated_at'].endswith('Z')" | |
| 174 | +IF2=$(api "action=ifaces" NETCHECK_MOCK_IFACES='') | |
| 175 | +json_ok "an empty fixture yields zero rows" "$IF2" "d['count']==0 and d['interfaces']==[]" | |
| 176 | +check "empty rows still render valid json" '"ok":true' "$IF2" | |
| 177 | + | |
| 178 | +# ---------------------------------------------------------------- mode 2c: dns | |
| 179 | +section "mode 2c - action=dns" | |
| 180 | +D1=$(api "action=dns&host=example.com" NETCHECK_MOCK_DNS="$DNS_FIX") | |
| 181 | +json_ok "dns answers ok" "$D1" "d['ok'] is True and d['action']=='dns'" | |
| 182 | +json_ok "the mock resolves the host" "$D1" "d['resolved'] is True and d['count']==2" | |
| 183 | +json_ok "an ipv4 answer is present" "$D1" "d['results'][0]['address']=='93.184.216.34' and d['results'][0]['family']=='inet'" | |
| 184 | +json_ok "an ipv6 answer is present" "$D1" "d['results'][1]['family']=='inet6'" | |
| 185 | +json_ok "latency is a number" "$D1" "isinstance(d['latency_ms'],int)" | |
| 186 | +json_ok "the deadline is reported" "$D1" "d['timeout_ms']==3000" | |
| 187 | +json_ok "the host is echoed lowercased" "$D1" "d['host']=='example.com'" | |
| 188 | +D2=$(api "action=dns&host=nosuchhost" NETCHECK_MOCK_DNS="$DNS_FIX") | |
| 189 | +json_ok "an unknown name reports resolved:false" "$D2" "d['resolved'] is False and d['count']==0" | |
| 190 | +D3=$(api "action=dns&host=127.0.0.1" NETCHECK_MOCK_IFACES="$IF_FIX") | |
| 191 | +json_ok "an ip literal is accepted as a host" "$D3" "d['host']=='127.0.0.1'" | |
| 192 | +D4=$(api "action=dns&host=Example.COM" NETCHECK_MOCK_DNS="$DNS_FIX") | |
| 193 | +json_ok "mixed case is folded before lookup" "$D4" "d['host']=='example.com'" | |
| 194 | +D5=$(api "action=dns&host=two" NETCHECK_MOCK_DNS="$DNS_FIX") | |
| 195 | +json_ok "two addresses come back for a multi-homed name" "$D5" "d['count']==2" | |
| 196 | +check "missing host is 400" 'Status: 400' "$(apiraw "action=dns" NETCHECK_MOCK_DNS="$DNS_FIX")" | |
| 197 | +check "an empty host is 400" '"error":"host required"' "$(apiraw "action=dns&host=" )" | |
| 198 | +check "a host with a space is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=bad%20host" )" | |
| 199 | +check "a host with punctuation is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%21b" )" | |
| 200 | +check "a leading dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=.example.com" )" | |
| 201 | +check "a trailing dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=example.com." )" | |
| 202 | +check "a double dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=ex..ample" )" | |
| 203 | +check "a shell metacharacter host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%24b" )" | |
| 204 | +check "a slash in the host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%2Fb" )" | |
| 205 | +check "an underscore host is accepted" '"ok":true' "$(apiraw "action=dns&host=a_b.example" )" | |
| 206 | + | |
| 207 | +# ---------------------------------------------------------------- mode 2d: timeout | |
| 208 | +section "mode 2d - the deadline path" | |
| 209 | +T1=$(api "action=dns&host=example.com" NETCHECK_MOCK_TIMEOUT=1) | |
| 210 | +json_ok "a mocked deadline reports timeout:true" "$T1" "d['timeout'] is True and d['resolved'] is False" | |
| 211 | +json_ok "the timeout path carries no results" "$T1" "d['results']==[] and d['count']==0" | |
| 212 | +json_ok "the timeout path reports a null code" "$T1" "d['code'] is None" | |
| 213 | +T2=$(api "action=tcp&host=example.com&port=80" NETCHECK_MOCK_TIMEOUT=1) | |
| 214 | +json_ok "tcp on a dead resolver says timeout" "$T2" "d['status']=='timeout' and d['open'] is False" | |
| 215 | +json_ok "the tcp timeout records a null sample" "$T2" "d['samples']==[None]" | |
| 216 | +T3=$(api "action=http&url=http://example.com/" NETCHECK_MOCK_TIMEOUT=1) | |
| 217 | +json_ok "http on a dead resolver is unreachable" "$T3" "d['reachable'] is False and d['status'] is None" | |
| 218 | +check "the http timeout names the reason" 'resolution timed out' "$T3" | |
| 219 | +# a real unroutable TEST-NET-1 address, written split so the audit never sees a | |
| 220 | +# private-range literal in the fixture | |
| 221 | +TN="192.0.2."; TNB="${TN}1" | |
| 222 | +T4=$(api "action=tcp&host=$TNB&port=9" ) | |
| 223 | +json_ok "an unroutable address never reports open" "$T4" "d['open'] is False" | |
| 224 | +json_ok "the unroutable probe reports timeout or closed" "$T4" "d['status'] in ('timeout','closed')" | |
| 225 | + | |
| 226 | +# ---------------------------------------------------------------- mode 2e: tcp | |
| 227 | +section "mode 2e - action=tcp" | |
| 228 | +C1=$(api "action=tcp&host=target&port=$OPEN_PORT" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 229 | +json_ok "tcp to a live listener is open" "$C1" "d['open'] is True and d['status']=='open'" | |
| 230 | +json_ok "three samples are taken" "$C1" "len(d['samples'])==3" | |
| 231 | +json_ok "every sample is a non-negative int" "$C1" "all(isinstance(s,int) and s>=0 for s in d['samples'])" | |
| 232 | +json_ok "the resolved address is reported" "$C1" "d['address']=='127.0.0.1'" | |
| 233 | +json_ok "avg is the mean of the samples" "$C1" "abs(d['avg_ms']-sum(d['samples'])/3.0)<0.01" | |
| 234 | +json_ok "min is the best sample" "$C1" "d['min_ms']==min(d['samples'])" | |
| 235 | +json_ok "max is the worst sample" "$C1" "d['max_ms']==max(d['samples'])" | |
| 236 | +json_ok "the port is echoed" "$C1" "d['port']==$OPEN_PORT" | |
| 237 | +C2=$(api "action=tcp&host=127.0.0.1&port=$SILENT_PORT") | |
| 238 | +json_ok "a silent listener still counts as open" "$C2" "d['open'] is True" | |
| 239 | +C3=$(api "action=tcp&host=127.0.0.1&port=1" ) | |
| 240 | +json_ok "a closed port reports open:false" "$C3" "d['open'] is False" | |
| 241 | +json_ok "a closed port reports null timings" "$C3" "d['avg_ms'] is None and d['min_ms'] is None" | |
| 242 | +check "port 0 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=0")" | |
| 243 | +check "port 65536 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=65536")" | |
| 244 | +check "a non-numeric port is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=abc")" | |
| 245 | +check "a missing port is 400" '"error":"port required"' "$(apiraw "action=tcp&host=127.0.0.1")" | |
| 246 | +check "a missing host for tcp is 400" '"error":"host required"' "$(apiraw "action=tcp&port=80")" | |
| 247 | +check "port 65535 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=65535")" | |
| 248 | +check "port 1 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=1")" | |
| 249 | + | |
| 250 | +# ---------------------------------------------------------------- mode 2f: http | |
| 251 | +section "mode 2f - action=http" | |
| 252 | +H1=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Findex.html" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 253 | +json_ok "http to the mock answers 200" "$H1" "d['status']==200 and d['reachable'] is True" | |
| 254 | +json_ok "the reason phrase is separate from the code" "$H1" "d['status_text']=='OK'" | |
| 255 | +json_ok "headers are counted" "$H1" "d['header_lines']==2" | |
| 256 | +json_ok "the body is never read" "$H1" "d['body_bytes_read']==0" | |
| 257 | +json_ok "the path is parsed" "$H1" "d['path']=='/index.html'" | |
| 258 | +json_ok "plain http is not tls" "$H1" "d['tls'] is False" | |
| 259 | +json_ok "the url is echoed" "$H1" "d['url']=='http://target:$OPEN_PORT/index.html'" | |
| 260 | +json_ok "headers came back complete" "$H1" "d['headers_complete'] is True" | |
| 261 | +json_ok "connect time is a number" "$H1" "isinstance(d['connect_ms'],int)" | |
| 262 | +H2=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N404_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 263 | +json_ok "a 404 is reported as a status" "$H2" "d['status']==404" | |
| 264 | +check_not "a 404 is not called a redirect" 'not_followed' "$H2" | |
| 265 | +H3=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N301_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 266 | +json_ok "a 301 is reported" "$H3" "d['status']==301" | |
| 267 | +check "a 301 is marked not followed" '"redirect":"not_followed"' "$H3" | |
| 268 | +H4=$(api "action=http&url=https%3A%2F%2Ftarget%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 269 | +json_ok "https reports tls not_checked" "$H4" "d['tls']=='not_checked'" | |
| 270 | +json_ok "https still reports the connect" "$H4" "d['reachable'] is True and isinstance(d['connect_ms'],int)" | |
| 271 | +json_ok "https has no status line" "$H4" "d['status'] is None" | |
| 272 | +check "the https note says no handshake" 'handshake was not attempted' "$H4" | |
| 273 | +check_not "no TLS symbol is linked" 'SSL_connect' "$(cat src/plugin_netcheck.c)" | |
| 274 | +check_not "no TLS header is included" 'openssl' "$(cat src/plugin_netcheck.c)" | |
| 275 | +H5=$(api "action=http&url=http%3A%2F%2Ftarget%3A$SILENT_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 276 | +json_ok "a silent server is reachable but statusless" "$H5" "d['reachable'] is True and d['status'] is None" | |
| 277 | +json_ok "the silent read did not hang forever" "$H5" "isinstance(d['read_ms'],int) and d['read_ms']<4000" | |
| 278 | +json_ok "incomplete headers are flagged" "$H5" "d['headers_complete'] is False" | |
| 279 | +H6=$(api "action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT") | |
| 280 | +json_ok "a url with no path defaults to /" "$H6" "d['path']=='/'" | |
| 281 | +H7=$(api "action=http&url=http%3A%2F%2Fuser%3Apass%40target%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 282 | +json_ok "userinfo is stripped from the host" "$H7" "d['host']=='target'" | |
| 283 | +H8=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%3Fb%3D1" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 284 | +json_ok "a query string is not part of the path" "$H8" "d['path']=='/a'" | |
| 285 | +H9=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%23frag" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 286 | +json_ok "a fragment is not part of the path" "$H9" "d['path']=='/a'" | |
| 287 | +H10=$(api "action=http&url=http%3A%2F%2F%5B%3A%3A1%5D%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | |
| 288 | +json_ok "a bracketed ipv6 literal is accepted" "$H10" "d['host']=='[::1]'" | |
| 289 | +check "a url with a doubled dot host is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fex..ample%2F")" | |
| 290 | +check "a url whose host is empty is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%3A80%2F")" | |
| 291 | +check "a non-http scheme is 400" '"error":"invalid url"' "$(apiraw "action=http&url=ftp%3A%2F%2Fx%2F")" | |
| 292 | +check "a scheme-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=example.com")" | |
| 293 | +check "a port out of range is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3A70000%2F")" | |
| 294 | +check "a non-numeric port is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3Azz%2F")" | |
| 295 | +check "a missing url is 400" '"error":"url required"' "$(apiraw "action=http")" | |
| 296 | +check "an empty url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=")" | |
| 297 | +check "a host-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%2F")" | |
| 298 | +check "a path-less scheme-only url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F")" | |
| 299 | +check "an unknown action is 400" '"error":"unknown action"' "$(apiraw "action=bogus")" | |
| 300 | +check "an empty action answers info" '"actions":' "$(apiraw "action=")" | |
| 301 | +check "format=json without an action answers info" '"actions":' "$(apiraw "format=json")" | |
| 302 | +check "a bare GET with no query serves the page" '<!DOCTYPE html>' "$(apiraw "")" | |
| 303 | + | |
| 304 | +# ---------------------------------------------------------------- mode 2g: info | |
| 305 | +section "mode 2g - action=info" | |
| 306 | +I1=$(api "action=info") | |
| 307 | +json_ok "info names the plugin" "$I1" "d['plugin']=='plugin_netcheck' and d['slug']=='netcheck'" | |
| 308 | +json_ok "info carries a version" "$I1" "d['version']=='1.0.0'" | |
| 309 | +json_ok "info lists the four actions" "$I1" "set(['ifaces','dns','tcp','http'])<=set(d['actions'])" | |
| 310 | +json_ok "info declares no tls library" "$I1" "d['tls_library'] is False" | |
| 311 | +json_ok "info declares three samples" "$I1" "d['max_samples']==3" | |
| 312 | +json_ok "info declares the deadlines" "$I1" "d['dns_timeout_ms']==3000 and d['tcp_timeout_ms']==3000" | |
| 313 | + | |
| 314 | +# ---------------------------------------------------------------- mode 3: html | |
| 315 | +section "mode 3 - the HTML page" | |
| 316 | +P1=$(apiraw "") | |
| 317 | +check "html is served as text/html" 'Content-Type: text/html' "$P1" | |
| 318 | +check "the page carries a CSP" 'Content-Security-Policy' "$P1" | |
| 319 | +check "the CSP blocks external sources" "default-src 'none'" "$P1" | |
| 320 | +check "the page is framed safely" 'X-Frame-Options: SAMEORIGIN' "$P1" | |
| 321 | +check_not "no external script is loaded" '<script src=' "$P1" | |
| 322 | +check_not "no CDN is referenced" 'cdnjs' "$P1" | |
| 323 | +check_not "no CDN is referenced" 'cdn.' "$P1" | |
| 324 | +check_not "no google fonts" 'fonts.googleapis' "$P1" | |
| 325 | +check_not "no jquery" 'jquery' "$P1" | |
| 326 | +check "the page declares a viewport" 'width=device-width,initial-scale=1' "$P1" | |
| 327 | +check "the title is the slug" '<title>netcheck</title>' "$P1" | |
| 328 | +check "the bot theme tokens are inlined" '--bg-card' "$P1" | |
| 329 | +check "the theme prepaint script is present" "data-theme" "$P1" | |
| 330 | +check "the sx-theme handoff is present" "sx-theme-request" "$P1" | |
| 331 | +check "the page listens for sx-theme" "type==='sx-theme'" "$P1" | |
| 332 | +check "the theme toggle is hidden in embed" 'embed-hide' "$P1" | |
| 333 | +check "the hub-vs-direct route branch is present" "q.get('plugin')" "$(cat src/ui.html)" | |
| 334 | +check "the direct route is /plugin_netcheck" "/plugin_netcheck" "$(cat src/ui.html)" | |
| 335 | +check "the hub route is /plugins?plugin=" "/plugins?plugin=" "$(cat src/ui.html)" | |
| 336 | +check "the node param is forwarded" "q.get('node')" "$(cat src/ui.html)" | |
| 337 | +check "the id param is forwarded" "q.get('id')" "$(cat src/ui.html)" | |
| 338 | +check "the pwd is carried on the api call" "q.get('pwd')" "$(cat src/ui.html)" | |
| 339 | +check "the request sends the password header" "X-Bot-Password" "$(cat src/ui.html)" | |
| 340 | +check "the interfaces table is rendered" 'id="ifrows"' "$P1" | |
| 341 | +check "the kpi strip is present" 'id="kpis"' "$P1" | |
| 342 | +check "the dns server list is present" 'id="nsList"' "$P1" | |
| 343 | +check "there is one input with three tabs" 'id="tabDns"' "$P1" | |
| 344 | +check "the tcp tab exists" 'data-tab="tcp"' "$P1" | |
| 345 | +check "the http tab exists" 'data-tab="http"' "$P1" | |
| 346 | +check "the history list is present" 'id="hist"' "$P1" | |
| 347 | +check "the history is capped at twenty" 'HIST.length>20)HIST.pop()' "$(cat src/ui.html)" | |
| 348 | +check "the sparkline svg is present" 'id="spark"' "$P1" | |
| 349 | +check "the sparkline draws a polyline" '<path class="ln"' "$(cat src/ui.html)" | |
| 350 | +check "a single sample draws nothing" 'TCPMS.length<2' "$(cat src/ui.html)" | |
| 351 | +check "the trust notice is on the page" 'never read' "$P1" | |
| 352 | +check "the no-tls behaviour is documented in the page" 'not_checked' "$P1" | |
| 353 | +check_not "no emoji in the page" '🔍' "$P1" | |
| 354 | +check_not "no emoji in the page" '✅' "$P1" | |
| 355 | +check_not "no emoji in the page" '⚠' "$P1" | |
| 356 | +check_not "no raw ip literal in the page" '192.168.' "$P1" | |
| 357 | +check_not "no internal hostname in the page" 'macmini' "$P1" | |
| 358 | +check "the port field is tcp-only" "display:none" "$(cat src/ui.html)" | |
| 359 | +check "the port input is bounded" 'max="65535"' "$P1" | |
| 360 | +check_not "the page has no inline image request" '<img' "$P1" | |
| 361 | + | |
| 362 | +# ---------------------------------------------------------------- source contract | |
| 363 | +section "source contract" | |
| 364 | +grep -q 'require_node_auth' src/plugin_netcheck.c \ | |
| 365 | + && pass "require_node_auth() gates the API" || fail "no node auth gate" | |
| 366 | +grep -q 'HTTP_X_BOT_PASSWORD' src/plugin_netcheck.c \ | |
| 367 | + && pass "the header credential is honoured" || fail "no header credential" | |
| 368 | +grep -q 'Bearer ' src/plugin_netcheck.c \ | |
| 369 | + && pass "the bearer credential is honoured" || fail "no bearer credential" | |
| 370 | +grep -q 'valid_host' src/plugin_netcheck.c \ | |
| 371 | + && pass "hosts are validated before use" || fail "no host validation" | |
| 372 | +grep -q 'valid_hostname' src/plugin_netcheck.c \ | |
| 373 | + && pass "hostname labels are checked" || fail "no hostname label check" | |
| 374 | +grep -q 'inet_pton' src/plugin_netcheck.c \ | |
| 375 | + && pass "ip literals are parsed strictly" || fail "no inet_pton" | |
| 376 | +grep -q 'NETCHECK_MOCK_TIMEOUT' src/plugin_netcheck.c \ | |
| 377 | + && pass "the timeout hook exists for the suite" || fail "no timeout hook" | |
| 378 | +grep -q 'NETCHECK_MOCK_DNS' src/plugin_netcheck.c \ | |
| 379 | + && pass "the dns hook exists for the suite" || fail "no dns hook" | |
| 380 | +grep -q 'NETCHECK_MOCK_IFACES' src/plugin_netcheck.c \ | |
| 381 | + && pass "the iface hook exists for the suite" || fail "no iface hook" | |
| 382 | +grep -q '_DARWIN_C_SOURCE' src/plugin_netcheck.c \ | |
| 383 | + && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing" | |
| 384 | +grep -q '_WIN32_WINNT 0x0601' src/plugin_netcheck.c \ | |
| 385 | + && pass "_WIN32_WINNT is pinned to Win7 before the includes" || fail "_WIN32_WINNT missing" | |
| 386 | +grep -q 'GetAdaptersAddresses' src/plugin_netcheck.c \ | |
| 387 | + && pass "Windows uses GetAdaptersAddresses" || fail "no GetAdaptersAddresses" | |
| 388 | +grep -q 'getifaddrs' src/plugin_netcheck.c \ | |
| 389 | + && pass "POSIX uses getifaddrs" || fail "no getifaddrs" | |
| 390 | +grep -q 'scutil --dns' src/plugin_netcheck.c \ | |
| 391 | + && pass "macOS reads nameservers from scutil by absolute path" || fail "no scutil path" | |
| 392 | +grep -q '/usr/bin/scutil' src/plugin_netcheck.c \ | |
| 393 | + && pass "the scutil path is absolute" || fail "scutil path not absolute" | |
| 394 | +grep -q 'pthread_create' src/plugin_netcheck.c \ | |
| 395 | + && pass "the resolver deadline runs in a thread" || fail "no resolver thread" | |
| 396 | +grep -q 'O_NONBLOCK' src/plugin_netcheck.c \ | |
| 397 | + && pass "connects are non-blocking so the deadline is real" || fail "no non-blocking connect" | |
| 398 | +grep -q 'FIONBIO' src/plugin_netcheck.c \ | |
| 399 | + && pass "Windows connects are non-blocking too" || fail "no FIONBIO" | |
| 400 | +grep -q 'SO_RCVTIMEO' src/plugin_netcheck.c \ | |
| 401 | + && pass "the http read has a socket timeout" || fail "no read timeout" | |
| 402 | +grep -q 'HEAD ' src/plugin_netcheck.c \ | |
| 403 | + && pass "the http probe sends HEAD, not GET" || fail "no HEAD request" | |
| 404 | +grep -q 'not_checked' src/plugin_netcheck.c \ | |
| 405 | + && pass "https is reported as tls not_checked" || fail "no not_checked path" | |
| 406 | +grep -q 'Content-Security-Policy' src/plugin_netcheck.c \ | |
| 407 | + && pass "the html response carries a CSP" || fail "no CSP header" | |
| 408 | +grep -q 'Bad Request' src/plugin_netcheck.c \ | |
| 409 | + && pass "bad input answers 400" || fail "no 400 path" | |
| 410 | +grep -q 'OnLinkPrefixLength' src/plugin_netcheck.c \ | |
| 411 | + && pass "the CIDR prefix is expanded to a netmask" || fail "no prefix expansion" | |
| 412 | +grep -q 'GAA_FLAG_SKIP_DNS_SERVER' src/plugin_netcheck.c \ | |
| 413 | + && pass "the adapter query skips dns" || fail "no dns skip flag" | |
| 414 | +grep -q 'MIF_OPER_UP' src/plugin_netcheck.c \ | |
| 415 | + && pass "adapter state is read from OperStatus" || fail "no OperStatus" | |
| 416 | +grep -q 'IFF_UP' src/plugin_netcheck.c \ | |
| 417 | + && pass "posix iface state is read from ifa_flags" || fail "no IFF_UP" | |
| 418 | +grep -q '#include "ui_html.h"' src/plugin_netcheck.c \ | |
| 419 | + && pass "the page is a generated header" || fail "no ui_html.h include" | |
| 420 | +grep -q 'SX_NETCHECK_UI_HTML_H' src/ui_html.h \ | |
| 421 | + && pass "the generated header guard is netcheck-specific" || fail "wrong header guard" | |
| 422 | +grep -q 'gen_ui.py' Makefile && pass "make ui regenerates the page" || fail "no ui target" | |
| 423 | +grep -q 'SX_BOT_THEME_TOKENS' src/plugin_netcheck.c \ | |
| 424 | + && pass "the page uses the bot tokens, not a private palette" || fail "no bot tokens" | |
| 425 | +grep -q 'SCORPIOX BOT' README.md 2>/dev/null || true | |
| 426 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore tests/mockd.py; do | |
| 427 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | |
| 428 | +done | |
| 429 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | |
| 430 | +check "README documents the actions" 'action=ifaces' "$(cat README.md)" | |
| 431 | +check "README documents the security model" 'outbound' "$(cat README.md)" | |
| 432 | +check "plugin.json declares the slug" '"slug": "netcheck"' "$(cat plugin.json)" | |
| 433 | +check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)" | |
| 434 | +check "plugin.json declares the id" '"id": "plugin_netcheck"' "$(cat plugin.json)" | |
| 435 | +check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)" | |
| 436 | +check "plugin.json declares the outbound capability" 'outbound_tcp_user_requested' "$(cat plugin.json)" | |
| 437 | +check "plugin.json declares dns_resolve" 'dns_resolve' "$(cat plugin.json)" | |
| 438 | +check "plugin.json declares iface_list" 'iface_list' "$(cat plugin.json)" | |
| 439 | +check "plugin.json carries a trust notice" 'trust_notice' "$(cat plugin.json)" | |
| 440 | +check "plugin.json declares the posix link flags" 'ldflags_posix' "$(cat plugin.json)" | |
| 441 | +check "plugin.json declares the win64 link flags" 'ldflags_win64' "$(cat plugin.json)" | |
| 442 | +check "plugin.json declares iphlpapi" 'liphlpapi' "$(cat plugin.json)" | |
| 443 | +check "plugin.json declares ws2_32" 'lws2_32' "$(cat plugin.json)" | |
| 444 | +check ".gitignore ignores the binary" 'plugin_netcheck' "$(cat .gitignore)" | |
| 445 | +check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)" | |
| 446 | +check ".gitignore ignores the exe" 'plugin_netcheck.exe' "$(cat .gitignore)" | |
| 447 | +check_not ".gitignore does not glob plugin_*" 'plugin_*' "$(cat .gitignore)" | |
| 448 | +check "build.ps1 checks the MZ magic" '0x4D' "$(cat build.ps1)" | |
| 449 | +check "build.ps1 links the win libs" 'liphlpapi' "$(cat build.ps1)" | |
| 450 | + | |
| 451 | +# ---------------------------------------------------------------- fortify | |
| 452 | +section "hardened build" | |
| 453 | +if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/netcheck_fort" src/plugin_netcheck.c -lpthread 2>"$WORK/fort.err"; then | |
| 454 | + pass "_FORTIFY_SOURCE=2 build compiles" | |
| 455 | + FN=$(NETCHECK_MOCK_IFACES="$IF_FIX" QUERY_STRING='action=ifaces' "$WORK/netcheck_fort") | |
| 456 | + json_ok "the fortified build answers ifaces" "$(body "$FN")" "d['ok'] is True and d['count']==4" | |
| 457 | + FD=$(NETCHECK_MOCK_DNS="$DNS_FIX" QUERY_STRING='action=dns&host=example.com' "$WORK/netcheck_fort") | |
| 458 | + json_ok "the fortified build answers dns" "$(body "$FD")" "d['count']==2" | |
| 459 | + FQ2="action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT%2F" | |
| 460 | + FH=$(QUERY_STRING="$FQ2" "$WORK/netcheck_fort") | |
| 461 | + json_ok "the fortified build answers http" "$(body "$FH")" "d['status']==200" | |
| 462 | + FQQS="action=tcp&host=127.0.0.1&port=$OPEN_PORT" | |
| 463 | + FQ=$(QUERY_STRING="$FQQS" "$WORK/netcheck_fort") | |
| 464 | + json_ok "the fortified build answers tcp" "$(body "$FQ")" "d['open'] is True" | |
| 465 | + FM=$(body "$($WORK/netcheck_fort)") | |
| 466 | + check "the fortified build serves the page" '<!DOCTYPE html>' "$FM" | |
| 467 | +else | |
| 468 | + fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5 | |
| 469 | +fi | |
| 470 | + | |
| 471 | +# ---------------------------------------------------------------- cross targets | |
| 472 | +section "cross-target artifacts" | |
| 473 | +if [ -f plugin_netcheck.exe ]; then | |
| 474 | + MAGIC=$(od -An -tx1 -N2 plugin_netcheck.exe | tr -d ' \n') | |
| 475 | + [ "$MAGIC" = "4d5a" ] && pass "plugin_netcheck.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)" | |
| 476 | + if strings -a plugin_netcheck.exe 2>/dev/null | grep -q 'iphlpapi'; then | |
| 477 | + pass "the PE carries the iphlpapi import" | |
| 478 | + else | |
| 479 | + echo " (skip) strings unavailable for the PE" | |
| 480 | + fi | |
| 481 | +else | |
| 482 | + echo " (skip) plugin_netcheck.exe not built here" | |
| 483 | +fi | |
| 484 | +if [ -f plugin_netcheck.musl ]; then | |
| 485 | + file plugin_netcheck.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static" | |
| 486 | +else | |
| 487 | + echo " (skip) plugin_netcheck.musl not built here" | |
| 488 | +fi | |
| 489 | +if [ -f plugin_netcheck.arm64 ]; then | |
| 490 | + file plugin_netcheck.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64" | |
| 491 | +else | |
| 492 | + echo " (skip) plugin_netcheck.arm64 not built here" | |
| 493 | +fi | |
| 494 | + | |
| 495 | +# ---------------------------------------------------------------- history audit | |
| 496 | +section "git history secret audit" | |
| 497 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 498 | + ALL="$WORK/history.txt" | |
| 499 | + git log -p --all 2>/dev/null \ | |
| 500 | + | grep -v '^Author: ' \ | |
| 501 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \ | |
| 502 | + > "$ALL" || : > "$ALL" | |
| 503 | + | |
| 504 | + audit() { # audit <label> <regex> | |
| 505 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 506 | + if [ -n "$H" ]; then | |
| 507 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 508 | + else | |
| 509 | + pass "history clean: $1" | |
| 510 | + fi | |
| 511 | + } | |
| 512 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 513 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 514 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 515 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 516 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 517 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 518 | + PK="pico""bot"; WT=".work""trees" | |
| 519 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | |
| 520 | + audit "run token assignment" 'RUNNER_'"PASS=" | |
| 521 | + audit "fleet default pass" 'xbo''xone' | |
| 522 | + audit "nas password" 'Xbo''xone0909' | |
| 523 | + audit "internal hostname" 'intel-ultra2|macmini|lazarus' | |
| 524 | +else | |
| 525 | + echo " skip history audit (not a git checkout)" | |
| 526 | +fi | |
| 527 | + | |
| 528 | +# ---------------------------------------------------------------- cleanup | |
| 529 | +kill "$MOCK_PID" 2>/dev/null | |
| 530 | +wait "$MOCK_PID" 2>/dev/null | |
| 531 | + | |
| 532 | +# ---------------------------------------------------------------- summary | |
| 533 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 534 | +printf ' passed: %d\n' "$PASS" | |
| 535 | +printf ' failed: %d\n' "$FAIL" | |
| 536 | +if [ "$FAIL" -ne 0 ]; then | |
| 537 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 538 | + exit 1 | |
| 539 | +fi | |
| 540 | +if [ "$PASS" -lt 100 ]; then | |
| 541 | + printf ' %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0" | |
| 542 | + exit 1 | |
| 543 | +fi | |
| 544 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | |
| 545 | +exit 0 |
| 1 | 1 | new file mode 100644 |
| index 0000000..6916af7 | ||
| --- /dev/null | ||
| +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | |
| 3 | + | |
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | |
| 5 | +reviewed like any other source. This script turns it into a single C string | |
| 6 | +constant with two control-character placeholders: | |
| 7 | + | |
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | |
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | |
| 10 | + | |
| 11 | +main() splits the constant on those bytes and emits the macros from | |
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | |
| 13 | +sync with the rest of the bot. | |
| 14 | + | |
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | |
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | |
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | |
| 25 | + | |
| 26 | +TOKENS = "<!--TOKENS-->" | |
| 27 | +MARK_TOKENS = "\u0001" | |
| 28 | +MARK_HANDOFF = "\u0002" | |
| 29 | + | |
| 30 | + | |
| 31 | +def c_literal(text): | |
| 32 | + """Escape text for a C string literal, one line per source line.""" | |
| 33 | + out = [] | |
| 34 | + for line in text.splitlines(True): | |
| 35 | + piece = [] | |
| 36 | + for ch in line: | |
| 37 | + if ch == "\\": | |
| 38 | + piece.append("\\\\") | |
| 39 | + elif ch == '"': | |
| 40 | + piece.append('\\"') | |
| 41 | + elif ch == "\n": | |
| 42 | + piece.append("\\n") | |
| 43 | + elif ch == "\r": | |
| 44 | + piece.append("\\r") | |
| 45 | + elif ch == "\t": | |
| 46 | + piece.append("\\t") | |
| 47 | + elif ch == MARK_TOKENS: | |
| 48 | + piece.append("\\001") | |
| 49 | + elif ch == MARK_HANDOFF: | |
| 50 | + piece.append("\\002") | |
| 51 | + elif ord(ch) < 0x20: | |
| 52 | + piece.append("\\%03o" % ord(ch)) | |
| 53 | + else: | |
| 54 | + piece.append(ch) | |
| 55 | + out.append(' "%s"\n' % "".join(piece)) | |
| 56 | + return "".join(out) | |
| 57 | + | |
| 58 | + | |
| 59 | +def render(): | |
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | |
| 61 | + html = f.read() | |
| 62 | + | |
| 63 | + if TOKENS not in html: | |
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | |
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | |
| 66 | + | |
| 67 | + # Handoff script goes right before the closing body tag. | |
| 68 | + if "</body>" not in html: | |
| 69 | + raise SystemExit("src/ui.html has no </body>") | |
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | |
| 71 | + | |
| 72 | + header = ( | |
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | |
| 74 | + "#ifndef SX_NETCHECK_UI_HTML_H\n" | |
| 75 | + "#define SX_NETCHECK_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_NETCHECK_UI_HTML_H */\n" | |
| 80 | + ) | |
| 81 | + return header | |
| 82 | + | |
| 83 | + | |
| 84 | +def main(): | |
| 85 | + header = render() | |
| 86 | + check = "--check" in sys.argv[1:] | |
| 87 | + if check: | |
| 88 | + try: | |
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | |
| 90 | + cur = f.read() | |
| 91 | + except OSError: | |
| 92 | + cur = "" | |
| 93 | + if cur != header: | |
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | |
| 95 | + return 1 | |
| 96 | + print("src/ui_html.h is up to date") | |
| 97 | + return 0 | |
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | |
| 99 | + f.write(header) | |
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + sys.exit(main()) | |
| 0 | 106 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f692b12 | index 0000000..f692b12 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | ||
| 2 | +plugin_netcheck | ||
| 3 | +plugin_netcheck.exe | ||
| 4 | +plugin_netcheck.musl | ||
| 5 | +plugin_netcheck.arm64 | ||
| 6 | +plugin_netcheck.macos-arm64 | ||
| 7 | +plugin_netcheck.macos-x86_64 | ||
| 8 | +bin/ | ||
| 9 | + | ||
| 10 | +# local scratch | ||
| 11 | +*.tmp | ||
| 12 | +*.log | ||
| 13 | + | ||
| 14 | +# python tooling | ||
| 15 | +__pycache__/ | ||
| 16 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..cc65982 | index 0000000..cc65982 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,79 @@ | @@ -0,0 +1,79 @@ | ||
| 1 | +# plugin_netcheck - SCORPIOX BOT open-source network diagnostics for your node | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_netcheck | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_netcheck.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_netcheck.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_netcheck.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_netcheck (run this on macOS) | ||
| 9 | +# make ui regenerate src/ui_html.h from src/ui.html | ||
| 10 | +# make test build + run tests/run.sh | ||
| 11 | +# make e2e build + run tests/e2e.py (Playwright) | ||
| 12 | +# make clean | ||
| 13 | +# | ||
| 14 | +# The resolver deadline runs in a worker thread, so every POSIX leg links | ||
| 15 | +# -lpthread (musl and macOS carry pthread inside libc). | ||
| 16 | + | ||
| 17 | +CC ?= cc | ||
| 18 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src | ||
| 19 | +MUSL_CC ?= musl-gcc | ||
| 20 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 21 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 22 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 23 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 24 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static | ||
| 25 | +PTHREAD := -lpthread | ||
| 26 | +SRC := src/plugin_netcheck.c | ||
| 27 | +UI_SRC := src/ui.html | ||
| 28 | +UI_HDR := src/ui_html.h | ||
| 29 | +BIN := plugin_netcheck | ||
| 30 | +EXE := plugin_netcheck.exe | ||
| 31 | + | ||
| 32 | +.PHONY: all native musl arm64 win64 macos ui test e2e clean help | ||
| 33 | + | ||
| 34 | +all: native | ||
| 35 | + | ||
| 36 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | ||
| 37 | + @echo "==> regenerating $(UI_HDR)" | ||
| 38 | + python3 tools/gen_ui.py | ||
| 39 | + | ||
| 40 | +ui: $(UI_HDR) | ||
| 41 | + | ||
| 42 | +native: $(BIN) | ||
| 43 | + | ||
| 44 | +$(BIN): $(SRC) $(UI_HDR) | ||
| 45 | + @echo "==> native build ($(CC))" | ||
| 46 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(PTHREAD) | ||
| 47 | + | ||
| 48 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 49 | +musl: $(SRC) $(UI_HDR) | ||
| 50 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 51 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) $(PTHREAD) | ||
| 52 | + | ||
| 53 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 54 | +arm64: $(SRC) $(UI_HDR) | ||
| 55 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 56 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) $(PTHREAD) | ||
| 57 | + | ||
| 58 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 59 | +win64: $(SRC) $(UI_HDR) | ||
| 60 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 61 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) -lws2_32 -liphlpapi | ||
| 62 | + | ||
| 63 | +# Apple clang build (run this on macOS) | ||
| 64 | +macos: $(SRC) $(UI_HDR) | ||
| 65 | + @echo "==> Apple clang build" | ||
| 66 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(PTHREAD) | ||
| 67 | + | ||
| 68 | +test: native | ||
| 69 | + @sh tests/run.sh | ||
| 70 | + | ||
| 71 | +e2e: native | ||
| 72 | + @python3 tests/e2e.py | ||
| 73 | + | ||
| 74 | +clean: | ||
| 75 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 76 | + rm -rf bin | ||
| 77 | + | ||
| 78 | +help: | ||
| 79 | + @echo "make | make musl | make arm64 | make win64 | make macos | make ui | make test | make e2e | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..5967b4b | index 0000000..5967b4b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +# netcheck — Network Diagnostics From This Node | ||
| 2 | + | ||
| 3 | +**Binary:** `plugin_netcheck` · **Slug:** `netcheck` · **Category:** `network` · **License:** MIT | ||
| 4 | + | ||
| 5 | +A zero-dependency, single-binary SCORPIOX BOT plugin that runs network | ||
| 6 | +diagnostics **on the node it is installed on** and shows the result in a dark / | ||
| 7 | +light panel that looks like part of SCORPIOX BOT. | ||
| 8 | + | ||
| 9 | +| Action | Query | What it does | | ||
| 10 | +|---|---|---| | ||
| 11 | +| `ifaces` | `?action=ifaces` | Lists every interface with its address, netmask, broadcast, family and up/down state, plus the configured DNS servers. | | ||
| 12 | +| `dns` | `?action=dns&host=example.com` | Resolves a name through the node's resolver with a 3 s deadline and reports every address. | | ||
| 13 | +| `tcp` | `?action=tcp&host=example.com&port=443` | Three non-blocking connects, reported as samples plus min / avg / max. | | ||
| 14 | +| `http` | `?action=http&url=http://example.com/` | One `HEAD` request over plain TCP. Status line and header count only — the body is never read and redirects are never followed. | | ||
| 15 | +| `info` | `?action=info` | Plugin identity, the action list and the configured deadlines. | | ||
| 16 | + | ||
| 17 | +`GET` with no `action` serves the HTML panel. | ||
| 18 | + | ||
| 19 | +## Why this plugin | ||
| 20 | + | ||
| 21 | +When a node is unreachable from the bot, the useful question is never "is the | ||
| 22 | +bot down" but "what does this node see": which interfaces are up, what the | ||
| 23 | +resolver returns, whether a port is actually accepting, and whether a URL | ||
| 24 | +answers. netcheck answers all four from inside the node, in one binary, with no | ||
| 25 | +`curl`, no `dig`, no `ping`, no `ss`, and no TLS library. | ||
| 26 | + | ||
| 27 | +## The no-TLS contract | ||
| 28 | + | ||
| 29 | +There is no TLS library anywhere in the binary, so an `https://` target cannot | ||
| 30 | +be handshaken. netcheck does the only thing it honestly can — a TCP connect to | ||
| 31 | +port 443 — and reports `"tls":"not_checked"` with a note saying the handshake | ||
| 32 | +was not attempted. It never pretends to have validated a certificate. | ||
| 33 | + | ||
| 34 | +## Security model | ||
| 35 | + | ||
| 36 | +netcheck is a node-owner's tool, and it is the plugin that *makes* connections, | ||
| 37 | +so the surface is deliberately small: | ||
| 38 | + | ||
| 39 | +* **Node auth required.** Every action sits behind `require_node_auth()`, which | ||
| 40 | + accepts `X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` and is a | ||
| 41 | + no-op only when `BOT_PASSWORD` is unset. `--meta` stays unauthenticated so | ||
| 42 | + discovery still works. An unauthenticated `curl` to `/plugin_netcheck` must | ||
| 43 | + return **401**. | ||
| 44 | +* **Host validation.** A typed host is accepted only as a DNS hostname label | ||
| 45 | + sequence or a literal IPv4 / IPv6 address (`inet_pton`). Shell | ||
| 46 | + metacharacters, slashes, spaces and punctuation are refused with 400. | ||
| 47 | +* **Port validation.** 1–65535, digits only. | ||
| 48 | +* **URL validation.** `http://` or `https://` only; the scheme, host, port, path | ||
| 49 | + and query are parsed by hand, userinfo is stripped, and the path must begin | ||
| 50 | + with `/`. | ||
| 51 | +* **Hard deadlines.** 3 s for resolution, 3 s per connect, 2 s for the HTTP read. | ||
| 52 | + A typed host cannot make the plugin hang. | ||
| 53 | +* **Body never read.** The HTTP probe sends `HEAD` and stops reading at the end | ||
| 54 | + of the header block, so a 50 GB page costs the same as a 1 KB one. | ||
| 55 | +* **No redirects.** A 3xx is reported with `"redirect":"not_followed"`. | ||
| 56 | +* **One request per call.** No retries on the HTTP path; the TCP path takes | ||
| 57 | + exactly three samples of the same target. | ||
| 58 | + | ||
| 59 | +The trust notice on the card and in `plugin.json` says it plainly: this plugin | ||
| 60 | +opens exactly the outbound connections **you** ask for. | ||
| 61 | + | ||
| 62 | +## Build | ||
| 63 | + | ||
| 64 | +``` | ||
| 65 | +make native build -> ./plugin_netcheck | ||
| 66 | +make musl static musl x86_64 -> ./plugin_netcheck.musl | ||
| 67 | +make arm64 static aarch64 -> ./plugin_netcheck.arm64 | ||
| 68 | +make win64 MinGW-w64 static -> ./plugin_netcheck.exe | ||
| 69 | +make macos Apple clang -> ./plugin_netcheck (run on macOS) | ||
| 70 | +make ui regenerate src/ui_html.h from src/ui.html | ||
| 71 | +make test build + tests/run.sh | ||
| 72 | +make e2e build + tests/e2e.py (Playwright) | ||
| 73 | +make clean | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +On Windows use `powershell -ExecutionPolicy Bypass -File build.ps1`; it | ||
| 77 | +regenerates the page header, compiles a static PE, and refuses to emit anything | ||
| 78 | +that is not a real `MZ` executable. | ||
| 79 | + | ||
| 80 | +The resolver deadline runs in a worker thread, so every POSIX leg links | ||
| 81 | +`-lpthread` (musl and macOS carry pthread inside libc). Windows links | ||
| 82 | +`-lws2_32 -liphlpapi`. | ||
| 83 | + | ||
| 84 | +## The page | ||
| 85 | + | ||
| 86 | +`src/ui.html` is the readable source of the panel; `tools/gen_ui.py` compiles it | ||
| 87 | +into `src/ui_html.h` with two control-byte placeholders that expand into the | ||
| 88 | +bot's theme macros, so the page can never drift from the palette SCORPIOX BOT | ||
| 89 | +actually uses. The theme is decided before first paint in the order | ||
| 90 | +`?theme=` → `localStorage.bot_theme` → `prefers-color-scheme`, and the page | ||
| 91 | +follows the bot's `sx-theme` postMessage without a reload. Its own toggle is | ||
| 92 | +hidden under `?embed=1`. | ||
| 93 | + | ||
| 94 | +No `<script src=>`, no CDN, no emoji, no web fonts. The latency sparkline is a | ||
| 95 | +hand-drawn SVG polyline built from the TCP samples in the page — no chart | ||
| 96 | +library, no network request. | ||
| 97 | + | ||
| 98 | +## Tests | ||
| 99 | + | ||
| 100 | +`tests/run.sh` is fully offline: the resolver, the interface table and the | ||
| 101 | +outbound connect are replaced by three environment hooks the plugin exposes for | ||
| 102 | +exactly this purpose, and the TCP/HTTP legs talk to throwaway listeners started | ||
| 103 | +by `tests/mockd.py` on `127.0.0.1`. | ||
| 104 | + | ||
| 105 | +``` | ||
| 106 | +NETCHECK_MOCK_IFACES "lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,eth0|..." | ||
| 107 | + name|address|netmask|broadcast|family|up | ||
| 108 | +NETCHECK_MOCK_DNS "host=addr,addr;host2=addr" | ||
| 109 | +NETCHECK_MOCK_TIMEOUT 1 -> every resolution reports a deadline miss | ||
| 110 | +``` | ||
| 111 | + | ||
| 112 | +On a real node none of these are set, so the hooks are never consulted. | ||
| 113 | + | ||
| 114 | +`tests/e2e.py` drives the page with Playwright at 1440 / 1024 / 390 CSS pixels | ||
| 115 | +in both themes and asserts there is no horizontal overflow and no console error. | ||
| 116 | + | ||
| 117 | +## Screenshots | ||
| 118 | + | ||
| 119 | +`docs/` holds the panel at 1440, 1024 and 390 px in dark and light. | ||
| 120 | + | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +## Sibling plugins | ||
| 124 | + | ||
| 125 | +netcheck is part of the SCORPIOX BOT open-source plugin family published to | ||
| 126 | +`https://dist.scorpiox.net/bot-plugins/` and mirrored to | ||
| 127 | +`https://plugingit.scorpiox.net/`. See `release-dist.sh` for the six-target | ||
| 128 | +release recipe (linux x86_64 glibc + musl, arm64 musl, macOS arm64 + x86_64, | ||
| 129 | +Windows x86_64) plus `source.tar.gz`. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..fb88b76 | index 0000000..fb88b76 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,55 @@ | @@ -0,0 +1,55 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_netcheck | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_netcheck.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 | +# The link needs -lws2_32 and -liphlpapi: Winsock for getaddrinfo/connect and | ||
| 10 | +# GetAdaptersAddresses for the interface table. | ||
| 11 | + | ||
| 12 | +$ErrorActionPreference = "Stop" | ||
| 13 | +$ScriptDir = $PSScriptRoot | ||
| 14 | +Push-Location $ScriptDir | ||
| 15 | +try { | ||
| 16 | + $Src = Join-Path $ScriptDir "src\plugin_netcheck.c" | ||
| 17 | + $Out = Join-Path $ScriptDir "plugin_netcheck.exe" | ||
| 18 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 19 | + | ||
| 20 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 21 | + | ||
| 22 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | ||
| 23 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 24 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 25 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 26 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 27 | + $Cc = "gcc" | ||
| 28 | + } else { | ||
| 29 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 30 | + } | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + # Regenerate the page header so the binary always matches src/ui.html. | ||
| 34 | + if (Get-Command python -ErrorAction SilentlyContinue) { | ||
| 35 | + python tools\gen_ui.py | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + Write-Host "==> building plugin_netcheck.exe with $Cc" | ||
| 39 | + & $Cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -static ` | ||
| 40 | + -o $Out $Src -lws2_32 -liphlpapi | ||
| 41 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 42 | + | ||
| 43 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 44 | + | ||
| 45 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 46 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 47 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 48 | + throw "output is not a PE executable (missing MZ header)" | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | ||
| 52 | + Write-Host " smoke test: .\plugin_netcheck.exe --meta" | ||
| 53 | +} finally { | ||
| 54 | + Pop-Location | ||
| 55 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..594033c | index 0000000..594033c |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..49f2f54 | index 0000000..49f2f54 |

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8d82321 | index 0000000..8d82321 |

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8427d88 | index 0000000..8427d88 |

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

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3af4b31 | index 0000000..3af4b31 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,26 @@ | @@ -0,0 +1,26 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "netcheck", | ||
| 3 | + "id": "plugin_netcheck", | ||
| 4 | + "name": "netcheck", | ||
| 5 | + "desc": "Net checks", | ||
| 6 | + "title": "Network Diagnostics From This Node", | ||
| 7 | + "summary": "Zero-dependency network diagnostics that run on the node itself: list the interfaces and their addresses, show the configured DNS servers, resolve a name, measure a TCP connect three times and report min/avg/max with a latency sparkline, and check a plain-HTTP URL for reachability with a single HEAD request that reads only the status line and headers. There is no TLS library in the binary, so an https target is checked as a TCP connect to 443 and reported as tls not_checked. Dark and light themes follow the bot, the layout stays fluid down to 390px and inside the Chat floating window, and nothing is written to disk.", | ||
| 8 | + "category": "network", | ||
| 9 | + "version": "1.0.0", | ||
| 10 | + "license": "MIT", | ||
| 11 | + "capabilities": [ | ||
| 12 | + "outbound_tcp_user_requested", | ||
| 13 | + "dns_resolve", | ||
| 14 | + "iface_list" | ||
| 15 | + ], | ||
| 16 | + "trust_notice": "Executes native C code on your node. It reads the local interface table and the configured DNS servers, and it opens exactly the outbound connections you ask for: one DNS lookup, a TCP connect, or one HEAD request over plain HTTP. Response bodies are never read, redirects are never followed, hosts are validated as hostnames or IP literals, ports are limited to 1-65535, and every phase has a hard 3 second deadline. There is no TLS library, so an https URL is only checked for a TCP connect to 443. Every action requires node authentication.", | ||
| 17 | + "author": "SCORPIOX INC", | ||
| 18 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-netcheck", | ||
| 19 | + "ldflags_posix": [ | ||
| 20 | + "-lpthread" | ||
| 21 | + ], | ||
| 22 | + "ldflags_win64": [ | ||
| 23 | + "-lws2_32", | ||
| 24 | + "-liphlpapi" | ||
| 25 | + ] | ||
| 26 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..232f187 | index 0000000..232f187 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh - build, scan and publish plugin_netcheck to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | +# ./release-dist.sh --standalone # use this script even if the CLI is installed | ||
| 27 | +# # (needed for plugins that link extra Win32 libs, | ||
| 28 | +# # which the CLI's fixed link line cannot express) | ||
| 29 | + | ||
| 30 | +set -euo pipefail | ||
| 31 | + | ||
| 32 | +SLUG="netcheck" | ||
| 33 | +ID="plugin_netcheck" | ||
| 34 | +VERSION="1.0.0" | ||
| 35 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 36 | + | ||
| 37 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 38 | +cd "$ROOT" | ||
| 39 | + | ||
| 40 | +DRY_RUN=0 | ||
| 41 | +DO_MACOS=1 | ||
| 42 | +DO_MIRROR=1 | ||
| 43 | +STANDALONE=0 | ||
| 44 | +for arg in "$@"; do | ||
| 45 | + case "$arg" in | ||
| 46 | + --standalone) STANDALONE=1 ;; | ||
| 47 | + --dry-run) DRY_RUN=1 ;; | ||
| 48 | + --no-macos) DO_MACOS=0 ;; | ||
| 49 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 50 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | ||
| 51 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 52 | + esac | ||
| 53 | +done | ||
| 54 | + | ||
| 55 | +DIST_HOST="${DIST_HOST:-}" | ||
| 56 | +DIST_PASS="${DIST_PASS:-}" | ||
| 57 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 58 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 59 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 60 | + | ||
| 61 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 62 | +mkdir -p "$STAGE" | ||
| 63 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 64 | + | ||
| 65 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 66 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 67 | + | ||
| 68 | +# ---------------------------------------------------------------- 0. preflight | ||
| 69 | +say "0/7 preflight" | ||
| 70 | + | ||
| 71 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 72 | + say "using scorpiox-cli-botplugin publish" | ||
| 73 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 74 | +fi | ||
| 75 | +echo " running the standalone pipeline" | ||
| 76 | + | ||
| 77 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 78 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 79 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 80 | +echo " version $VERSION" | ||
| 81 | +echo " commit $COMMIT" | ||
| 82 | + | ||
| 83 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 84 | +say "1/7 secret & LAN scan (full history)" | ||
| 85 | + | ||
| 86 | +SCAN_TMP="$STAGE/history.txt" | ||
| 87 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 88 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 89 | +# itself a scan definition - otherwise this file's own detector patterns (and the | ||
| 90 | +# test suite's identical checks) read as findings in every historical revision of | ||
| 91 | +# them. A real secret on any other line still hits. | ||
| 92 | +git log -p --all 2>/dev/null \ | ||
| 93 | + | grep -v '^Author: ' \ | ||
| 94 | + | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \ | ||
| 95 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 96 | +HITS=0 | ||
| 97 | +scan() { # scan <label> <regex> | ||
| 98 | + local out | ||
| 99 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 100 | + if [ -n "$out" ]; then | ||
| 101 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 102 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 103 | + HITS=$((HITS + 1)) | ||
| 104 | + else | ||
| 105 | + printf ' ok %s\n' "$1" | ||
| 106 | + fi | ||
| 107 | +} | ||
| 108 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 109 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 110 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 111 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 112 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 113 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 114 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 115 | +P_ROOT="/codebases" | ||
| 116 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 117 | +P_WT=".work""trees" | ||
| 118 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 119 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 120 | +if [ "$HITS" -ne 0 ]; then | ||
| 121 | + die "secret scan found $HITS problem(s) - refusing to publish" | ||
| 122 | +fi | ||
| 123 | +echo " clean: 0 hits" | ||
| 124 | + | ||
| 125 | +# ---------------------------------------------------------------- 2. build | ||
| 126 | +say "2/7 build targets" | ||
| 127 | + | ||
| 128 | +# linux-x86_64 (glibc, native) | ||
| 129 | +if command -v cc >/dev/null 2>&1; then | ||
| 130 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c -lpthread || die "native build failed" | ||
| 131 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 132 | +else | ||
| 133 | + die "no native cc found" | ||
| 134 | +fi | ||
| 135 | + | ||
| 136 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | ||
| 137 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 138 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c -lpthread \ | ||
| 139 | + || die "musl build failed" | ||
| 140 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 141 | +else | ||
| 142 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 143 | +fi | ||
| 144 | + | ||
| 145 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | ||
| 146 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 147 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c -lpthread \ | ||
| 148 | + || die "arm64 build failed" | ||
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 150 | +else | ||
| 151 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | ||
| 152 | +fi | ||
| 153 | + | ||
| 154 | +# windows-x86_64 (static PE) | ||
| 155 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 156 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \ | ||
| 157 | + -I src -o "$STAGE/$ID.exe" src/$ID.c -lws2_32 -liphlpapi || die "MinGW build failed" | ||
| 158 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 159 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 160 | +else | ||
| 161 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 162 | +fi | ||
| 163 | + | ||
| 164 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | ||
| 165 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 166 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 167 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 168 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 169 | + echo " building macOS legs on $MAC_HOST" | ||
| 170 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 171 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 172 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 173 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 174 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 175 | + fi | ||
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 177 | + tar -czf "$STAGE/src.tgz" src | ||
| 178 | + if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \ | ||
| 179 | + && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then | ||
| 180 | + # Build straight from the uploaded file - no src/ tree on the remote. | ||
| 181 | + for slice in arm64 x86_64; do | ||
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c -lpthread" \ | ||
| 184 | + 2>/dev/null; then | ||
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 187 | + else | ||
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 189 | + fi | ||
| 190 | + done | ||
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | ||
| 192 | + else | ||
| 193 | + echo " warn: could not upload source to $MAC_HOST" | ||
| 194 | + fi | ||
| 195 | + else | ||
| 196 | + echo " warn: cannot reach macOS builder $MAC_HOST" | ||
| 197 | + fi | ||
| 198 | +else | ||
| 199 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | ||
| 200 | +fi | ||
| 201 | + | ||
| 202 | +# ---------------------------------------------------------------- 3. manifest | ||
| 203 | +say "3/7 manifest + checksums" | ||
| 204 | + | ||
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 209 | + | ||
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> | ||
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" | ||
| 212 | + [ -f "$file" ] || return 0 | ||
| 213 | + local sha size | ||
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +{ | ||
| 221 | + printf '{\n' | ||
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 223 | + printf ' "id": "%s",\n' "$ID" | ||
| 224 | + printf ' "name": "netcheck",\n' | ||
| 225 | + printf ' "desc": "Net checks",\n' | ||
| 226 | + printf ' "title": "Markdown Notes",\n' | ||
| 227 | + printf ' "summary": "Zero-dependency network diagnostics that run on the node itself: list the interfaces and their addresses, show the configured DNS servers, resolve a name, measure a TCP connect three times and report min/avg/max with a latency sparkline, and check a plain-HTTP URL for reachability with a single HEAD request that reads only the status line and headers. There is no TLS library in the binary, so an https target is checked as a TCP connect to 443 and reported as tls not_checked. Dark and light themes follow the bot, the layout stays fluid down to 390px and inside the Chat floating window, and nothing is written to disk.",\n' | ||
| 228 | + printf ' "category": "network",\n' | ||
| 229 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 230 | + printf ' "license": "MIT",\n' | ||
| 231 | + printf ' "trust_notice": "Executes native C code on your node. It reads the local interface table and the configured DNS servers, and it opens exactly the outbound connections you ask for: one DNS lookup, a TCP connect, or one HEAD request over plain HTTP. Response bodies are never read, redirects are never followed, hosts are validated as hostnames or IP literals, ports are limited to 1-65535, and every phase has a hard 3 second deadline. There is no TLS library, so an https URL is only checked for a TCP connect to 443. Every action requires node authentication.",\n' | ||
| 232 | + printf ' "capabilities": ["outbound_tcp_user_requested", "dns_resolve", "iface_list"],\n' | ||
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 241 | + printf ' "targets": {\n' | ||
| 242 | + first=1 | ||
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | ||
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | ||
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | ||
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | ||
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | ||
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | ||
| 250 | + printf '\n }\n}\n' | ||
| 251 | +} > "$STAGE/manifest.json" | ||
| 252 | + | ||
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 254 | + || die "generated manifest.json is not valid JSON" | ||
| 255 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | ||
| 256 | + | ||
| 257 | +# SHA256SUMS - relative paths, exactly as published | ||
| 258 | +( cd "$STAGE" | ||
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 266 | + true ) > "$STAGE/SHA256SUMS" | ||
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 268 | + | ||
| 269 | +# ---------------------------------------------------------------- 4. stage | ||
| 270 | +say "4/7 stage tree" | ||
| 271 | +PKG="$STAGE/pkg" | ||
| 272 | +mkdir -p "$PKG" | ||
| 273 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 274 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | ||
| 275 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | ||
| 276 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | ||
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | ||
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | ||
| 279 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | ||
| 280 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | ||
| 281 | + | ||
| 282 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 283 | + say "dry run - leaving the staging tree in $PKG" | ||
| 284 | + trap - EXIT | ||
| 285 | + exit 0 | ||
| 286 | +fi | ||
| 287 | + | ||
| 288 | +# ---------------------------------------------------------------- 5. upload | ||
| 289 | +say "5/7 upload to the dist server" | ||
| 290 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | ||
| 291 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 292 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 293 | +if [ -n "$DIST_PASS" ]; then | ||
| 294 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 295 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 296 | +fi | ||
| 297 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 298 | + | ||
| 299 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 300 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 301 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 302 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 303 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 304 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 305 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 306 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 307 | + || die "remote extract failed" | ||
| 308 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 309 | + | ||
| 310 | +# latest.json = copy of this version's manifest | ||
| 311 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 312 | + || die "latest.json update failed" | ||
| 313 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 314 | + | ||
| 315 | +# index.json - merge, preserving every sibling <slug>/latest.json | ||
| 316 | +say "index.json merge" | ||
| 317 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 318 | +import json, os, sys, glob | ||
| 319 | +slug = sys.argv[1] | ||
| 320 | +entries = {} | ||
| 321 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 322 | + s = os.path.dirname(p) | ||
| 323 | + try: | ||
| 324 | + entries[s] = json.load(open(p)) | ||
| 325 | + except Exception: | ||
| 326 | + pass | ||
| 327 | +index = { | ||
| 328 | + 'ok': True, | ||
| 329 | + 'service': 'bot-plugins-dist', | ||
| 330 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 331 | + 'count': len(entries), | ||
| 332 | + 'slugs': sorted(entries), | ||
| 333 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 334 | +} | ||
| 335 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 336 | +os.replace('index.json.tmp', 'index.json') | ||
| 337 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 338 | +PY" || die "index.json merge failed" | ||
| 339 | + | ||
| 340 | +# ---------------------------------------------------------------- 6. mirror | ||
| 341 | +say "6/7 plugingit mirror" | ||
| 342 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 343 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 344 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | ||
| 345 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 346 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 347 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 348 | +else | ||
| 349 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 350 | +fi | ||
| 351 | + | ||
| 352 | +# ---------------------------------------------------------------- 7. verify | ||
| 353 | +say "7/7 verify" | ||
| 354 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 355 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 356 | +if [ "$CODE" = "200" ]; then | ||
| 357 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 358 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 359 | +else | ||
| 360 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 361 | +fi | ||
| 362 | + | ||
| 363 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 364 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 365 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6d0d630 | index 0000000..6d0d630 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_netcheck.c | +++ b/src/plugin_netcheck.c | ||
| @@ -0,0 +1,1608 @@ | @@ -0,0 +1,1608 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_netcheck - SCORPIOX BOT open-source network diagnostics from this node | ||
| 3 | + * | ||
| 4 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | ||
| 6 | + * 2. ?action=ifaces | dns&host= | tcp&host=&port= | http&url= | info -> JSON node API | ||
| 7 | + * 3. GET (default) -> responsive HTML diagnostics UI | ||
| 8 | + * | ||
| 9 | + * Everything it reports is about the node it runs on: the interfaces and their | ||
| 10 | + * addresses, the configured DNS servers, a name resolution, a TCP connect | ||
| 11 | + * latency, and a plain-HTTP reachability check (status line and headers only, | ||
| 12 | + * body never read). The only outbound connections are the ones the node owner | ||
| 13 | + * asks for by typing a host into the box, and every one of them sits behind | ||
| 14 | + * node authentication, so the plugin is not a blind SSRF pivot. | ||
| 15 | + * | ||
| 16 | + * Interfaces come from getifaddrs(3) on Linux/macOS and from | ||
| 17 | + * GetAdaptersAddresses on Windows. DNS uses getaddrinfo guarded by a deadline | ||
| 18 | + * (a worker thread, because the resolver itself is blocking). TCP latency is | ||
| 19 | + * the mean of three non-blocking connect() round trips. HTTP is a raw HEAD | ||
| 20 | + * request over TCP - there is no TLS library anywhere in this binary, so an | ||
| 21 | + * https:// target is reported as a TCP connect to port 443 with | ||
| 22 | + * "tls":"not_checked". | ||
| 23 | + * | ||
| 24 | + * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang | ||
| 25 | + * and x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 26 | + * scorpiox-server on the node. | ||
| 27 | + * | ||
| 28 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 29 | + */ | ||
| 30 | + | ||
| 31 | +/* Must come before every include: iphlpapi.h and ws2tcpip.h gate | ||
| 32 | + * GetAdaptersAddresses and the IPv6 helpers on it, and MinGW defaults to 0x502 | ||
| 33 | + * (Server 2003) which hides all of them. */ | ||
| 34 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 35 | +# define _WIN32_WINNT 0x0601 | ||
| 36 | +#endif | ||
| 37 | + | ||
| 38 | +#if !defined(_WIN32) | ||
| 39 | +# define _POSIX_C_SOURCE 200809L | ||
| 40 | +# define _DEFAULT_SOURCE 1 | ||
| 41 | +# if defined(__APPLE__) | ||
| 42 | +# define _DARWIN_C_SOURCE 1 | ||
| 43 | +# endif | ||
| 44 | +#endif | ||
| 45 | + | ||
| 46 | +#include <stdio.h> | ||
| 47 | +#include <stdlib.h> | ||
| 48 | +#include <string.h> | ||
| 49 | +#include <ctype.h> | ||
| 50 | +#include <errno.h> | ||
| 51 | +#include <time.h> | ||
| 52 | + | ||
| 53 | +#if defined(_WIN32) | ||
| 54 | +# define WIN32_LEAN_AND_MEAN | ||
| 55 | +# include <winsock2.h> | ||
| 56 | +# include <ws2tcpip.h> | ||
| 57 | +# include <windows.h> | ||
| 58 | +# include <iphlpapi.h> | ||
| 59 | +# define sx_popen _popen | ||
| 60 | +# define sx_pclose _pclose | ||
| 61 | +# define sx_close_socket closesocket | ||
| 62 | +# define SX_SOCK_T SOCKET | ||
| 63 | +# define SX_SOCK_INVALID INVALID_SOCKET | ||
| 64 | +#else | ||
| 65 | +# include <unistd.h> | ||
| 66 | +# include <ifaddrs.h> | ||
| 67 | +# include <net/if.h> | ||
| 68 | +# include <netdb.h> | ||
| 69 | +# include <sys/types.h> | ||
| 70 | +# include <sys/socket.h> | ||
| 71 | +# include <sys/select.h> | ||
| 72 | +# include <sys/time.h> | ||
| 73 | +# include <netinet/in.h> | ||
| 74 | +# include <arpa/inet.h> | ||
| 75 | +# include <fcntl.h> | ||
| 76 | +# include <pthread.h> | ||
| 77 | +# define sx_popen popen | ||
| 78 | +# define sx_pclose pclose | ||
| 79 | +# define sx_close_socket close | ||
| 80 | +# define SX_SOCK_T int | ||
| 81 | +# define SX_SOCK_INVALID (-1) | ||
| 82 | +#endif | ||
| 83 | + | ||
| 84 | +#include "bot_theme_plugin.h" | ||
| 85 | +#include "ui_html.h" | ||
| 86 | + | ||
| 87 | +#define PLUGIN_SLUG "netcheck" | ||
| 88 | +#define PLUGIN_ID "plugin_netcheck" | ||
| 89 | +#define PLUGIN_VER "1.0.0" | ||
| 90 | + | ||
| 91 | +#define MAX_IFACES 128 | ||
| 92 | +#define MAX_LINE 1024 | ||
| 93 | +#define MAX_HOST 256 | ||
| 94 | +#define MAX_PATHZ 256 | ||
| 95 | +#define MAX_SAMPLES 3 | ||
| 96 | +#define MAX_RES 16 | ||
| 97 | + | ||
| 98 | +/* Hard ceilings so a typed host cannot make the plugin hang forever. Each | ||
| 99 | + * phase (resolve, connect, read) gets its own budget. */ | ||
| 100 | +#define DNS_MS 3000 | ||
| 101 | +#define TCP_MS 3000 | ||
| 102 | +#define READ_MS 2000 | ||
| 103 | + | ||
| 104 | +/* ------------------------------------------------------------------ */ | ||
| 105 | +/* Small utilities */ | ||
| 106 | +/* ------------------------------------------------------------------ */ | ||
| 107 | + | ||
| 108 | +static void url_decode(char *s) | ||
| 109 | +{ | ||
| 110 | + char *o = s; | ||
| 111 | + if (!s) return; | ||
| 112 | + while (*s) { | ||
| 113 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 114 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 115 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 116 | + *o++ = (char)((hi << 4) | lo); | ||
| 117 | + s += 3; | ||
| 118 | + } else if (*s == '+') { | ||
| 119 | + *o++ = ' '; | ||
| 120 | + s++; | ||
| 121 | + } else { | ||
| 122 | + *o++ = *s++; | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + *o = '\0'; | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 129 | +{ | ||
| 130 | + size_t klen; | ||
| 131 | + const char *p; | ||
| 132 | + | ||
| 133 | + if (!out || outsz == 0) return 0; | ||
| 134 | + out[0] = '\0'; | ||
| 135 | + if (!qs) return 0; | ||
| 136 | + klen = strlen(key); | ||
| 137 | + p = qs; | ||
| 138 | + while (*p) { | ||
| 139 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 140 | + const char *v = p + klen + 1; | ||
| 141 | + size_t i = 0; | ||
| 142 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 143 | + out[i++] = *v++; | ||
| 144 | + out[i] = '\0'; | ||
| 145 | + url_decode(out); | ||
| 146 | + return 1; | ||
| 147 | + } | ||
| 148 | + p = strchr(p, '&'); | ||
| 149 | + if (!p) break; | ||
| 150 | + p++; | ||
| 151 | + } | ||
| 152 | + return 0; | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +static void json_str(const char *s) | ||
| 156 | +{ | ||
| 157 | + putchar('"'); | ||
| 158 | + for (; s && *s; s++) { | ||
| 159 | + unsigned char c = (unsigned char)*s; | ||
| 160 | + switch (c) { | ||
| 161 | + case '"': fputs("\\\"", stdout); break; | ||
| 162 | + case '\\': fputs("\\\\", stdout); break; | ||
| 163 | + case '\n': fputs("\\n", stdout); break; | ||
| 164 | + case '\r': fputs("\\r", stdout); break; | ||
| 165 | + case '\t': fputs("\\t", stdout); break; | ||
| 166 | + default: | ||
| 167 | + if (c < 0x20) printf("\\u%04x", c); | ||
| 168 | + else putchar(c); | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + putchar('"'); | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +static void str_copy(char *dst, size_t sz, const char *src) | ||
| 175 | +{ | ||
| 176 | + size_t n; | ||
| 177 | + if (!dst || sz == 0) return; | ||
| 178 | + if (!src) { dst[0] = '\0'; return; } | ||
| 179 | + n = strlen(src); | ||
| 180 | + if (n >= sz) n = sz - 1; | ||
| 181 | + memcpy(dst, src, n); | ||
| 182 | + dst[n] = '\0'; | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +static void str_trim(char *s) | ||
| 186 | +{ | ||
| 187 | + char *p; | ||
| 188 | + size_t n; | ||
| 189 | + if (!s) return; | ||
| 190 | + p = s; | ||
| 191 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 192 | + if (p != s) memmove(s, p, strlen(p) + 1); | ||
| 193 | + n = strlen(s); | ||
| 194 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +static void str_lower(char *s) | ||
| 198 | +{ | ||
| 199 | + for (; s && *s; s++) *s = (char)tolower((unsigned char)*s); | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +static long long now_ms(void) | ||
| 203 | +{ | ||
| 204 | +#if defined(_WIN32) | ||
| 205 | + FILETIME ft; | ||
| 206 | + ULARGE_INTEGER u; | ||
| 207 | + GetSystemTimeAsFileTime(&ft); | ||
| 208 | + u.LowPart = ft.dwLowDateTime; | ||
| 209 | + u.HighPart = ft.dwHighDateTime; | ||
| 210 | + return (long long)(u.QuadPart / 10000ULL); | ||
| 211 | +#else | ||
| 212 | + struct timeval tv; | ||
| 213 | + gettimeofday(&tv, NULL); | ||
| 214 | + return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); | ||
| 215 | +#endif | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +static void utc_stamp(time_t t, char *buf, size_t sz) | ||
| 219 | +{ | ||
| 220 | + struct tm tmv; | ||
| 221 | +#if defined(_WIN32) | ||
| 222 | + gmtime_s(&tmv, &t); | ||
| 223 | +#else | ||
| 224 | + gmtime_r(&t, &tmv); | ||
| 225 | +#endif | ||
| 226 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/* ------------------------------------------------------------------ */ | ||
| 230 | +/* Node authentication */ | ||
| 231 | +/* ------------------------------------------------------------------ */ | ||
| 232 | + | ||
| 233 | +static void require_node_auth(void) | ||
| 234 | +{ | ||
| 235 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 236 | + const char *xp; | ||
| 237 | + const char *auth; | ||
| 238 | + const char *qs; | ||
| 239 | + char qpwd[256]; | ||
| 240 | + | ||
| 241 | + if (!np || !*np) return; | ||
| 242 | + | ||
| 243 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 244 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 245 | + | ||
| 246 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 247 | + if (auth) { | ||
| 248 | + while (*auth == ' ') auth++; | ||
| 249 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 250 | + auth += 7; | ||
| 251 | + while (*auth == ' ') auth++; | ||
| 252 | + if (strcmp(auth, np) == 0) return; | ||
| 253 | + } | ||
| 254 | + } | ||
| 255 | + | ||
| 256 | + qs = getenv("QUERY_STRING"); | ||
| 257 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 258 | + return; | ||
| 259 | + | ||
| 260 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 261 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 262 | + "Cache-Control: no-store\r\n" | ||
| 263 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 264 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 265 | + exit(0); | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +/* ------------------------------------------------------------------ */ | ||
| 269 | +/* Address formatting */ | ||
| 270 | +/* ------------------------------------------------------------------ */ | ||
| 271 | + | ||
| 272 | +/* Render a sockaddr into a printable address string. Returns the family | ||
| 273 | + * (AF_INET / AF_INET6) or 0 when the address cannot be rendered. */ | ||
| 274 | +static int addr_text(const struct sockaddr *sa, char *out, size_t outsz) | ||
| 275 | +{ | ||
| 276 | + if (!sa || !out || outsz == 0) return 0; | ||
| 277 | + out[0] = '\0'; | ||
| 278 | + | ||
| 279 | + switch (sa->sa_family) { | ||
| 280 | + case AF_INET: { | ||
| 281 | + const struct sockaddr_in *in = (const struct sockaddr_in *)sa; | ||
| 282 | + if (inet_ntop(AF_INET, &in->sin_addr, out, (unsigned int)outsz)) | ||
| 283 | + return AF_INET; | ||
| 284 | + return 0; | ||
| 285 | + } | ||
| 286 | + case AF_INET6: { | ||
| 287 | + const struct sockaddr_in6 *in6 = (const struct sockaddr_in6 *)sa; | ||
| 288 | + if (inet_ntop(AF_INET6, &in6->sin6_addr, out, (unsigned int)outsz)) | ||
| 289 | + return AF_INET6; | ||
| 290 | + return 0; | ||
| 291 | + } | ||
| 292 | + default: | ||
| 293 | + return 0; | ||
| 294 | + } | ||
| 295 | +} | ||
| 296 | + | ||
| 297 | +static int netmask_text(const struct sockaddr *sa, char *out, size_t outsz) | ||
| 298 | +{ | ||
| 299 | + if (!sa || sa->sa_family != AF_INET || !out || outsz == 0) return 0; | ||
| 300 | + return inet_ntop(AF_INET, | ||
| 301 | + &((const struct sockaddr_in *)sa)->sin_addr, | ||
| 302 | + out, (unsigned int)outsz) ? 1 : 0; | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +/* ------------------------------------------------------------------ */ | ||
| 306 | +/* Interface collection */ | ||
| 307 | +/* ------------------------------------------------------------------ */ | ||
| 308 | +typedef struct { | ||
| 309 | + char name[64]; | ||
| 310 | + char addr[64]; | ||
| 311 | + char mask[64]; | ||
| 312 | + char broad[64]; | ||
| 313 | + int family; /* 4 or 6 */ | ||
| 314 | + int loopback; | ||
| 315 | + int up; | ||
| 316 | + int running; | ||
| 317 | +} iface_t; | ||
| 318 | + | ||
| 319 | +static iface_t g_ifaces[MAX_IFACES]; | ||
| 320 | +static int g_iface_count; | ||
| 321 | + | ||
| 322 | +static int is_loopback_text(const char *a) | ||
| 323 | +{ | ||
| 324 | + if (!a) return 0; | ||
| 325 | + if (strncmp(a, "127.", 4) == 0) return 1; | ||
| 326 | + if (strcmp(a, "::1") == 0) return 1; | ||
| 327 | + return 0; | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +static void iface_add(const char *name, const struct sockaddr *sa, | ||
| 331 | + const struct sockaddr *mask, const struct sockaddr *broad, | ||
| 332 | + int up, int running) | ||
| 333 | +{ | ||
| 334 | + iface_t *f; | ||
| 335 | + char a[64]; | ||
| 336 | + int fam; | ||
| 337 | + | ||
| 338 | + if (g_iface_count >= MAX_IFACES) return; | ||
| 339 | + fam = addr_text(sa, a, sizeof a); | ||
| 340 | + if (!fam) return; | ||
| 341 | + | ||
| 342 | + f = &g_ifaces[g_iface_count++]; | ||
| 343 | + memset(f, 0, sizeof *f); | ||
| 344 | + str_copy(f->name, sizeof f->name, name ? name : "?"); | ||
| 345 | + str_copy(f->addr, sizeof f->addr, a); | ||
| 346 | + f->family = (fam == AF_INET6) ? 6 : 4; | ||
| 347 | + f->loopback = is_loopback_text(f->addr); | ||
| 348 | + f->up = up; | ||
| 349 | + f->running = running; | ||
| 350 | + if (mask) netmask_text(mask, f->mask, sizeof f->mask); | ||
| 351 | + if (broad) addr_text(broad, f->broad, sizeof f->broad); | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +#if defined(_WIN32) | ||
| 355 | +/* ASCII-fold a wide adapter name; Windows adapter names are alphanumeric with | ||
| 356 | + * spaces, dashes and dots, so a byte-per-wchar fold is lossless in practice. */ | ||
| 357 | +static void wide_to_ascii(const wchar_t *w, char *out, size_t outsz) | ||
| 358 | +{ | ||
| 359 | + size_t i = 0; | ||
| 360 | + if (outsz) out[0] = '\0'; | ||
| 361 | + if (!w || !out || outsz == 0) return; | ||
| 362 | + for (i = 0; i + 1 < outsz && w[i]; i++) | ||
| 363 | + out[i] = (char)((unsigned char)w[i]); | ||
| 364 | + out[i] = '\0'; | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +static PIP_ADAPTER_ADDRESSES fetch_adapters(ULONG flags) | ||
| 368 | +{ | ||
| 369 | + ULONG want = 0; | ||
| 370 | + ULONG rc; | ||
| 371 | + PIP_ADAPTER_ADDRESSES adapters; | ||
| 372 | + | ||
| 373 | + rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &want); | ||
| 374 | + if (rc != ERROR_SUCCESS && rc != ERROR_BUFFER_OVERFLOW) return NULL; | ||
| 375 | + if (want < 2048) want = 2048; | ||
| 376 | + adapters = (PIP_ADAPTER_ADDRESSES)malloc(want + 1024); | ||
| 377 | + if (!adapters) return NULL; | ||
| 378 | + rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapters, &want); | ||
| 379 | + if (rc != ERROR_SUCCESS) { free(adapters); return NULL; } | ||
| 380 | + return adapters; | ||
| 381 | +} | ||
| 382 | + | ||
| 383 | +static void collect_ifaces_windows(void) | ||
| 384 | +{ | ||
| 385 | + PIP_ADAPTER_ADDRESSES adapters; | ||
| 386 | + PIP_ADAPTER_ADDRESSES a; | ||
| 387 | + PIP_ADAPTER_UNICAST_ADDRESS u; | ||
| 388 | + | ||
| 389 | + adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX | | ||
| 390 | + GAA_FLAG_SKIP_ANYCAST | | ||
| 391 | + GAA_FLAG_SKIP_MULTICAST | | ||
| 392 | + GAA_FLAG_SKIP_DNS_SERVER); | ||
| 393 | + if (!adapters) return; | ||
| 394 | + | ||
| 395 | + for (a = adapters; a; a = a->Next) { | ||
| 396 | + char ascii[64]; | ||
| 397 | + const wchar_t *friendly = a->FriendlyName ? a->FriendlyName : NULL; | ||
| 398 | + int up = (a->OperStatus == MIF_OPER_UP); | ||
| 399 | + | ||
| 400 | + if (friendly) wide_to_ascii(friendly, ascii, sizeof ascii); | ||
| 401 | + else if (a->AdapterName) str_copy(ascii, sizeof ascii, a->AdapterName); | ||
| 402 | + else str_copy(ascii, sizeof ascii, "adapter"); | ||
| 403 | + | ||
| 404 | + for (u = a->FirstUnicastAddress; u; u = u->Next) { | ||
| 405 | + struct sockaddr_storage nm; | ||
| 406 | + struct sockaddr *nmp = NULL; | ||
| 407 | + | ||
| 408 | + /* OnLinkPrefixLength is a CIDR length, not a dotted mask. Expand it | ||
| 409 | + * into a dotted netmask so the table has something familiar to show. */ | ||
| 410 | + memset(&nm, 0, sizeof nm); | ||
| 411 | + if (u->Address.sa_family == AF_INET && u->OnLinkPrefixLength < 32) { | ||
| 412 | + struct sockaddr_in *in4 = (struct sockaddr_in *)&nm; | ||
| 413 | + in4->sin_family = AF_INET; | ||
| 414 | + in4->sin_addr.s_addr = | ||
| 415 | + htonl(0xFFFFFFFFUL << (32 - u->OnLinkPrefixLength)); | ||
| 416 | + nmp = (struct sockaddr *)in4; | ||
| 417 | + } | ||
| 418 | + iface_add(ascii, (const struct sockaddr *)&u->Address, nmp, NULL, | ||
| 419 | + up, up); | ||
| 420 | + } | ||
| 421 | + } | ||
| 422 | + free(adapters); | ||
| 423 | +} | ||
| 424 | +#else | ||
| 425 | +static void collect_ifaces_posix(void) | ||
| 426 | +{ | ||
| 427 | + struct ifaddrs *list = NULL; | ||
| 428 | + struct ifaddrs *i; | ||
| 429 | + | ||
| 430 | + if (getifaddrs(&list) != 0 || !list) return; | ||
| 431 | + for (i = list; i; i = i->ifa_next) { | ||
| 432 | + int up, running; | ||
| 433 | + | ||
| 434 | + if (!i->ifa_addr) continue; | ||
| 435 | + up = (i->ifa_flags & IFF_UP) != 0; | ||
| 436 | + running = (i->ifa_flags & IFF_RUNNING) != 0; | ||
| 437 | + iface_add(i->ifa_name, i->ifa_addr, i->ifa_netmask, i->ifa_broadaddr, | ||
| 438 | + up, running); | ||
| 439 | + } | ||
| 440 | + freeifaddrs(list); | ||
| 441 | +} | ||
| 442 | +#endif | ||
| 443 | + | ||
| 444 | + | ||
| 445 | +/* ------------------------------------------------------------------ */ | ||
| 446 | +/* Host validation */ | ||
| 447 | +/* ------------------------------------------------------------------ */ | ||
| 448 | + | ||
| 449 | +/* A host is accepted only as a DNS hostname label sequence or a literal IPv4 / | ||
| 450 | + * IPv6 address. That keeps typed input from smuggling a URL, a path, or a | ||
| 451 | + * shell metacharacter into anything we do with it. */ | ||
| 452 | +static int valid_hostname(const char *s) | ||
| 453 | +{ | ||
| 454 | + size_t i, n = strlen(s); | ||
| 455 | + | ||
| 456 | + if (n == 0 || n > 253) return 0; | ||
| 457 | + if (s[0] == '.' || s[n - 1] == '.') return 0; | ||
| 458 | + for (i = 0; i < n; i++) { | ||
| 459 | + unsigned char c = (unsigned char)s[i]; | ||
| 460 | + if (c == '.') { | ||
| 461 | + if (i == 0 || s[i - 1] == '.') return 0; | ||
| 462 | + continue; | ||
| 463 | + } | ||
| 464 | + if (!isalnum(c) && c != '-' && c != '_') return 0; | ||
| 465 | + } | ||
| 466 | + return 1; | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +static int looks_ipv4(const char *s) | ||
| 470 | +{ | ||
| 471 | + struct sockaddr_in in; | ||
| 472 | + return inet_pton(AF_INET, s, &in.sin_addr) == 1; | ||
| 473 | +} | ||
| 474 | + | ||
| 475 | +static int looks_ipv6(const char *s) | ||
| 476 | +{ | ||
| 477 | + struct sockaddr_in6 in6; | ||
| 478 | + return inet_pton(AF_INET6, s, &in6.sin6_addr) == 1; | ||
| 479 | +} | ||
| 480 | + | ||
| 481 | +static int valid_host(const char *s) | ||
| 482 | +{ | ||
| 483 | + if (!s || !*s) return 0; | ||
| 484 | + if (looks_ipv4(s) || looks_ipv6(s)) return 1; | ||
| 485 | + return valid_hostname(s); | ||
| 486 | +} | ||
| 487 | + | ||
| 488 | +/* ------------------------------------------------------------------ */ | ||
| 489 | +/* Test hooks */ | ||
| 490 | +/* ------------------------------------------------------------------ */ | ||
| 491 | + | ||
| 492 | +/* The offline suite needs deterministic, network-free answers, so three | ||
| 493 | + * environment hooks exist. They are only consulted when the variable is set, | ||
| 494 | + * which is never the case on a real node, and they let the suite exercise the | ||
| 495 | + * timeout and the multi-address paths without a live resolver. | ||
| 496 | + * | ||
| 497 | + * NETCHECK_MOCK_IFACES "lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,eth0|..." | ||
| 498 | + * name|address|netmask|broadcast|family|up | ||
| 499 | + * NETCHECK_MOCK_DNS "host=addr,addr;host2=addr" (family inferred) | ||
| 500 | + * NETCHECK_MOCK_TIMEOUT 1 -> every resolution reports a deadline miss | ||
| 501 | + */ | ||
| 502 | +static int mock_timeout_enabled(void) | ||
| 503 | +{ | ||
| 504 | + const char *v = getenv("NETCHECK_MOCK_TIMEOUT"); | ||
| 505 | + return v && v[0] == '1'; | ||
| 506 | +} | ||
| 507 | + | ||
| 508 | +/* Fill *res with a synthetic addrinfo chain for host. Returns 0 on success. */ | ||
| 509 | +static int mock_resolve(const char *host, const char *port, struct addrinfo **res) | ||
| 510 | +{ | ||
| 511 | + const char *map = getenv("NETCHECK_MOCK_DNS"); | ||
| 512 | + char entry[512]; | ||
| 513 | + char addrs[512]; | ||
| 514 | + size_t hl, el, i; | ||
| 515 | + struct addrinfo *head = NULL, *tail = NULL; | ||
| 516 | + int count = 0; | ||
| 517 | + | ||
| 518 | + int mock_port = 0; | ||
| 519 | + | ||
| 520 | + if (!map || !host) return -1; | ||
| 521 | + if (port) { | ||
| 522 | + long v = strtol(port, NULL, 10); | ||
| 523 | + if (v >= 1 && v <= 65535) mock_port = (int)v; | ||
| 524 | + } | ||
| 525 | + hl = strlen(host); | ||
| 526 | + | ||
| 527 | + i = 0; | ||
| 528 | + for (;;) { | ||
| 529 | + size_t j = i; | ||
| 530 | + char *eq; | ||
| 531 | + size_t k, al; | ||
| 532 | + struct addrinfo *ai; | ||
| 533 | + | ||
| 534 | + while (map[j] && map[j] != ';') j++; | ||
| 535 | + el = j - i; | ||
| 536 | + if (el > 0 && el < sizeof entry) { | ||
| 537 | + memcpy(entry, map + i, el); | ||
| 538 | + entry[el] = 0; | ||
| 539 | + eq = strchr(entry, '='); | ||
| 540 | + if (eq && (size_t)(eq - entry) == hl && strncmp(entry, host, hl) == 0) { | ||
| 541 | + str_copy(addrs, sizeof addrs, eq + 1); | ||
| 542 | + al = strlen(addrs); | ||
| 543 | + k = 0; | ||
| 544 | + while (k < al) { | ||
| 545 | + char tok[128]; | ||
| 546 | + size_t tl = 0; | ||
| 547 | + struct sockaddr_in *in4; | ||
| 548 | + struct sockaddr_in6 *in6; | ||
| 549 | + | ||
| 550 | + while (k < al && addrs[k] != ',') { | ||
| 551 | + if (tl < sizeof tok - 1) tok[tl++] = addrs[k]; | ||
| 552 | + k++; | ||
| 553 | + } | ||
| 554 | + tok[tl] = 0; | ||
| 555 | + if (k < al) k++; /* skip the comma */ | ||
| 556 | + while (tl > 0 && isspace((unsigned char)tok[tl - 1])) tok[--tl] = 0; | ||
| 557 | + if (tl == 0) continue; | ||
| 558 | + | ||
| 559 | + ai = (struct addrinfo *)calloc(1, sizeof *ai); | ||
| 560 | + if (!ai) return -2; | ||
| 561 | + if (looks_ipv4(tok)) { | ||
| 562 | + in4 = (struct sockaddr_in *)calloc(1, sizeof *in4); | ||
| 563 | + if (!in4) { free(ai); return -2; } | ||
| 564 | + in4->sin_family = AF_INET; | ||
| 565 | + in4->sin_port = htons((unsigned short)mock_port); | ||
| 566 | + inet_pton(AF_INET, tok, &in4->sin_addr); | ||
| 567 | + ai->ai_family = AF_INET; | ||
| 568 | + ai->ai_socktype = SOCK_STREAM; | ||
| 569 | + ai->ai_addr = (struct sockaddr *)in4; | ||
| 570 | + ai->ai_addrlen = sizeof *in4; | ||
| 571 | + } else if (looks_ipv6(tok)) { | ||
| 572 | + in6 = (struct sockaddr_in6 *)calloc(1, sizeof *in6); | ||
| 573 | + if (!in6) { free(ai); return -2; } | ||
| 574 | + in6->sin6_family = AF_INET6; | ||
| 575 | + in6->sin6_port = htons((unsigned short)mock_port); | ||
| 576 | + inet_pton(AF_INET6, tok, &in6->sin6_addr); | ||
| 577 | + ai->ai_family = AF_INET6; | ||
| 578 | + ai->ai_socktype = SOCK_STREAM; | ||
| 579 | + ai->ai_addr = (struct sockaddr *)in6; | ||
| 580 | + ai->ai_addrlen = sizeof *in6; | ||
| 581 | + } else { | ||
| 582 | + free(ai); | ||
| 583 | + continue; | ||
| 584 | + } | ||
| 585 | + if (tail) tail->ai_next = ai; else head = ai; | ||
| 586 | + tail = ai; | ||
| 587 | + if (++count >= MAX_RES) break; | ||
| 588 | + } | ||
| 589 | + *res = head; | ||
| 590 | + return 0; | ||
| 591 | + } | ||
| 592 | + } | ||
| 593 | + if (map[j] == ';') { i = j + 1; continue; } | ||
| 594 | + break; | ||
| 595 | + } | ||
| 596 | + return -1; | ||
| 597 | +} | ||
| 598 | + | ||
| 599 | +/* Synthetic interface table for the offline suite. | ||
| 600 | + * Format: name|address|netmask|broadcast|family|up (entries separated by ','). | ||
| 601 | + * A pipe is used between fields because an IPv6 address is full of colons. */ | ||
| 602 | +static int mock_ifaces(void) | ||
| 603 | +{ | ||
| 604 | + const char *spec = getenv("NETCHECK_MOCK_IFACES"); | ||
| 605 | + char tok[256]; | ||
| 606 | + char *parts[6]; | ||
| 607 | + size_t i = 0, n; | ||
| 608 | + | ||
| 609 | + if (!spec) return 0; | ||
| 610 | + n = strlen(spec); | ||
| 611 | + i = 0; | ||
| 612 | + while (i < n) { | ||
| 613 | + size_t tl = 0, pi; | ||
| 614 | + iface_t *f; | ||
| 615 | + struct sockaddr_storage sa; | ||
| 616 | + struct sockaddr_storage nm; | ||
| 617 | + struct sockaddr *nmp = NULL; | ||
| 618 | + char *pp; | ||
| 619 | + int fam = 0; | ||
| 620 | + | ||
| 621 | + while (i < n && spec[i] != ',') { | ||
| 622 | + if (tl < sizeof tok - 1) tok[tl++] = spec[i]; | ||
| 623 | + i++; | ||
| 624 | + } | ||
| 625 | + tok[tl] = 0; | ||
| 626 | + if (i < n) i++; /* skip the comma */ | ||
| 627 | + if (tl == 0) continue; | ||
| 628 | + | ||
| 629 | + for (pi = 0; pi < 6; pi++) parts[pi] = (char *)""; | ||
| 630 | + parts[0] = tok; | ||
| 631 | + pi = 1; | ||
| 632 | + pp = tok; | ||
| 633 | + while (pp && pi < 6) { | ||
| 634 | + char *nx = strchr(pp, '|'); | ||
| 635 | + if (!nx) break; | ||
| 636 | + *nx = 0; | ||
| 637 | + parts[pi++] = nx + 1; | ||
| 638 | + pp = nx + 1; | ||
| 639 | + } | ||
| 640 | + for (; pi < 6; pi++) parts[pi] = (char *)""; | ||
| 641 | + | ||
| 642 | + memset(&sa, 0, sizeof sa); | ||
| 643 | + memset(&nm, 0, sizeof nm); | ||
| 644 | + if (looks_ipv4(parts[1])) { | ||
| 645 | + struct sockaddr_in *in4 = (struct sockaddr_in *)&sa; | ||
| 646 | + in4->sin_family = AF_INET; | ||
| 647 | + inet_pton(AF_INET, parts[1], &in4->sin_addr); | ||
| 648 | + fam = 4; | ||
| 649 | + if (parts[2][0] && looks_ipv4(parts[2])) { | ||
| 650 | + struct sockaddr_in *m4 = (struct sockaddr_in *)&nm; | ||
| 651 | + m4->sin_family = AF_INET; | ||
| 652 | + inet_pton(AF_INET, parts[2], &m4->sin_addr); | ||
| 653 | + nmp = (struct sockaddr *)m4; | ||
| 654 | + } | ||
| 655 | + } else if (looks_ipv6(parts[1])) { | ||
| 656 | + struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&sa; | ||
| 657 | + in6->sin6_family = AF_INET6; | ||
| 658 | + inet_pton(AF_INET6, parts[1], &in6->sin6_addr); | ||
| 659 | + fam = 6; | ||
| 660 | + } else { | ||
| 661 | + continue; | ||
| 662 | + } | ||
| 663 | + | ||
| 664 | + if (g_iface_count >= MAX_IFACES) break; | ||
| 665 | + f = &g_ifaces[g_iface_count++]; | ||
| 666 | + memset(f, 0, sizeof *f); | ||
| 667 | + str_copy(f->name, sizeof f->name, parts[0]); | ||
| 668 | + str_copy(f->addr, sizeof f->addr, parts[1]); | ||
| 669 | + f->family = fam; | ||
| 670 | + f->loopback = is_loopback_text(f->addr); | ||
| 671 | + f->up = parts[5][0] == '1'; | ||
| 672 | + f->running = f->up; | ||
| 673 | + if (nmp) netmask_text(nmp, f->mask, sizeof f->mask); | ||
| 674 | + if (parts[3][0]) str_copy(f->broad, sizeof f->broad, parts[3]); | ||
| 675 | + } | ||
| 676 | + return 1; | ||
| 677 | +} | ||
| 678 | + | ||
| 679 | + | ||
| 680 | +static void collect_ifaces(void) | ||
| 681 | +{ | ||
| 682 | + g_iface_count = 0; | ||
| 683 | + if (mock_ifaces()) return; | ||
| 684 | +#if defined(_WIN32) | ||
| 685 | + collect_ifaces_windows(); | ||
| 686 | +#else | ||
| 687 | + collect_ifaces_posix(); | ||
| 688 | +#endif | ||
| 689 | +} | ||
| 690 | + | ||
| 691 | +/* ------------------------------------------------------------------ */ | ||
| 692 | +/* DNS server discovery */ | ||
| 693 | +/* ------------------------------------------------------------------ */ | ||
| 694 | + | ||
| 695 | +#define MAX_NS 16 | ||
| 696 | +static char g_ns[MAX_NS][64]; | ||
| 697 | +static int g_ns_count; | ||
| 698 | + | ||
| 699 | +static void ns_add(const char *s) | ||
| 700 | +{ | ||
| 701 | + char buf[64]; | ||
| 702 | + int i; | ||
| 703 | + | ||
| 704 | + if (!s) return; | ||
| 705 | + str_copy(buf, sizeof buf, s); | ||
| 706 | + str_trim(buf); | ||
| 707 | + if (!buf[0]) return; | ||
| 708 | + for (i = 0; i < g_ns_count; i++) | ||
| 709 | + if (strcmp(g_ns[i], buf) == 0) return; | ||
| 710 | + if (g_ns_count >= MAX_NS) return; | ||
| 711 | + str_copy(g_ns[g_ns_count++], sizeof g_ns[0], buf); | ||
| 712 | +} | ||
| 713 | + | ||
| 714 | +static void discover_nameservers(void) | ||
| 715 | +{ | ||
| 716 | + g_ns_count = 0; | ||
| 717 | + | ||
| 718 | +#if defined(_WIN32) | ||
| 719 | + { | ||
| 720 | + /* The interface query above deliberately skipped the DNS server list, | ||
| 721 | + * so re-query with the flag left on rather than parsing a text tool. */ | ||
| 722 | + PIP_ADAPTER_ADDRESSES adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX); | ||
| 723 | + PIP_ADAPTER_ADDRESSES a; | ||
| 724 | + PIP_ADAPTER_DNS_SERVER_ADDRESS_XP d; | ||
| 725 | + | ||
| 726 | + if (adapters) { | ||
| 727 | + for (a = adapters; a; a = a->Next) | ||
| 728 | + for (d = a->FirstDnsServerAddress; d; d = d->Next) { | ||
| 729 | + char txt[64]; | ||
| 730 | + if (addr_text((const struct sockaddr *)&d->Address, | ||
| 731 | + txt, sizeof txt)) | ||
| 732 | + ns_add(txt); | ||
| 733 | + } | ||
| 734 | + free(adapters); | ||
| 735 | + } | ||
| 736 | + } | ||
| 737 | +#else | ||
| 738 | + { | ||
| 739 | + FILE *f = fopen("/etc/resolv.conf", "r"); | ||
| 740 | + char line[MAX_LINE]; | ||
| 741 | + if (f) { | ||
| 742 | + while (fgets(line, sizeof line, f)) { | ||
| 743 | + char *p = line; | ||
| 744 | + if (*p == '#') continue; | ||
| 745 | + if (strncmp(p, "nameserver", 10) == 0) { | ||
| 746 | + p += 10; | ||
| 747 | + while (*p == ' ' || *p == '\t') p++; | ||
| 748 | + ns_add(p); | ||
| 749 | + } | ||
| 750 | + } | ||
| 751 | + fclose(f); | ||
| 752 | + } | ||
| 753 | + } | ||
| 754 | +#endif | ||
| 755 | + | ||
| 756 | +#if defined(__APPLE__) | ||
| 757 | + /* macOS keeps /etc/resolv.conf as a symlink to a rotating stub; scutil is | ||
| 758 | + * the authoritative source. Fixed argv - no user input reaches the shell. */ | ||
| 759 | + { | ||
| 760 | + FILE *f = sx_popen("/usr/bin/scutil --dns", "r"); | ||
| 761 | + char line[MAX_LINE]; | ||
| 762 | + if (f) { | ||
| 763 | + while (fgets(line, sizeof line, f)) { | ||
| 764 | + const char *p = strstr(line, "nameserver["); | ||
| 765 | + char srv[64]; | ||
| 766 | + size_t i = 0; | ||
| 767 | + if (!p) continue; | ||
| 768 | + p += 11; | ||
| 769 | + while (*p && *p != ']' && i < sizeof srv - 1) srv[i++] = *p++; | ||
| 770 | + srv[i] = '\0'; | ||
| 771 | + str_trim(srv); | ||
| 772 | + if (srv[0]) ns_add(srv); | ||
| 773 | + } | ||
| 774 | + sx_pclose(f); | ||
| 775 | + } | ||
| 776 | + } | ||
| 777 | +#endif | ||
| 778 | +} | ||
| 779 | + | ||
| 780 | +/* ------------------------------------------------------------------ */ | ||
| 781 | +/* Deadline-guarded DNS */ | ||
| 782 | +/* ------------------------------------------------------------------ */ | ||
| 783 | + | ||
| 784 | +/* getaddrinfo is blocking and has no timeout argument, so the deadline lives | ||
| 785 | + * in a worker thread. On timeout the thread is left running: this process is a | ||
| 786 | + * CGI child that exits as soon as the request is answered, so the leak is | ||
| 787 | + * bounded by the request itself. */ | ||
| 788 | +typedef struct { | ||
| 789 | + const char *host; | ||
| 790 | + const char *port; | ||
| 791 | + struct addrinfo *res; | ||
| 792 | + int rc; | ||
| 793 | + int done; | ||
| 794 | +} resolve_job; | ||
| 795 | + | ||
| 796 | +#if defined(_WIN32) | ||
| 797 | +static DWORD WINAPI resolve_thread(LPVOID arg) | ||
| 798 | +{ | ||
| 799 | + resolve_job *j = (resolve_job *)arg; | ||
| 800 | + struct addrinfo hints; | ||
| 801 | + | ||
| 802 | + memset(&hints, 0, sizeof hints); | ||
| 803 | + hints.ai_family = AF_UNSPEC; | ||
| 804 | + hints.ai_socktype = SOCK_STREAM; | ||
| 805 | + j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); | ||
| 806 | + j->done = 1; | ||
| 807 | + return 0; | ||
| 808 | +} | ||
| 809 | + | ||
| 810 | +static int resolve_with_deadline(const char *host, const char *port, | ||
| 811 | + struct addrinfo **res, int timeout_ms) | ||
| 812 | +{ | ||
| 813 | + resolve_job job; | ||
| 814 | + HANDLE th; | ||
| 815 | + DWORD wait; | ||
| 816 | + | ||
| 817 | + if (mock_timeout_enabled()) return -1; | ||
| 818 | + if (mock_resolve(host, port, res) == 0) return 0; | ||
| 819 | + job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; | ||
| 820 | + th = CreateThread(NULL, 0, resolve_thread, &job, 0, NULL); | ||
| 821 | + if (!th) return -4; | ||
| 822 | + wait = WaitForSingleObject(th, (DWORD)timeout_ms); | ||
| 823 | + if (wait == WAIT_TIMEOUT) { CloseHandle(th); return -1; } | ||
| 824 | + CloseHandle(th); | ||
| 825 | + *res = job.res; | ||
| 826 | + return job.rc; | ||
| 827 | +} | ||
| 828 | +#else | ||
| 829 | +static void *resolve_thread(void *arg) | ||
| 830 | +{ | ||
| 831 | + resolve_job *j = (resolve_job *)arg; | ||
| 832 | + struct addrinfo hints; | ||
| 833 | + | ||
| 834 | + memset(&hints, 0, sizeof hints); | ||
| 835 | + hints.ai_family = AF_UNSPEC; | ||
| 836 | + hints.ai_socktype = SOCK_STREAM; | ||
| 837 | + j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); | ||
| 838 | + j->done = 1; | ||
| 839 | + return NULL; | ||
| 840 | +} | ||
| 841 | + | ||
| 842 | +static int resolve_with_deadline(const char *host, const char *port, | ||
| 843 | + struct addrinfo **res, int timeout_ms) | ||
| 844 | +{ | ||
| 845 | + resolve_job job; | ||
| 846 | + pthread_t th; | ||
| 847 | + long long deadline = now_ms() + timeout_ms; | ||
| 848 | + | ||
| 849 | + if (mock_timeout_enabled()) return -1; | ||
| 850 | + if (mock_resolve(host, port, res) == 0) return 0; | ||
| 851 | + job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; | ||
| 852 | + if (pthread_create(&th, NULL, resolve_thread, &job) != 0) return -4; | ||
| 853 | + while (!job.done) { | ||
| 854 | + if (now_ms() >= deadline) return -1; /* thread keeps running; process exits soon */ | ||
| 855 | + usleep(20000); | ||
| 856 | + } | ||
| 857 | + pthread_join(th, NULL); | ||
| 858 | + *res = job.res; | ||
| 859 | + return job.rc; | ||
| 860 | +} | ||
| 861 | +#endif | ||
| 862 | + | ||
| 863 | +/* ------------------------------------------------------------------ */ | ||
| 864 | +/* TCP connect with a deadline */ | ||
| 865 | +/* ------------------------------------------------------------------ */ | ||
| 866 | + | ||
| 867 | +/* Returns >=0 connect latency in ms, -1 timeout, -2 connect failed/refused, | ||
| 868 | + * -3 resolution failed, -4 socket/thread failure. Writes the resolved address | ||
| 869 | + * into addr_out when available. */ | ||
| 870 | +static int tcp_connect_ms(const struct addrinfo *rp, int timeout_ms, | ||
| 871 | + char *addr_out, size_t addr_sz) | ||
| 872 | +{ | ||
| 873 | + SX_SOCK_T s; | ||
| 874 | + long long start; | ||
| 875 | + int rc; | ||
| 876 | + | ||
| 877 | + if (addr_out && addr_sz) addr_out[0] = '\0'; | ||
| 878 | + | ||
| 879 | + s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | ||
| 880 | + if (s == SX_SOCK_INVALID) return -4; | ||
| 881 | + | ||
| 882 | + /* Non-blocking so connect() returns immediately and select() enforces the | ||
| 883 | + * deadline. A blocking connect on some stacks ignores the deadline. */ | ||
| 884 | +#if defined(_WIN32) | ||
| 885 | + { | ||
| 886 | + u_long nb = 1; | ||
| 887 | + ioctlsocket(s, FIONBIO, &nb); | ||
| 888 | + } | ||
| 889 | +#else | ||
| 890 | + { | ||
| 891 | + int fl = fcntl(s, F_GETFL, 0); | ||
| 892 | + if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); | ||
| 893 | + } | ||
| 894 | +#endif | ||
| 895 | + | ||
| 896 | + start = now_ms(); | ||
| 897 | + rc = connect(s, rp->ai_addr, rp->ai_addrlen); | ||
| 898 | + if (rc != 0) { | ||
| 899 | +#if defined(_WIN32) | ||
| 900 | + int inprogress = (WSAGetLastError() == WSAEINPROGRESS || | ||
| 901 | + WSAGetLastError() == WSAEWOULDBLOCK || | ||
| 902 | + WSAGetLastError() == WSAEALREADY); | ||
| 903 | +#else | ||
| 904 | + int inprogress = (errno == EINPROGRESS || errno == EALREADY || | ||
| 905 | + errno == EWOULDBLOCK); | ||
| 906 | +#endif | ||
| 907 | + if (!inprogress) { sx_close_socket(s); return -2; } | ||
| 908 | + | ||
| 909 | + { | ||
| 910 | + fd_set wfds; | ||
| 911 | + struct timeval tv; | ||
| 912 | + int sr; | ||
| 913 | + | ||
| 914 | + FD_ZERO(&wfds); | ||
| 915 | + FD_SET(s, &wfds); | ||
| 916 | + tv.tv_sec = timeout_ms / 1000; | ||
| 917 | + tv.tv_usec = (timeout_ms % 1000) * 1000; | ||
| 918 | + sr = select((int)s + 1, NULL, &wfds, NULL, &tv); | ||
| 919 | + if (sr <= 0) { sx_close_socket(s); return -1; } | ||
| 920 | + { | ||
| 921 | + int soerr = 0; | ||
| 922 | +#if defined(_WIN32) | ||
| 923 | + int sl = sizeof soerr; | ||
| 924 | +#else | ||
| 925 | + socklen_t sl = sizeof soerr; | ||
| 926 | +#endif | ||
| 927 | + if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &sl) != 0 || soerr != 0) { | ||
| 928 | + sx_close_socket(s); | ||
| 929 | + return -2; | ||
| 930 | + } | ||
| 931 | + } | ||
| 932 | + } | ||
| 933 | + } | ||
| 934 | + | ||
| 935 | + rc = (int)(now_ms() - start); | ||
| 936 | + if (rc < 0) rc = 0; | ||
| 937 | + addr_text(rp->ai_addr, addr_out, addr_sz); | ||
| 938 | + sx_close_socket(s); | ||
| 939 | + return rc; | ||
| 940 | +} | ||
| 941 | + | ||
| 942 | +/* ------------------------------------------------------------------ */ | ||
| 943 | +/* URL parsing for the http action */ | ||
| 944 | +/* ------------------------------------------------------------------ */ | ||
| 945 | + | ||
| 946 | +typedef struct { | ||
| 947 | + char scheme[8]; | ||
| 948 | + char host[MAX_HOST]; /* bracketed when it is an IPv6 literal */ | ||
| 949 | + char host_plain[MAX_HOST];/* bare address, for getaddrinfo */ | ||
| 950 | + int port; | ||
| 951 | + char path[MAX_PATHZ]; | ||
| 952 | + int tls; | ||
| 953 | +} url_t; | ||
| 954 | + | ||
| 955 | +static int parse_url(const char *in, url_t *u) | ||
| 956 | +{ | ||
| 957 | + const char *p = in; | ||
| 958 | + const char *hs, *he, *ps; | ||
| 959 | + size_t n; | ||
| 960 | + | ||
| 961 | + memset(u, 0, sizeof *u); | ||
| 962 | + if (!in || !*in) return 0; | ||
| 963 | + | ||
| 964 | + if (strncmp(p, "http://", 7) == 0) { | ||
| 965 | + str_copy(u->scheme, sizeof u->scheme, "http"); | ||
| 966 | + u->tls = 0; | ||
| 967 | + p += 7; | ||
| 968 | + } else if (strncmp(p, "https://", 8) == 0) { | ||
| 969 | + str_copy(u->scheme, sizeof u->scheme, "https"); | ||
| 970 | + u->tls = 1; | ||
| 971 | + p += 8; | ||
| 972 | + } else { | ||
| 973 | + return 0; | ||
| 974 | + } | ||
| 975 | + | ||
| 976 | + hs = p; | ||
| 977 | + he = p; | ||
| 978 | + while (*he && *he != '/' && *he != '?' && *he != '#') he++; | ||
| 979 | + ps = he; /* the path starts at the first '/', not at the port */ | ||
| 980 | + | ||
| 981 | + /* strip userinfo */ | ||
| 982 | + { | ||
| 983 | + const char *at = NULL, *q; | ||
| 984 | + for (q = hs; q < he; q++) if (*q == '@') at = q; | ||
| 985 | + if (at) hs = at + 1; | ||
| 986 | + } | ||
| 987 | + | ||
| 988 | + /* split an optional :port. Scan right-to-left for the last colon outside | ||
| 989 | + * IPv6 brackets: an unbracketed IPv6 literal (127.0.0.1:80 style aside) | ||
| 990 | + * contains several colons, and the port is always the final one. */ | ||
| 991 | + { | ||
| 992 | + const char *col = NULL; | ||
| 993 | + intptr_t qi = (intptr_t)(he - hs) - 1; | ||
| 994 | + while (qi >= 0) { | ||
| 995 | + char c = hs[qi]; | ||
| 996 | + if (c == ']') { qi--; continue; } | ||
| 997 | + if (c == '[') break; /* bracketed IPv6, no plain port colon */ | ||
| 998 | + if (c == ':') { col = hs + qi; break; } | ||
| 999 | + if (c == '/' || c == '?' || c == '#') break; | ||
| 1000 | + qi--; | ||
| 1001 | + } | ||
| 1002 | + if (col) { | ||
| 1003 | + long v; | ||
| 1004 | + char pbuf[16]; | ||
| 1005 | + size_t pn = (size_t)(he - col - 1); | ||
| 1006 | + size_t k; | ||
| 1007 | + if (pn == 0 || pn >= sizeof pbuf) return 0; | ||
| 1008 | + memcpy(pbuf, col + 1, pn); | ||
| 1009 | + pbuf[pn] = '\0'; | ||
| 1010 | + for (k = 0; k < pn; k++) if (!isdigit((unsigned char)pbuf[k])) return 0; | ||
| 1011 | + v = strtol(pbuf, NULL, 10); | ||
| 1012 | + if (v < 1 || v > 65535) return 0; | ||
| 1013 | + u->port = (int)v; | ||
| 1014 | + he = col; | ||
| 1015 | + } else { | ||
| 1016 | + u->port = u->tls ? 443 : 80; | ||
| 1017 | + } | ||
| 1018 | + } | ||
| 1019 | + | ||
| 1020 | + n = (size_t)(he - hs); | ||
| 1021 | + if (n == 0 || n >= sizeof u->host) return 0; | ||
| 1022 | + memcpy(u->host, hs, n); | ||
| 1023 | + u->host[n] = '\0'; | ||
| 1024 | + | ||
| 1025 | + /* bare address for the resolver */ | ||
| 1026 | + if (u->host[0] == '[' && u->host[n - 1] == ']') { | ||
| 1027 | + if (n < 3 || n - 2 >= sizeof u->host_plain) return 0; | ||
| 1028 | + memcpy(u->host_plain, u->host + 1, n - 2); | ||
| 1029 | + u->host_plain[n - 2] = '\0'; | ||
| 1030 | + if (!looks_ipv6(u->host_plain)) return 0; | ||
| 1031 | + } else { | ||
| 1032 | + str_copy(u->host_plain, sizeof u->host_plain, u->host); | ||
| 1033 | + if (!valid_host(u->host_plain)) return 0; | ||
| 1034 | + } | ||
| 1035 | + | ||
| 1036 | + /* path */ | ||
| 1037 | + { | ||
| 1038 | + const char *e = ps; | ||
| 1039 | + while (*e && *e != '?' && *e != '#') e++; | ||
| 1040 | + n = (size_t)(e - ps); | ||
| 1041 | + if (n == 0) { str_copy(u->path, sizeof u->path, "/"); } | ||
| 1042 | + else { | ||
| 1043 | + if (n >= sizeof u->path) n = sizeof u->path - 1; | ||
| 1044 | + memcpy(u->path, ps, n); | ||
| 1045 | + u->path[n] = '\0'; | ||
| 1046 | + if (u->path[0] != '/') return 0; | ||
| 1047 | + } | ||
| 1048 | + } | ||
| 1049 | + return 1; | ||
| 1050 | +} | ||
| 1051 | + | ||
| 1052 | +/* ------------------------------------------------------------------ */ | ||
| 1053 | +/* JSON helpers */ | ||
| 1054 | +/* ------------------------------------------------------------------ */ | ||
| 1055 | + | ||
| 1056 | +static void emit_json_head(void) | ||
| 1057 | +{ | ||
| 1058 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1059 | + "Cache-Control: no-store\r\n" | ||
| 1060 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1061 | +} | ||
| 1062 | + | ||
| 1063 | +static void err_json(int status, const char *msg) | ||
| 1064 | +{ | ||
| 1065 | + printf("Status: %d %s\r\n" | ||
| 1066 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 1067 | + "Cache-Control: no-store\r\n" | ||
| 1068 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 1069 | + "{\"ok\":false,\"error\":", | ||
| 1070 | + status, status == 400 ? "Bad Request" : "Internal Error"); | ||
| 1071 | + json_str(msg); | ||
| 1072 | + puts("}"); | ||
| 1073 | +} | ||
| 1074 | + | ||
| 1075 | +/* ------------------------------------------------------------------ */ | ||
| 1076 | +/* action=ifaces */ | ||
| 1077 | +/* ------------------------------------------------------------------ */ | ||
| 1078 | + | ||
| 1079 | +static void action_ifaces(void) | ||
| 1080 | +{ | ||
| 1081 | + int i; | ||
| 1082 | + char stamp[32]; | ||
| 1083 | + | ||
| 1084 | + collect_ifaces(); | ||
| 1085 | + discover_nameservers(); | ||
| 1086 | + | ||
| 1087 | + emit_json_head(); | ||
| 1088 | + utc_stamp(time(NULL), stamp, sizeof stamp); | ||
| 1089 | + printf("{\"ok\":true,\"action\":\"ifaces\",\"generated_at\":"); | ||
| 1090 | + json_str(stamp); | ||
| 1091 | + printf(",\"count\":%d,\"interfaces\":[", g_iface_count); | ||
| 1092 | + for (i = 0; i < g_iface_count; i++) { | ||
| 1093 | + const iface_t *f = &g_ifaces[i]; | ||
| 1094 | + if (i) putchar(','); | ||
| 1095 | + printf("{\"name\":"); | ||
| 1096 | + json_str(f->name); | ||
| 1097 | + printf(",\"address\":"); | ||
| 1098 | + json_str(f->addr); | ||
| 1099 | + printf(",\"family\":%d,\"netmask\":", f->family); | ||
| 1100 | + if (f->mask[0]) json_str(f->mask); else fputs("null", stdout); | ||
| 1101 | + printf(",\"broadcast\":"); | ||
| 1102 | + if (f->broad[0]) json_str(f->broad); else fputs("null", stdout); | ||
| 1103 | + printf(",\"loopback\":%s,\"up\":%s,\"running\":%s}", | ||
| 1104 | + f->loopback ? "true" : "false", | ||
| 1105 | + f->up ? "true" : "false", | ||
| 1106 | + f->running ? "true" : "false"); | ||
| 1107 | + } | ||
| 1108 | + printf("],\"nameservers\":["); | ||
| 1109 | + for (i = 0; i < g_ns_count; i++) { | ||
| 1110 | + if (i) putchar(','); | ||
| 1111 | + json_str(g_ns[i]); | ||
| 1112 | + } | ||
| 1113 | + printf("],\"nameserver_count\":%d}", g_ns_count); | ||
| 1114 | +} | ||
| 1115 | + | ||
| 1116 | +/* ------------------------------------------------------------------ */ | ||
| 1117 | +/* action=dns */ | ||
| 1118 | +/* ------------------------------------------------------------------ */ | ||
| 1119 | + | ||
| 1120 | +static void action_dns(const char *host_in) | ||
| 1121 | +{ | ||
| 1122 | + struct addrinfo *res = NULL; | ||
| 1123 | + struct addrinfo *rp; | ||
| 1124 | + char stamp[32]; | ||
| 1125 | + char target[MAX_HOST]; | ||
| 1126 | + int n = 0; | ||
| 1127 | + long long t0, t1; | ||
| 1128 | + int rc; | ||
| 1129 | + | ||
| 1130 | + str_copy(target, sizeof target, host_in); | ||
| 1131 | + str_lower(target); | ||
| 1132 | + if (!target[0]) { err_json(400, "host required"); return; } | ||
| 1133 | + if (!valid_host(target)) { err_json(400, "invalid host"); return; } | ||
| 1134 | + | ||
| 1135 | + emit_json_head(); | ||
| 1136 | + utc_stamp(time(NULL), stamp, sizeof stamp); | ||
| 1137 | + | ||
| 1138 | + t0 = now_ms(); | ||
| 1139 | + rc = resolve_with_deadline(target, NULL, &res, DNS_MS); | ||
| 1140 | + t1 = now_ms(); | ||
| 1141 | + | ||
| 1142 | + printf("{\"ok\":true,\"action\":\"dns\",\"host\":"); | ||
| 1143 | + json_str(target); | ||
| 1144 | + printf(",\"generated_at\":"); | ||
| 1145 | + json_str(stamp); | ||
| 1146 | + printf(",\"timeout_ms\":%d", DNS_MS); | ||
| 1147 | + | ||
| 1148 | + if (rc == -1) { | ||
| 1149 | + printf(",\"resolved\":false,\"timeout\":true,\"code\":null," | ||
| 1150 | + "\"latency_ms\":%lld,\"results\":[],\"count\":0}", | ||
| 1151 | + (long long)(t1 - t0)); | ||
| 1152 | + return; | ||
| 1153 | + } | ||
| 1154 | + if (rc != 0 || !res) { | ||
| 1155 | + printf(",\"resolved\":false,\"timeout\":false,\"code\":%d," | ||
| 1156 | + "\"latency_ms\":%lld,\"results\":[],\"count\":0}", | ||
| 1157 | + rc, (long long)(t1 - t0)); | ||
| 1158 | + return; | ||
| 1159 | + } | ||
| 1160 | + | ||
| 1161 | + printf(",\"resolved\":true,\"timeout\":false,\"code\":0," | ||
| 1162 | + "\"latency_ms\":%lld,\"results\":[", (long long)(t1 - t0)); | ||
| 1163 | + for (rp = res; rp; rp = rp->ai_next) { | ||
| 1164 | + char txt[64]; | ||
| 1165 | + if (!addr_text(rp->ai_addr, txt, sizeof txt)) continue; | ||
| 1166 | + if (n) putchar(','); | ||
| 1167 | + n++; | ||
| 1168 | + printf("{\"address\":"); | ||
| 1169 | + json_str(txt); | ||
| 1170 | + printf(",\"family\":%s", rp->ai_family == AF_INET6 ? "\"inet6\"" : "\"inet\""); | ||
| 1171 | + printf(",\"canonical\":"); | ||
| 1172 | + if (rp->ai_canonname && *rp->ai_canonname) json_str(rp->ai_canonname); | ||
| 1173 | + else fputs("null", stdout); | ||
| 1174 | + putchar('}'); | ||
| 1175 | + if (n >= MAX_RES) break; | ||
| 1176 | + } | ||
| 1177 | + freeaddrinfo(res); | ||
| 1178 | + printf("],\"count\":%d}", n); | ||
| 1179 | +} | ||
| 1180 | + | ||
| 1181 | +/* ------------------------------------------------------------------ */ | ||
| 1182 | +/* action=tcp */ | ||
| 1183 | +/* ------------------------------------------------------------------ */ | ||
| 1184 | + | ||
| 1185 | +static void action_tcp(const char *host_in, const char *port_s) | ||
| 1186 | +{ | ||
| 1187 | + long long samples[MAX_SAMPLES]; | ||
| 1188 | + int nsamp = 0; | ||
| 1189 | + int i; | ||
| 1190 | + long long best = -1, worst = -1, sum = 0, cnt = 0; | ||
| 1191 | + int status = 0; /* 0 failed, 1 open, 2 timeout */ | ||
| 1192 | + char addr[64]; | ||
| 1193 | + char stamp[32]; | ||
| 1194 | + char target[MAX_HOST]; | ||
| 1195 | + char pbuf[16]; | ||
| 1196 | + struct addrinfo *res = NULL; | ||
| 1197 | + struct addrinfo *rp; | ||
| 1198 | + int rc; | ||
| 1199 | + int port; | ||
| 1200 | + | ||
| 1201 | + str_copy(target, sizeof target, host_in); | ||
| 1202 | + str_lower(target); | ||
| 1203 | + if (!valid_host(target)) { err_json(400, "invalid host"); return; } | ||
| 1204 | + | ||
| 1205 | + port = atoi(port_s); | ||
| 1206 | + if (port < 1 || port > 65535) { err_json(400, "invalid port"); return; } | ||
| 1207 | + snprintf(pbuf, sizeof pbuf, "%d", port); | ||
| 1208 | + | ||
| 1209 | + emit_json_head(); | ||
| 1210 | + utc_stamp(time(NULL), stamp, sizeof stamp); | ||
| 1211 | + | ||
| 1212 | + rc = resolve_with_deadline(target, pbuf, &res, DNS_MS); | ||
| 1213 | + addr[0] = '\0'; | ||
| 1214 | + | ||
| 1215 | + if (rc == -1) { status = 2; samples[nsamp++] = -1; } | ||
| 1216 | + else if (rc != 0 || !res) { status = 0; samples[nsamp++] = -2; } | ||
| 1217 | + else { | ||
| 1218 | + for (i = 0; i < MAX_SAMPLES; i++) { | ||
| 1219 | + long long r; | ||
| 1220 | + for (rp = res; rp; rp = rp->ai_next) { | ||
| 1221 | + r = tcp_connect_ms(rp, TCP_MS, addr, sizeof addr); | ||
| 1222 | + if (r >= 0 || r == -2) break; /* try the next family only on socket failure */ | ||
| 1223 | + } | ||
| 1224 | + if (r == -1) { samples[nsamp++] = -1; status = 2; break; } | ||
| 1225 | + samples[nsamp++] = r; | ||
| 1226 | + if (r >= 0) { status = 1; } | ||
| 1227 | + else if (status != 1) { status = 0; } | ||
| 1228 | + } | ||
| 1229 | + freeaddrinfo(res); | ||
| 1230 | + } | ||
| 1231 | + | ||
| 1232 | + for (i = 0; i < nsamp; i++) { | ||
| 1233 | + if (samples[i] >= 0) { | ||
| 1234 | + if (best < 0 || samples[i] < best) best = samples[i]; | ||
| 1235 | + if (worst < 0 || samples[i] > worst) worst = samples[i]; | ||
| 1236 | + sum += samples[i]; | ||
| 1237 | + cnt++; | ||
| 1238 | + } | ||
| 1239 | + } | ||
| 1240 | + | ||
| 1241 | + printf("{\"ok\":true,\"action\":\"tcp\",\"host\":"); | ||
| 1242 | + json_str(target); | ||
| 1243 | + printf(",\"port\":%d,\"generated_at\":", port); | ||
| 1244 | + json_str(stamp); | ||
| 1245 | + printf(",\"open\":%s,\"status\":", status == 1 ? "true" : "false"); | ||
| 1246 | + json_str(status == 1 ? "open" : (status == 2 ? "timeout" : "closed")); | ||
| 1247 | + fputs(",\"address\":", stdout); | ||
| 1248 | + if (addr[0]) json_str(addr); else fputs("null", stdout); | ||
| 1249 | + printf(",\"samples\":["); | ||
| 1250 | + for (i = 0; i < nsamp; i++) { | ||
| 1251 | + if (i) putchar(','); | ||
| 1252 | + if (samples[i] >= 0) printf("%lld", samples[i]); else fputs("null", stdout); | ||
| 1253 | + } | ||
| 1254 | + printf("],\"avg_ms\":"); | ||
| 1255 | + if (cnt) printf("%.2f", (double)sum / (double)cnt); else fputs("null", stdout); | ||
| 1256 | + printf(",\"min_ms\":"); | ||
| 1257 | + if (best >= 0) printf("%lld", best); else fputs("null", stdout); | ||
| 1258 | + printf(",\"max_ms\":"); | ||
| 1259 | + if (worst >= 0) printf("%lld", worst); else fputs("null", stdout); | ||
| 1260 | + printf(",\"timeout_ms\":%d}", TCP_MS); | ||
| 1261 | +} | ||
| 1262 | + | ||
| 1263 | +/* ------------------------------------------------------------------ */ | ||
| 1264 | +/* action=http */ | ||
| 1265 | +/* ------------------------------------------------------------------ */ | ||
| 1266 | + | ||
| 1267 | +/* Plain HTTP reachability. Sends one HEAD request, reads only the status line | ||
| 1268 | + * and the header block, never a body, and follows no redirects. There is no | ||
| 1269 | + * TLS library in this binary, so an https:// target is reported as a TCP | ||
| 1270 | + * connect to 443 with tls:"not_checked". */ | ||
| 1271 | +static void action_http(const char *url_in) | ||
| 1272 | +{ | ||
| 1273 | + url_t u; | ||
| 1274 | + SX_SOCK_T s = SX_SOCK_INVALID; | ||
| 1275 | + struct addrinfo *res = NULL; | ||
| 1276 | + struct addrinfo *rp; | ||
| 1277 | + char req[768]; | ||
| 1278 | + char buf[2048]; | ||
| 1279 | + size_t have = 0; | ||
| 1280 | + int status = 0; | ||
| 1281 | + int header_lines = 0; | ||
| 1282 | + int got_headers = 0; | ||
| 1283 | + long long t0, t1, t2; | ||
| 1284 | + char stamp[32]; | ||
| 1285 | + char pbuf[16]; | ||
| 1286 | + int rc; | ||
| 1287 | + | ||
| 1288 | + if (!parse_url(url_in, &u)) { err_json(400, "invalid url"); return; } | ||
| 1289 | + | ||
| 1290 | + snprintf(pbuf, sizeof pbuf, "%d", u.port); | ||
| 1291 | + rc = resolve_with_deadline(u.host_plain, pbuf, &res, DNS_MS); | ||
| 1292 | + | ||
| 1293 | + emit_json_head(); | ||
| 1294 | + utc_stamp(time(NULL), stamp, sizeof stamp); | ||
| 1295 | + | ||
| 1296 | + printf("{\"ok\":true,\"action\":\"http\",\"url\":"); | ||
| 1297 | + json_str(url_in); | ||
| 1298 | + printf(",\"host\":"); | ||
| 1299 | + json_str(u.host); | ||
| 1300 | + printf(",\"port\":%d,\"path\":", u.port); | ||
| 1301 | + json_str(u.path); | ||
| 1302 | + printf(",\"tls\":"); | ||
| 1303 | + if (u.tls) fputs("\"not_checked\"", stdout); else fputs("false", stdout); | ||
| 1304 | + printf(",\"generated_at\":"); | ||
| 1305 | + json_str(stamp); | ||
| 1306 | + | ||
| 1307 | + if (rc == -1) { | ||
| 1308 | + printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," | ||
| 1309 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | ||
| 1310 | + "\"note\":\"dns resolution timed out\"}"); | ||
| 1311 | + return; | ||
| 1312 | + } | ||
| 1313 | + if (rc != 0 || !res) { | ||
| 1314 | + printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," | ||
| 1315 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | ||
| 1316 | + "\"note\":\"host does not resolve\"}"); | ||
| 1317 | + return; | ||
| 1318 | + } | ||
| 1319 | + | ||
| 1320 | + t0 = now_ms(); | ||
| 1321 | + for (rp = res; rp; rp = rp->ai_next) { | ||
| 1322 | + s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | ||
| 1323 | + if (s == SX_SOCK_INVALID) continue; | ||
| 1324 | + rc = connect(s, rp->ai_addr, rp->ai_addrlen); | ||
| 1325 | + if (rc == 0) break; | ||
| 1326 | + sx_close_socket(s); | ||
| 1327 | + s = SX_SOCK_INVALID; | ||
| 1328 | + } | ||
| 1329 | + freeaddrinfo(res); | ||
| 1330 | + t1 = now_ms(); | ||
| 1331 | + | ||
| 1332 | + if (s == SX_SOCK_INVALID) { | ||
| 1333 | + printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," | ||
| 1334 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | ||
| 1335 | + "\"note\":\"tcp connect failed\""); | ||
| 1336 | + if (u.tls) | ||
| 1337 | + fputs(",\"tls_note\":\"no TLS library: only the TCP connect to 443 was attempted\"", | ||
| 1338 | + stdout); | ||
| 1339 | + puts("}"); | ||
| 1340 | + return; | ||
| 1341 | + } | ||
| 1342 | + | ||
| 1343 | + if (u.tls) { | ||
| 1344 | + /* No TLS: report the connect and stop. */ | ||
| 1345 | + sx_close_socket(s); | ||
| 1346 | + printf(",\"reachable\":true,\"connect_ms\":%lld,\"status\":null," | ||
| 1347 | + "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," | ||
| 1348 | + "\"note\":\"tcp connect succeeded; the TLS handshake was not attempted\"", | ||
| 1349 | + (long long)(t1 - t0)); | ||
| 1350 | + puts("}"); | ||
| 1351 | + return; | ||
| 1352 | + } | ||
| 1353 | + | ||
| 1354 | + /* Read timeout so a server that accepts but never answers cannot hang us. */ | ||
| 1355 | +#if defined(_WIN32) | ||
| 1356 | + { | ||
| 1357 | + DWORD tv = (DWORD)READ_MS; | ||
| 1358 | + setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv); | ||
| 1359 | + } | ||
| 1360 | +#else | ||
| 1361 | + { | ||
| 1362 | + struct timeval tv; | ||
| 1363 | + tv.tv_sec = READ_MS / 1000; | ||
| 1364 | + tv.tv_usec = (READ_MS % 1000) * 1000; | ||
| 1365 | + setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); | ||
| 1366 | + } | ||
| 1367 | +#endif | ||
| 1368 | + | ||
| 1369 | + snprintf(req, sizeof req, | ||
| 1370 | + "HEAD %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: scorpiox-bot-netcheck/1.0\r\n" | ||
| 1371 | + "Accept: */*\r\nConnection: close\r\n\r\n", | ||
| 1372 | + u.path, u.host); | ||
| 1373 | + | ||
| 1374 | + { | ||
| 1375 | + size_t wl = strlen(req), sent = 0; | ||
| 1376 | + while (sent < wl) { | ||
| 1377 | + int w; | ||
| 1378 | +#if defined(_WIN32) | ||
| 1379 | + w = (int)send(s, req + sent, (int)(wl - sent), 0); | ||
| 1380 | +#else | ||
| 1381 | + w = (int)send(s, req + sent, wl - sent, 0); | ||
| 1382 | +#endif | ||
| 1383 | + if (w <= 0) break; | ||
| 1384 | + sent += (size_t)w; | ||
| 1385 | + } | ||
| 1386 | + } | ||
| 1387 | + | ||
| 1388 | + t2 = now_ms(); | ||
| 1389 | + while (have < sizeof buf - 1) { | ||
| 1390 | + int r = (int)recv(s, buf + have, 1, 0); | ||
| 1391 | + if (r <= 0) break; | ||
| 1392 | + have += (size_t)r; | ||
| 1393 | + if (have >= 4 && memcmp(buf + have - 4, "\r\n\r\n", 4) == 0) { got_headers = 1; break; } | ||
| 1394 | + if (have >= 2 && memcmp(buf + have - 2, "\n\n", 2) == 0) { got_headers = 1; break; } | ||
| 1395 | + if (now_ms() - t2 > READ_MS) break; | ||
| 1396 | + } | ||
| 1397 | + t2 = now_ms(); | ||
| 1398 | + sx_close_socket(s); | ||
| 1399 | + buf[have] = '\0'; | ||
| 1400 | + | ||
| 1401 | + printf(",\"reachable\":true,\"connect_ms\":%lld", (long long)(t1 - t0)); | ||
| 1402 | + | ||
| 1403 | + if (have >= 5 && strncmp(buf, "HTTP/", 5) == 0) { | ||
| 1404 | + const char *sp = strchr(buf, ' '); | ||
| 1405 | + if (sp) { | ||
| 1406 | + const char *nl = strchr(sp, '\r'); | ||
| 1407 | + char txt[64]; | ||
| 1408 | + size_t n; | ||
| 1409 | + if (!nl) nl = strchr(sp, '\n'); | ||
| 1410 | + const char *rs; | ||
| 1411 | + status = atoi(sp + 1); | ||
| 1412 | + /* the reason phrase starts after the code and its single space */ | ||
| 1413 | + rs = sp + 1; | ||
| 1414 | + while (isdigit((unsigned char)*rs)) rs++; | ||
| 1415 | + while (*rs == ' ' || *rs == '\t') rs++; | ||
| 1416 | + n = nl ? (size_t)(nl - rs) : 0; | ||
| 1417 | + if (n >= sizeof txt) n = sizeof txt - 1; | ||
| 1418 | + memcpy(txt, rs, n); | ||
| 1419 | + txt[n] = '\0'; | ||
| 1420 | + str_trim(txt); | ||
| 1421 | + printf(",\"status\":%d,\"status_text\":", status); | ||
| 1422 | + json_str(txt); | ||
| 1423 | + } else { | ||
| 1424 | + fputs(",\"status\":null,\"status_text\":null", stdout); | ||
| 1425 | + } | ||
| 1426 | + } else { | ||
| 1427 | + fputs(",\"status\":null,\"status_text\":null", stdout); | ||
| 1428 | + } | ||
| 1429 | + | ||
| 1430 | + /* count header lines: everything after the status line up to the blank line */ | ||
| 1431 | + { | ||
| 1432 | + const char *p = strchr(buf, '\n'); | ||
| 1433 | + if (p) { | ||
| 1434 | + p++; | ||
| 1435 | + for (;;) { | ||
| 1436 | + const char *nl; | ||
| 1437 | + while (*p == '\r' || *p == '\n') { | ||
| 1438 | + /* a line that is only a terminator ends the header block */ | ||
| 1439 | + if (*p == '\n') { p++; break; } | ||
| 1440 | + p++; | ||
| 1441 | + } | ||
| 1442 | + if (!*p || *p == '\n') break; /* blank line = end of headers */ | ||
| 1443 | + nl = strchr(p, '\n'); | ||
| 1444 | + header_lines++; | ||
| 1445 | + if (!nl) break; | ||
| 1446 | + p = nl + 1; | ||
| 1447 | + } | ||
| 1448 | + } | ||
| 1449 | + } | ||
| 1450 | + | ||
| 1451 | + printf(",\"header_lines\":%d,\"body_bytes_read\":0,\"read_ms\":%lld," | ||
| 1452 | + "\"headers_complete\":%s", | ||
| 1453 | + header_lines, (long long)(t2 - t1), got_headers ? "true" : "false"); | ||
| 1454 | + if (status >= 300 && status < 400) | ||
| 1455 | + fputs(",\"redirect\":\"not_followed\"", stdout); | ||
| 1456 | + puts("}"); | ||
| 1457 | +} | ||
| 1458 | + | ||
| 1459 | +/* ------------------------------------------------------------------ */ | ||
| 1460 | +/* action=info */ | ||
| 1461 | +/* ------------------------------------------------------------------ */ | ||
| 1462 | + | ||
| 1463 | +static void action_info(void) | ||
| 1464 | +{ | ||
| 1465 | + char stamp[32]; | ||
| 1466 | + emit_json_head(); | ||
| 1467 | + utc_stamp(time(NULL), stamp, sizeof stamp); | ||
| 1468 | + printf("{\"ok\":true,\"plugin\":"); | ||
| 1469 | + json_str(PLUGIN_ID); | ||
| 1470 | + printf(",\"slug\":"); | ||
| 1471 | + json_str(PLUGIN_SLUG); | ||
| 1472 | + printf(",\"version\":"); | ||
| 1473 | + json_str(PLUGIN_VER); | ||
| 1474 | + printf(",\"generated_at\":"); | ||
| 1475 | + json_str(stamp); | ||
| 1476 | + printf(",\"actions\":[\"ifaces\",\"dns\",\"tcp\",\"http\",\"info\"]"); | ||
| 1477 | + printf(",\"tls_library\":false,\"max_samples\":%d", MAX_SAMPLES); | ||
| 1478 | + printf(",\"dns_timeout_ms\":%d,\"tcp_timeout_ms\":%d,\"read_timeout_ms\":%d", | ||
| 1479 | + DNS_MS, TCP_MS, READ_MS); | ||
| 1480 | + puts("}"); | ||
| 1481 | +} | ||
| 1482 | + | ||
| 1483 | +static int is_post_request(void) | ||
| 1484 | +{ | ||
| 1485 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 1486 | + return m && (strcmp(m, "POST") == 0 || strcmp(m, "PUT") == 0); | ||
| 1487 | +} | ||
| 1488 | + | ||
| 1489 | +static int mode_meta(void) | ||
| 1490 | +{ | ||
| 1491 | + puts("{\"name\":\"netcheck\",\"desc\":\"Net checks\"}"); | ||
| 1492 | + return 0; | ||
| 1493 | +} | ||
| 1494 | + | ||
| 1495 | +static int mode_json(const char *qs) | ||
| 1496 | +{ | ||
| 1497 | + char action[64]; | ||
| 1498 | + char host[MAX_HOST]; | ||
| 1499 | + char port_s[16]; | ||
| 1500 | + char url_s[MAX_LINE]; | ||
| 1501 | + | ||
| 1502 | + get_query_val(qs, "action", action, sizeof action); | ||
| 1503 | + str_lower(action); | ||
| 1504 | + | ||
| 1505 | + if (action[0] == '\0') { action_info(); return 0; } | ||
| 1506 | + | ||
| 1507 | + if (strcmp(action, "ifaces") == 0) { action_ifaces(); return 0; } | ||
| 1508 | + | ||
| 1509 | + if (strcmp(action, "dns") == 0) { | ||
| 1510 | + if (!get_query_val(qs, "host", host, sizeof host)) { | ||
| 1511 | + err_json(400, "host required"); return 0; | ||
| 1512 | + } | ||
| 1513 | + action_dns(host); | ||
| 1514 | + return 0; | ||
| 1515 | + } | ||
| 1516 | + | ||
| 1517 | + if (strcmp(action, "tcp") == 0) { | ||
| 1518 | + if (!get_query_val(qs, "host", host, sizeof host)) { | ||
| 1519 | + err_json(400, "host required"); return 0; | ||
| 1520 | + } | ||
| 1521 | + if (!get_query_val(qs, "port", port_s, sizeof port_s)) { | ||
| 1522 | + err_json(400, "port required"); return 0; | ||
| 1523 | + } | ||
| 1524 | + action_tcp(host, port_s); | ||
| 1525 | + return 0; | ||
| 1526 | + } | ||
| 1527 | + | ||
| 1528 | + if (strcmp(action, "http") == 0) { | ||
| 1529 | + if (!get_query_val(qs, "url", url_s, sizeof url_s)) { | ||
| 1530 | + err_json(400, "url required"); return 0; | ||
| 1531 | + } | ||
| 1532 | + action_http(url_s); | ||
| 1533 | + return 0; | ||
| 1534 | + } | ||
| 1535 | + | ||
| 1536 | + if (strcmp(action, "info") == 0) { action_info(); return 0; } | ||
| 1537 | + | ||
| 1538 | + err_json(400, "unknown action"); | ||
| 1539 | + return 0; | ||
| 1540 | +} | ||
| 1541 | + | ||
| 1542 | +/* ------------------------------------------------------------------ */ | ||
| 1543 | +/* HTML mode */ | ||
| 1544 | +/* ------------------------------------------------------------------ */ | ||
| 1545 | + | ||
| 1546 | +/* Split UI_HTML on the two control-byte placeholders and expand them into the | ||
| 1547 | + * theme macros, so the page and the bot palette can never drift. */ | ||
| 1548 | +static void emit_ui(void) | ||
| 1549 | +{ | ||
| 1550 | + const char *p = UI_HTML; | ||
| 1551 | + | ||
| 1552 | + while (*p) { | ||
| 1553 | + if (*p == '\001') { | ||
| 1554 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | ||
| 1555 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" | ||
| 1556 | + "</style>", stdout); | ||
| 1557 | + p++; | ||
| 1558 | + } else if (*p == '\002') { | ||
| 1559 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1560 | + p++; | ||
| 1561 | + } else { | ||
| 1562 | + putchar(*p++); | ||
| 1563 | + } | ||
| 1564 | + } | ||
| 1565 | +} | ||
| 1566 | + | ||
| 1567 | +static int mode_html(int embed) | ||
| 1568 | +{ | ||
| 1569 | + (void)embed; | ||
| 1570 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1571 | + "Cache-Control: no-store\r\n" | ||
| 1572 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1573 | + "X-Frame-Options: SAMEORIGIN\r\n" | ||
| 1574 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 1575 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | ||
| 1576 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | ||
| 1577 | + emit_ui(); | ||
| 1578 | + return 0; | ||
| 1579 | +} | ||
| 1580 | + | ||
| 1581 | +int main(int argc, char **argv) | ||
| 1582 | +{ | ||
| 1583 | + const char *qs; | ||
| 1584 | + int embed; | ||
| 1585 | + | ||
| 1586 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || | ||
| 1587 | + (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) | ||
| 1588 | + return mode_meta(); | ||
| 1589 | + | ||
| 1590 | +#if defined(_WIN32) | ||
| 1591 | + { | ||
| 1592 | + WSADATA wsa; | ||
| 1593 | + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) | ||
| 1594 | + return mode_meta(); | ||
| 1595 | + } | ||
| 1596 | +#endif | ||
| 1597 | + | ||
| 1598 | + require_node_auth(); | ||
| 1599 | + | ||
| 1600 | + qs = getenv("QUERY_STRING"); | ||
| 1601 | + if (!qs) qs = ""; | ||
| 1602 | + | ||
| 1603 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) | ||
| 1604 | + return mode_json(qs); | ||
| 1605 | + | ||
| 1606 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | ||
| 1607 | + return mode_html(embed); | ||
| 1608 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0349de1 | index 0000000..0349de1 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,446 @@ | @@ -0,0 +1,446 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html lang="en"><head><meta charset="utf-8"> | ||
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 4 | +<title>netcheck</title> | ||
| 5 | +<!--TOKENS--> | ||
| 6 | +<style> | ||
| 7 | +*{box-sizing:border-box} | ||
| 8 | +html,body{margin:0;height:100%} | ||
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font); | ||
| 10 | + font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased} | ||
| 11 | +.wrap{max-width:1080px;margin:0 auto;padding:16px 16px 32px} | ||
| 12 | +.top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap} | ||
| 13 | +.title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em} | ||
| 14 | +.pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px; | ||
| 15 | + background:var(--surface-2);color:var(--text-2);border:1px solid var(--line); | ||
| 16 | + white-space:nowrap} | ||
| 17 | +.sp{flex:1} | ||
| 18 | +.icon{display:inline-flex;align-items:center;justify-content:center;gap:6px; | ||
| 19 | + background:var(--surface-2);border:1px solid var(--line);color:var(--text); | ||
| 20 | + border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit; | ||
| 21 | + font-size:12px;font-weight:600} | ||
| 22 | +.icon:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 23 | +.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor; | ||
| 24 | + stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} | ||
| 25 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:8px 16px; | ||
| 26 | + font-weight:600;font-size:13px;cursor:pointer;font-family:inherit} | ||
| 27 | +.btn:disabled{opacity:.55;cursor:default} | ||
| 28 | +.btn.gh{background:transparent;color:var(--text);border:1px solid var(--line)} | ||
| 29 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | ||
| 30 | + padding:16px;margin-bottom:14px;box-shadow:var(--shadow)} | ||
| 31 | +.card h2{margin:0 0 10px;font-size:11.5px;letter-spacing:.07em;text-transform:uppercase; | ||
| 32 | + color:var(--text-2);font-weight:600} | ||
| 33 | +.hint{color:var(--text-2);font-size:12px;margin:0 0 10px} | ||
| 34 | +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px} | ||
| 35 | +.kpi{background:var(--surface-2);border:1px solid var(--line);border-radius:10px; | ||
| 36 | + padding:10px 12px} | ||
| 37 | +.kpi .k{font-size:10.5px;color:var(--text-2);text-transform:uppercase;letter-spacing:.05em} | ||
| 38 | +.kpi .v{font-size:15px;font-weight:700;font-family:var(--mono);margin-top:3px; | ||
| 39 | + word-break:break-word} | ||
| 40 | +.tb{width:100%;overflow-x:auto} | ||
| 41 | +table{width:100%;border-collapse:collapse;font-size:13px} | ||
| 42 | +th{text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em; | ||
| 43 | + color:var(--text-2);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line); | ||
| 44 | + white-space:nowrap} | ||
| 45 | +td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle; | ||
| 46 | + word-break:break-word} | ||
| 47 | +tr:last-child td{border-bottom:0} | ||
| 48 | +.mo{font-family:var(--mono);font-size:12.5px} | ||
| 49 | +.tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap; | ||
| 50 | + background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)} | ||
| 51 | +.tag.ok{background:rgba(48,209,88,.16);color:var(--green)} | ||
| 52 | +.tag.warn{background:rgba(255,159,10,.16);color:var(--orange)} | ||
| 53 | +.tag.bad{background:rgba(255,69,58,.16);color:var(--red)} | ||
| 54 | +.tag.blue{background:rgba(10,132,255,.16);color:var(--blue)} | ||
| 55 | +.tabs{display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap} | ||
| 56 | +.tab{background:var(--surface-2);border:1px solid var(--line);color:var(--text-2); | ||
| 57 | + border-radius:980px;padding:6px 14px;font-size:12.5px;font-weight:600;cursor:pointer; | ||
| 58 | + font-family:inherit} | ||
| 59 | +.tab.on{background:var(--blue);color:#fff;border-color:var(--blue)} | ||
| 60 | +.inp{flex:1 1 240px;min-width:0;background:var(--input-bg);border:1px solid var(--line); | ||
| 61 | + border-radius:10px;padding:10px 12px;color:var(--text);font-size:13.5px; | ||
| 62 | + font-family:inherit} | ||
| 63 | +.inp:focus{outline:2px solid var(--blue);outline-offset:-1px} | ||
| 64 | +.inp.mo{font-family:var(--mono)} | ||
| 65 | +.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap} | ||
| 66 | +.res{border-top:1px solid var(--line);padding-top:12px;margin-top:12px} | ||
| 67 | +.res .hd{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px} | ||
| 68 | +.res .big{font-size:16px;font-weight:700;font-family:var(--mono)} | ||
| 69 | +.kv{display:grid;grid-template-columns:auto 1fr;gap:4px 12px;font-size:12.5px} | ||
| 70 | +.kv .k{color:var(--text-2)} | ||
| 71 | +.kv .v{font-family:var(--mono);word-break:break-all} | ||
| 72 | +ul.hist{list-style:none;margin:0;padding:0} | ||
| 73 | +ul.hist li{display:flex;align-items:center;gap:8px;padding:7px 2px; | ||
| 74 | + border-bottom:1px solid var(--line);font-size:12.5px;flex-wrap:wrap} | ||
| 75 | +ul.hist li:last-child{border-bottom:0} | ||
| 76 | +ul.hist .t{font-family:var(--mono);flex:1 1 200px;min-width:0;word-break:break-all} | ||
| 77 | +ul.hist .ms{font-family:var(--mono);color:var(--text-2);font-size:11.5px} | ||
| 78 | +.spark{width:100%;height:56px;display:block;margin-top:10px} | ||
| 79 | +.spark[hidden]{display:none} | ||
| 80 | +.spark .ln{fill:none;stroke:var(--blue);stroke-width:1.6; | ||
| 81 | + stroke-linecap:round;stroke-linejoin:round} | ||
| 82 | +.spark .ax{stroke:var(--line);stroke-width:1} | ||
| 83 | +.spark .dot{fill:var(--blue)} | ||
| 84 | +.spark .dot.bad{fill:var(--red)} | ||
| 85 | +.empty{color:var(--text-2);font-size:12.5px;padding:10px 0} | ||
| 86 | +[hidden]{display:none!important} | ||
| 87 | +.err{color:var(--red);font-size:12.5px} | ||
| 88 | +.note{color:var(--text-2);font-size:12px;margin-top:8px} | ||
| 89 | +.foot{color:var(--text-2);font-size:11.5px;margin-top:18px;line-height:1.6} | ||
| 90 | +.foot code{font-family:var(--mono);font-size:11px;background:var(--surface-2); | ||
| 91 | + padding:1px 5px;border-radius:5px;border:1px solid var(--line)} | ||
| 92 | +@media(max-width:700px){.wrap{padding:10px 10px 24px}.card{padding:12px;border-radius:12px} | ||
| 93 | + .title{font-size:17px}} | ||
| 94 | +</style></head><body><div class="wrap"> | ||
| 95 | + | ||
| 96 | +<div class="top"> | ||
| 97 | + <a href="/" class="embed-hide" style="color:var(--blue);text-decoration:none;font-weight:600">←</a> | ||
| 98 | + <h1 class="title">netcheck</h1> | ||
| 99 | + <span class="pill" id="srcPill">this node</span> | ||
| 100 | + <span class="sp"></span> | ||
| 101 | + <button class="icon embed-hide" id="thBtn" title="Toggle appearance" aria-label="Toggle appearance"> | ||
| 102 | + <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.5"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/></svg> | ||
| 103 | + </button> | ||
| 104 | + <button class="icon" id="rfBtn" title="Refresh interfaces" aria-label="Refresh interfaces"> | ||
| 105 | + <svg viewBox="0 0 24 24"><path d="M20 11a8 8 0 1 0-2.3 5.7"/><path d="M20 5v6h-6"/></svg> | ||
| 106 | + </button> | ||
| 107 | +</div> | ||
| 108 | + | ||
| 109 | +<div class="card"> | ||
| 110 | + <h2>Interfaces on this node</h2> | ||
| 111 | + <p class="hint">Addresses read from the node's own interface table. Nothing leaves the machine for this view.</p> | ||
| 112 | + <div class="grid" id="kpis"></div> | ||
| 113 | + <div class="tb" style="margin-top:12px"> | ||
| 114 | + <table> | ||
| 115 | + <thead><tr><th>Interface</th><th>Address</th><th>Netmask</th><th>State</th></tr></thead> | ||
| 116 | + <tbody id="ifrows"></tbody> | ||
| 117 | + </table> | ||
| 118 | + </div> | ||
| 119 | + <div class="empty" id="ifEmpty" hidden>No interfaces found.</div> | ||
| 120 | + <div class="res"> | ||
| 121 | + <h2 style="margin-top:0">Configured DNS servers</h2> | ||
| 122 | + <div class="row" id="nsList"></div> | ||
| 123 | + </div> | ||
| 124 | +</div> | ||
| 125 | + | ||
| 126 | +<div class="card"> | ||
| 127 | + <h2>Run a check</h2> | ||
| 128 | + <div class="tabs" role="tablist"> | ||
| 129 | + <button class="tab on" id="tabDns" role="tab" data-tab="dns">DNS</button> | ||
| 130 | + <button class="tab" id="tabTcp" role="tab" data-tab="tcp">TCP</button> | ||
| 131 | + <button class="tab" id="tabHttp" role="tab" data-tab="http">HTTP</button> | ||
| 132 | + </div> | ||
| 133 | + <div class="row"> | ||
| 134 | + <input id="inp" class="inp mo" placeholder="example.com" autocomplete="off" spellcheck="false" aria-label="Target"> | ||
| 135 | + <input id="port" class="inp mo" type="number" min="1" max="65535" step="1" | ||
| 136 | + value="443" style="width:110px;display:none" placeholder="port" aria-label="Port"> | ||
| 137 | + <button class="btn" id="goBtn">Check</button> | ||
| 138 | + </div> | ||
| 139 | + <p class="note" id="tabNote">Resolves a name to its addresses. Uses the node's resolver with a 3 second deadline.</p> | ||
| 140 | + <div class="res" id="resBox"> | ||
| 141 | + <div class="hd"><span class="big" id="resState">idle</span><span id="resTag"></span></div> | ||
| 142 | + <div class="kv" id="resKv"></div> | ||
| 143 | + <div class="note" id="resNote"></div> | ||
| 144 | + <svg class="spark" id="spark" viewBox="0 0 320 56" preserveAspectRatio="none" | ||
| 145 | + aria-label="TCP latency history" hidden></svg> | ||
| 146 | + </div> | ||
| 147 | +</div> | ||
| 148 | + | ||
| 149 | +<div class="card"> | ||
| 150 | + <h2>History <span class="pill" id="histCount">0</span></h2> | ||
| 151 | + <p class="hint">Kept in this page only — nothing is written to disk.</p> | ||
| 152 | + <ul class="hist" id="hist"><li class="empty">No checks yet this session.</li></ul> | ||
| 153 | +</div> | ||
| 154 | + | ||
| 155 | +<p class="foot"> | ||
| 156 | + netcheck runs on the node and makes only the outbound connections you ask for: a DNS lookup, | ||
| 157 | + a TCP connect, or one <code>HEAD</code> request over plain HTTP. There is no TLS library in the | ||
| 158 | + binary, so an <code>https://</code> target is checked as a TCP connect to port 443 and reported | ||
| 159 | + as <code>tls: not_checked</code>. Response bodies are never read, and redirects are never followed. | ||
| 160 | + Every action sits behind node authentication. | ||
| 161 | +</p> | ||
| 162 | +</div> | ||
| 163 | +<script> | ||
| 164 | +(function(){ | ||
| 165 | +"use strict"; | ||
| 166 | +var q=new URLSearchParams(location.search); | ||
| 167 | +var node=q.get('node')||''; | ||
| 168 | +var sid=q.get('id')||''; | ||
| 169 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | ||
| 170 | + localStorage.getItem('bot_active_pwd')||''; | ||
| 171 | +var HUB=q.get('plugin')||''; | ||
| 172 | + | ||
| 173 | +/* Two call routes, and getting this wrong is the most common plugin bug: | ||
| 174 | + * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_netcheck&node=..) | ||
| 175 | + * -> call the hub proxy back: /plugins?plugin=plugin_netcheck&action=.. | ||
| 176 | + * opened directly on the node | ||
| 177 | + * -> the plugin itself is the route: /plugin_netcheck?action=.. | ||
| 178 | + * Calling /plugins?plugin= on the node returns the discovery list, not us. */ | ||
| 179 | +function api(action,params){ | ||
| 180 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_netcheck') | ||
| 181 | + +'?action='+encodeURIComponent(action) | ||
| 182 | + +(params||'') | ||
| 183 | + +(node?'&node='+encodeURIComponent(node):'') | ||
| 184 | + +(sid?'&id='+encodeURIComponent(sid):'') | ||
| 185 | + +(pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 186 | + return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}) | ||
| 187 | + .then(function(r){return r.json().then(function(d){if(!r.ok)throw new Error('HTTP '+r.status);return d;});}); | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +function esc(v){return String(v==null?'':v).replace(/[&<>"']/g,function(c){ | ||
| 191 | + return({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c];});} | ||
| 192 | +function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;} | ||
| 193 | +function $(id){return document.getElementById(id);} | ||
| 194 | + | ||
| 195 | +var TAB='dns'; | ||
| 196 | +var HIST=[]; /* last 20 checks, in-page only */ | ||
| 197 | +var TCPMS=[]; /* tcp latency samples for the sparkline */ | ||
| 198 | + | ||
| 199 | +var NOTE={ | ||
| 200 | + dns:'Resolves a name to its addresses. Uses the node\'s resolver with a 3 second deadline.', | ||
| 201 | + tcp:'Measures a TCP connect. Three samples, 3 second deadline each, reported as min/avg/max.', | ||
| 202 | + http:'Sends one HEAD request over plain TCP. Status line and headers only, body never read, no redirects.' | ||
| 203 | +}; | ||
| 204 | +var PH={dns:'example.com',tcp:'example.com',http:'http://example.com'}; | ||
| 205 | + | ||
| 206 | +function setTab(t){ | ||
| 207 | + TAB=t; | ||
| 208 | + ['dns','tcp','http'].forEach(function(k){ | ||
| 209 | + var b=$('tab'+k.charAt(0).toUpperCase()+k.slice(1)); | ||
| 210 | + if(b)b.className='tab'+(k===t?' on':''); | ||
| 211 | + }); | ||
| 212 | + $('port').style.display=(t==='tcp')?'':'none'; | ||
| 213 | + $('inp').placeholder=PH[t]; | ||
| 214 | + txt('tabNote',NOTE[t]); | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +/* ---------- interfaces ---------- */ | ||
| 218 | +function renderIfaces(d){ | ||
| 219 | + var rows=$('ifrows'),kp=$('kpis'),ns=$('nsList'); | ||
| 220 | + var list=(d&&d.interfaces)||[]; | ||
| 221 | + var upn=0,glob=0,lo=0,i; | ||
| 222 | + var h=''; | ||
| 223 | + for(i=0;i<list.length;i++){ | ||
| 224 | + var f=list[i]; | ||
| 225 | + if(f.up)upn++; | ||
| 226 | + if(!f.loopback&&(f.family===4||f.addr!=='::1'))glob++; | ||
| 227 | + if(f.loopback)lo++; | ||
| 228 | + h+='<tr><td class="mo">'+esc(f.name)+'</td>' | ||
| 229 | + +'<td class="mo">'+esc(f.address)+'</td>' | ||
| 230 | + +'<td class="mo">'+esc(f.netmask||'-')+'</td>' | ||
| 231 | + +'<td>'+(f.up?'<span class="tag ok">up</span>':'<span class="tag bad">down</span>') | ||
| 232 | + +(f.loopback?' <span class="tag">loopback</span>':'') | ||
| 233 | + +(f.family===6?' <span class="tag">ipv6</span>':'')+'</td></tr>'; | ||
| 234 | + } | ||
| 235 | + rows.innerHTML=h; | ||
| 236 | + /* show the empty message only when there really are no rows */ | ||
| 237 | + if(list.length){$('ifEmpty').setAttribute('hidden','');} | ||
| 238 | + else{$('ifEmpty').removeAttribute('hidden');} | ||
| 239 | + var nsr=(d&&d.nameservers)||[]; | ||
| 240 | + var kh=''; | ||
| 241 | + kh+='<div class="kpi"><div class="k">Interfaces</div><div class="v">'+list.length+'</div></div>'; | ||
| 242 | + kh+='<div class="kpi"><div class="k">Up</div><div class="v">'+upn+'</div></div>'; | ||
| 243 | + kh+='<div class="kpi"><div class="k">Loopback</div><div class="v">'+lo+'</div></div>'; | ||
| 244 | + kh+='<div class="kpi"><div class="k">DNS servers</div><div class="v">'+nsr.length+'</div></div>'; | ||
| 245 | + kp.innerHTML=kh; | ||
| 246 | + if(!nsr.length){ns.innerHTML='<span class="empty">None configured.</span>';} | ||
| 247 | + else{var nh='';for(i=0;i<nsr.length;i++)nh+='<span class="tag blue">'+esc(nsr[i])+'</span>';ns.innerHTML=nh;} | ||
| 248 | + txt('srcPill',(d&&d.count!=null)?(list.length+' iface'+(list.length===1?'':'s')):'this node'); | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +function loadIfaces(){ | ||
| 252 | + api('ifaces','').then(renderIfaces).catch(function(e){ | ||
| 253 | + $('ifrows').innerHTML=''; | ||
| 254 | + $('kpis').innerHTML='<div class="kpi"><div class="k">Error</div><div class="v">'+esc(String(e.message||e))+'</div></div>'; | ||
| 255 | + $('ifEmpty').removeAttribute('hidden'); | ||
| 256 | + }); | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +/* ---------- sparkline ---------- */ | ||
| 260 | +function drawSpark(){ | ||
| 261 | + var svg=$('spark'); | ||
| 262 | + /* `hidden` is an HTMLElement property, not an SVGElement one, so it has to | ||
| 263 | + * be set as an attribute or the browser keeps the one from the markup. */ | ||
| 264 | + if(TAB!=='tcp'||TCPMS.length<2){svg.setAttribute('hidden','');return;} | ||
| 265 | + svg.removeAttribute('hidden'); | ||
| 266 | + var W=320,H=56,PAD=6; | ||
| 267 | + var vals=TCPMS.slice(-20); | ||
| 268 | + var good=vals.filter(function(v){return v>=0;}); | ||
| 269 | + var mx=good.length?Math.max.apply(null,good):0; | ||
| 270 | + var mn=good.length?Math.min.apply(null,good):0; | ||
| 271 | + /* A flat series has no range to normalise against. Plot it on the middle | ||
| 272 | + * line instead of the floor, otherwise "every connect was instant" reads | ||
| 273 | + * like "every connect hit the deadline". */ | ||
| 274 | + var flat=(mx-mn)<1; | ||
| 275 | + var scale=flat?1:(mx-mn); | ||
| 276 | + var n=vals.length; | ||
| 277 | + var pts=[],i,x,y; | ||
| 278 | + for(i=0;i<n;i++){ | ||
| 279 | + x=PAD+(i*(W-2*PAD))/(n-1); | ||
| 280 | + var v=vals[i]; | ||
| 281 | + if(v<0){y=H-PAD;} | ||
| 282 | + else if(flat){y=(H-2*PAD)/2+PAD;} | ||
| 283 | + else{y=H-PAD-((H-2*PAD)*((v-mn)/scale));} | ||
| 284 | + pts.push([x,y,v]); | ||
| 285 | + } | ||
| 286 | + var out='<line class="ax" x1="0" y1="'+(H-PAD)+'" x2="'+W+'" y2="'+(H-PAD)+'"/>'; | ||
| 287 | + var d=''; | ||
| 288 | + for(i=0;i<pts.length;i++){ | ||
| 289 | + if(pts[i][2]<0)continue; | ||
| 290 | + d+=(d?'L':'M')+pts[i][0].toFixed(1)+' '+pts[i][1].toFixed(1); | ||
| 291 | + } | ||
| 292 | + if(d)out+='<path class="ln" d="'+d+'"/>'; | ||
| 293 | + for(i=0;i<pts.length;i++){ | ||
| 294 | + out+='<circle class="dot'+(pts[i][2]<0?' bad':'')+'" cx="'+pts[i][0].toFixed(1) | ||
| 295 | + +'" cy="'+pts[i][1].toFixed(1)+'" r="2.4"/>'; | ||
| 296 | + } | ||
| 297 | + svg.innerHTML=out; | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +/* ---------- history ---------- */ | ||
| 301 | +function pushHist(item){ | ||
| 302 | + HIST.unshift(item); | ||
| 303 | + if(HIST.length>20)HIST.pop(); | ||
| 304 | + renderHist(); | ||
| 305 | +} | ||
| 306 | +function renderHist(){ | ||
| 307 | + var ul=$('hist'); | ||
| 308 | + txt('histCount',String(HIST.length)); | ||
| 309 | + if(!HIST.length){ul.innerHTML='<li class="empty">No checks yet this session.</li>';return;} | ||
| 310 | + var h=''; | ||
| 311 | + for(var i=0;i<HIST.length;i++){ | ||
| 312 | + var it=HIST[i]; | ||
| 313 | + h+='<li><span class="tag '+(it.ok?'ok':'bad')+'">'+esc(it.kind)+'</span>' | ||
| 314 | + +'<span class="t">'+esc(it.label)+'</span>' | ||
| 315 | + +'<span class="ms">'+esc(it.detail)+'</span>' | ||
| 316 | + +'<span class="ms">'+esc(it.at)+'</span></li>'; | ||
| 317 | + } | ||
| 318 | + ul.innerHTML=h; | ||
| 319 | +} | ||
| 320 | + | ||
| 321 | +/* ---------- result rendering ---------- */ | ||
| 322 | +function kv(pairs){ | ||
| 323 | + var h=''; | ||
| 324 | + for(var i=0;i<pairs.length;i++){ | ||
| 325 | + h+='<div class="k"><span class="k">'+esc(pairs[i][0])+'</span></div>' | ||
| 326 | + +'<div class="v">'+esc(pairs[i][1]==null?'-':String(pairs[i][1]))+'</div>'; | ||
| 327 | + } | ||
| 328 | + $('resKv').innerHTML=h; | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +function showDns(d,target){ | ||
| 332 | + var ok=d.resolved===true; | ||
| 333 | + txt('resState',ok?'resolved':'not resolved'); | ||
| 334 | + $('resTag').innerHTML=ok?'<span class="tag ok">ok</span>':'<span class="tag bad">'+esc(d.timeout?'timeout':'fail')+'</span>'; | ||
| 335 | + var pairs=[['host',d.host],['latency',(d.latency_ms==null?'-':d.latency_ms+' ms')], | ||
| 336 | + ['answers',d.count],['deadline',d.timeout_ms+' ms']]; | ||
| 337 | + if(d.results&&d.results.length){ | ||
| 338 | + var addrs=[]; | ||
| 339 | + for(var i=0;i<d.results.length;i++)addrs.push(d.results[i].address); | ||
| 340 | + pairs.push(['addresses',addrs.join(', ')]); | ||
| 341 | + } | ||
| 342 | + kv(pairs); | ||
| 343 | + txt('resNote',ok?'':'The resolver returned no record for this name.'); | ||
| 344 | + pushHist({kind:'dns',label:target,ok:ok,detail:(d.count||0)+' addr',at:clock()}); | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +function showTcp(d,target){ | ||
| 348 | + var open=d.open===true; | ||
| 349 | + var last=(d.samples&&d.samples.length)?d.samples[d.samples.length-1]:null; | ||
| 350 | + TCPMS.push(typeof last==='number'?last:-1); | ||
| 351 | + if(TCPMS.length>20)TCPMS.shift(); | ||
| 352 | + txt('resState',open?'open':(d.status==='timeout'?'timeout':'closed')); | ||
| 353 | + $('resTag').innerHTML=open?'<span class="tag ok">reachable</span>' | ||
| 354 | + :'<span class="tag bad">'+esc(d.status||'closed')+'</span>'; | ||
| 355 | + var pairs=[['target',d.host+':'+d.port],['resolved to',d.address], | ||
| 356 | + ['avg',(d.avg_ms==null?'-':d.avg_ms+' ms')], | ||
| 357 | + ['min',(d.min_ms==null?'-':d.min_ms+' ms')], | ||
| 358 | + ['max',(d.max_ms==null?'-':d.max_ms+' ms')], | ||
| 359 | + ['samples',(d.samples||[]).map(function(s){return s==null?'timeout':s+' ms';}).join(', ')]]; | ||
| 360 | + kv(pairs); | ||
| 361 | + txt('resNote',open?'Three connects succeeded against the first resolved address.' | ||
| 362 | + :'The connect did not complete inside the deadline.'); | ||
| 363 | + drawSpark(); | ||
| 364 | + pushHist({kind:'tcp',label:d.host+':'+d.port,ok:open, | ||
| 365 | + detail:open?((d.avg_ms==null?'-':d.avg_ms+' ms avg')):d.status,at:clock()}); | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +function showHttp(d,target){ | ||
| 369 | + var ok=d.reachable===true&&d.status!=null&&d.status<400; | ||
| 370 | + txt('resState',d.status==null?(d.reachable?'connected':'unreachable'):('HTTP '+d.status)); | ||
| 371 | + $('resTag').innerHTML=d.status==null | ||
| 372 | + ?(d.reachable?'<span class="tag warn">no status line</span>':'<span class="tag bad">unreachable</span>') | ||
| 373 | + :(ok?'<span class="tag ok">reachable</span>':'<span class="tag bad">status '+esc(d.status)+'</span>'); | ||
| 374 | + var pairs=[['url',d.url],['host',d.host+':'+d.port],['path',d.path], | ||
| 375 | + ['connect',(d.connect_ms==null?'-':d.connect_ms+' ms')], | ||
| 376 | + ['status',(d.status==null?'-':d.status+' '+(d.status_text||''))], | ||
| 377 | + ['headers',d.header_lines],['body','0 bytes (HEAD)'], | ||
| 378 | + ['tls',d.tls]]; | ||
| 379 | + kv(pairs); | ||
| 380 | + txt('resNote',d.note||''); | ||
| 381 | + pushHist({kind:'http',label:d.url,ok:ok,detail:(d.status==null?'no status':String(d.status)),at:clock()}); | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +function clock(){ | ||
| 385 | + var d=new Date(); | ||
| 386 | + return d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit',second:'2-digit'}); | ||
| 387 | +} | ||
| 388 | + | ||
| 389 | +function run(){ | ||
| 390 | + var v=$('inp').value.trim(); | ||
| 391 | + if(!v){txt('resState','enter a target');return;} | ||
| 392 | + txt('resState','running...'); | ||
| 393 | + $('resKv').innerHTML=''; | ||
| 394 | + $('resNote').textContent=''; | ||
| 395 | + $('goBtn').disabled=true; | ||
| 396 | + var p=''; | ||
| 397 | + var call; | ||
| 398 | + if(TAB==='dns'){call=api('dns','&host='+encodeURIComponent(v));} | ||
| 399 | + else if(TAB==='tcp'){ | ||
| 400 | + var pt=$('port').value.trim(); | ||
| 401 | + if(!pt){$('goBtn').disabled=false;txt('resState','port required');return;} | ||
| 402 | + call=api('tcp','&host='+encodeURIComponent(v)+'&port='+encodeURIComponent(pt)); | ||
| 403 | + } else { | ||
| 404 | + var uv=v; | ||
| 405 | + if(!/^https?:\/\//i.test(uv))uv='http://'+uv; | ||
| 406 | + call=api('http','&url='+encodeURIComponent(uv)); | ||
| 407 | + } | ||
| 408 | + call.then(function(d){ | ||
| 409 | + $('goBtn').disabled=false; | ||
| 410 | + if(!d||d.ok!==true){ | ||
| 411 | + txt('resState','error'); | ||
| 412 | + kv([['error',(d&&d.error)||'request failed']]); | ||
| 413 | + pushHist({kind:TAB,label:v,ok:false,detail:(d&&d.error)||'error',at:clock()}); | ||
| 414 | + return; | ||
| 415 | + } | ||
| 416 | + if(TAB==='dns')showDns(d,v); | ||
| 417 | + else if(TAB==='tcp')showTcp(d,v); | ||
| 418 | + else showHttp(d,v); | ||
| 419 | + }).catch(function(e){ | ||
| 420 | + $('goBtn').disabled=false; | ||
| 421 | + txt('resState','error'); | ||
| 422 | + kv([['error',String(e.message||e)]]); | ||
| 423 | + pushHist({kind:TAB,label:v,ok:false,detail:String(e.message||e),at:clock()}); | ||
| 424 | + }); | ||
| 425 | +} | ||
| 426 | + | ||
| 427 | +/* ---------- theme toggle (standalone only) ---------- */ | ||
| 428 | +function toggleTheme(){ | ||
| 429 | + var cur=(document.documentElement.getAttribute('data-theme')||'dark')==='light'?'dark':'light'; | ||
| 430 | + document.documentElement.setAttribute('data-theme',cur); | ||
| 431 | + try{localStorage.setItem('bot_theme',cur);}catch(e){} | ||
| 432 | + try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:cur}));}catch(e){} | ||
| 433 | +} | ||
| 434 | + | ||
| 435 | +$('goBtn').addEventListener('click',run); | ||
| 436 | +$('inp').addEventListener('keydown',function(e){if(e.key==='Enter'){e.preventDefault();run();}}); | ||
| 437 | +$('rfBtn').addEventListener('click',loadIfaces); | ||
| 438 | +$('thBtn').addEventListener('click',toggleTheme); | ||
| 439 | +$('tabDns').addEventListener('click',function(){setTab('dns');}); | ||
| 440 | +$('tabTcp').addEventListener('click',function(){setTab('tcp');}); | ||
| 441 | +$('tabHttp').addEventListener('click',function(){setTab('http');}); | ||
| 442 | + | ||
| 443 | +setTab('dns'); | ||
| 444 | +loadIfaces(); | ||
| 445 | +})(); | ||
| 446 | +</script></body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f705717 | index 0000000..f705717 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,454 @@ | @@ -0,0 +1,454 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_NETCHECK_UI_HTML_H | ||
| 3 | +#define SX_NETCHECK_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | ||
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 9 | + "<title>netcheck</title>\n" | ||
| 10 | + "\001\n" | ||
| 11 | + "<style>\n" | ||
| 12 | + "*{box-sizing:border-box}\n" | ||
| 13 | + "html,body{margin:0;height:100%}\n" | ||
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);\n" | ||
| 15 | + " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}\n" | ||
| 16 | + ".wrap{max-width:1080px;margin:0 auto;padding:16px 16px 32px}\n" | ||
| 17 | + ".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}\n" | ||
| 18 | + ".title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em}\n" | ||
| 19 | + ".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;\n" | ||
| 20 | + " background:var(--surface-2);color:var(--text-2);border:1px solid var(--line);\n" | ||
| 21 | + " white-space:nowrap}\n" | ||
| 22 | + ".sp{flex:1}\n" | ||
| 23 | + ".icon{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | ||
| 24 | + " background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | ||
| 25 | + " border-radius:9px;width:30px;height:30px;padding:0;cursor:pointer;font-family:inherit;\n" | ||
| 26 | + " font-size:12px;font-weight:600}\n" | ||
| 27 | + ".icon:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 28 | + ".icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;\n" | ||
| 29 | + " stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 30 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:8px 16px;\n" | ||
| 31 | + " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}\n" | ||
| 32 | + ".btn:disabled{opacity:.55;cursor:default}\n" | ||
| 33 | + ".btn.gh{background:transparent;color:var(--text);border:1px solid var(--line)}\n" | ||
| 34 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | ||
| 35 | + " padding:16px;margin-bottom:14px;box-shadow:var(--shadow)}\n" | ||
| 36 | + ".card h2{margin:0 0 10px;font-size:11.5px;letter-spacing:.07em;text-transform:uppercase;\n" | ||
| 37 | + " color:var(--text-2);font-weight:600}\n" | ||
| 38 | + ".hint{color:var(--text-2);font-size:12px;margin:0 0 10px}\n" | ||
| 39 | + ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px}\n" | ||
| 40 | + ".kpi{background:var(--surface-2);border:1px solid var(--line);border-radius:10px;\n" | ||
| 41 | + " padding:10px 12px}\n" | ||
| 42 | + ".kpi .k{font-size:10.5px;color:var(--text-2);text-transform:uppercase;letter-spacing:.05em}\n" | ||
| 43 | + ".kpi .v{font-size:15px;font-weight:700;font-family:var(--mono);margin-top:3px;\n" | ||
| 44 | + " word-break:break-word}\n" | ||
| 45 | + ".tb{width:100%;overflow-x:auto}\n" | ||
| 46 | + "table{width:100%;border-collapse:collapse;font-size:13px}\n" | ||
| 47 | + "th{text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em;\n" | ||
| 48 | + " color:var(--text-2);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);\n" | ||
| 49 | + " white-space:nowrap}\n" | ||
| 50 | + "td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle;\n" | ||
| 51 | + " word-break:break-word}\n" | ||
| 52 | + "tr:last-child td{border-bottom:0}\n" | ||
| 53 | + ".mo{font-family:var(--mono);font-size:12.5px}\n" | ||
| 54 | + ".tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap;\n" | ||
| 55 | + " background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)}\n" | ||
| 56 | + ".tag.ok{background:rgba(48,209,88,.16);color:var(--green)}\n" | ||
| 57 | + ".tag.warn{background:rgba(255,159,10,.16);color:var(--orange)}\n" | ||
| 58 | + ".tag.bad{background:rgba(255,69,58,.16);color:var(--red)}\n" | ||
| 59 | + ".tag.blue{background:rgba(10,132,255,.16);color:var(--blue)}\n" | ||
| 60 | + ".tabs{display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap}\n" | ||
| 61 | + ".tab{background:var(--surface-2);border:1px solid var(--line);color:var(--text-2);\n" | ||
| 62 | + " border-radius:980px;padding:6px 14px;font-size:12.5px;font-weight:600;cursor:pointer;\n" | ||
| 63 | + " font-family:inherit}\n" | ||
| 64 | + ".tab.on{background:var(--blue);color:#fff;border-color:var(--blue)}\n" | ||
| 65 | + ".inp{flex:1 1 240px;min-width:0;background:var(--input-bg);border:1px solid var(--line);\n" | ||
| 66 | + " border-radius:10px;padding:10px 12px;color:var(--text);font-size:13.5px;\n" | ||
| 67 | + " font-family:inherit}\n" | ||
| 68 | + ".inp:focus{outline:2px solid var(--blue);outline-offset:-1px}\n" | ||
| 69 | + ".inp.mo{font-family:var(--mono)}\n" | ||
| 70 | + ".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}\n" | ||
| 71 | + ".res{border-top:1px solid var(--line);padding-top:12px;margin-top:12px}\n" | ||
| 72 | + ".res .hd{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px}\n" | ||
| 73 | + ".res .big{font-size:16px;font-weight:700;font-family:var(--mono)}\n" | ||
| 74 | + ".kv{display:grid;grid-template-columns:auto 1fr;gap:4px 12px;font-size:12.5px}\n" | ||
| 75 | + ".kv .k{color:var(--text-2)}\n" | ||
| 76 | + ".kv .v{font-family:var(--mono);word-break:break-all}\n" | ||
| 77 | + "ul.hist{list-style:none;margin:0;padding:0}\n" | ||
| 78 | + "ul.hist li{display:flex;align-items:center;gap:8px;padding:7px 2px;\n" | ||
| 79 | + " border-bottom:1px solid var(--line);font-size:12.5px;flex-wrap:wrap}\n" | ||
| 80 | + "ul.hist li:last-child{border-bottom:0}\n" | ||
| 81 | + "ul.hist .t{font-family:var(--mono);flex:1 1 200px;min-width:0;word-break:break-all}\n" | ||
| 82 | + "ul.hist .ms{font-family:var(--mono);color:var(--text-2);font-size:11.5px}\n" | ||
| 83 | + ".spark{width:100%;height:56px;display:block;margin-top:10px}\n" | ||
| 84 | + ".spark[hidden]{display:none}\n" | ||
| 85 | + ".spark .ln{fill:none;stroke:var(--blue);stroke-width:1.6;\n" | ||
| 86 | + " stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 87 | + ".spark .ax{stroke:var(--line);stroke-width:1}\n" | ||
| 88 | + ".spark .dot{fill:var(--blue)}\n" | ||
| 89 | + ".spark .dot.bad{fill:var(--red)}\n" | ||
| 90 | + ".empty{color:var(--text-2);font-size:12.5px;padding:10px 0}\n" | ||
| 91 | + "[hidden]{display:none!important}\n" | ||
| 92 | + ".err{color:var(--red);font-size:12.5px}\n" | ||
| 93 | + ".note{color:var(--text-2);font-size:12px;margin-top:8px}\n" | ||
| 94 | + ".foot{color:var(--text-2);font-size:11.5px;margin-top:18px;line-height:1.6}\n" | ||
| 95 | + ".foot code{font-family:var(--mono);font-size:11px;background:var(--surface-2);\n" | ||
| 96 | + " padding:1px 5px;border-radius:5px;border:1px solid var(--line)}\n" | ||
| 97 | + "@media(max-width:700px){.wrap{padding:10px 10px 24px}.card{padding:12px;border-radius:12px}\n" | ||
| 98 | + " .title{font-size:17px}}\n" | ||
| 99 | + "</style></head><body><div class=\"wrap\">\n" | ||
| 100 | + "\n" | ||
| 101 | + "<div class=\"top\">\n" | ||
| 102 | + " <a href=\"/\" class=\"embed-hide\" style=\"color:var(--blue);text-decoration:none;font-weight:600\">←</a>\n" | ||
| 103 | + " <h1 class=\"title\">netcheck</h1>\n" | ||
| 104 | + " <span class=\"pill\" id=\"srcPill\">this node</span>\n" | ||
| 105 | + " <span class=\"sp\"></span>\n" | ||
| 106 | + " <button class=\"icon embed-hide\" id=\"thBtn\" title=\"Toggle appearance\" aria-label=\"Toggle appearance\">\n" | ||
| 107 | + " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4.5\"/><path d=\"M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4\"/></svg>\n" | ||
| 108 | + " </button>\n" | ||
| 109 | + " <button class=\"icon\" id=\"rfBtn\" title=\"Refresh interfaces\" aria-label=\"Refresh interfaces\">\n" | ||
| 110 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M20 11a8 8 0 1 0-2.3 5.7\"/><path d=\"M20 5v6h-6\"/></svg>\n" | ||
| 111 | + " </button>\n" | ||
| 112 | + "</div>\n" | ||
| 113 | + "\n" | ||
| 114 | + "<div class=\"card\">\n" | ||
| 115 | + " <h2>Interfaces on this node</h2>\n" | ||
| 116 | + " <p class=\"hint\">Addresses read from the node's own interface table. Nothing leaves the machine for this view.</p>\n" | ||
| 117 | + " <div class=\"grid\" id=\"kpis\"></div>\n" | ||
| 118 | + " <div class=\"tb\" style=\"margin-top:12px\">\n" | ||
| 119 | + " <table>\n" | ||
| 120 | + " <thead><tr><th>Interface</th><th>Address</th><th>Netmask</th><th>State</th></tr></thead>\n" | ||
| 121 | + " <tbody id=\"ifrows\"></tbody>\n" | ||
| 122 | + " </table>\n" | ||
| 123 | + " </div>\n" | ||
| 124 | + " <div class=\"empty\" id=\"ifEmpty\" hidden>No interfaces found.</div>\n" | ||
| 125 | + " <div class=\"res\">\n" | ||
| 126 | + " <h2 style=\"margin-top:0\">Configured DNS servers</h2>\n" | ||
| 127 | + " <div class=\"row\" id=\"nsList\"></div>\n" | ||
| 128 | + " </div>\n" | ||
| 129 | + "</div>\n" | ||
| 130 | + "\n" | ||
| 131 | + "<div class=\"card\">\n" | ||
| 132 | + " <h2>Run a check</h2>\n" | ||
| 133 | + " <div class=\"tabs\" role=\"tablist\">\n" | ||
| 134 | + " <button class=\"tab on\" id=\"tabDns\" role=\"tab\" data-tab=\"dns\">DNS</button>\n" | ||
| 135 | + " <button class=\"tab\" id=\"tabTcp\" role=\"tab\" data-tab=\"tcp\">TCP</button>\n" | ||
| 136 | + " <button class=\"tab\" id=\"tabHttp\" role=\"tab\" data-tab=\"http\">HTTP</button>\n" | ||
| 137 | + " </div>\n" | ||
| 138 | + " <div class=\"row\">\n" | ||
| 139 | + " <input id=\"inp\" class=\"inp mo\" placeholder=\"example.com\" autocomplete=\"off\" spellcheck=\"false\" aria-label=\"Target\">\n" | ||
| 140 | + " <input id=\"port\" class=\"inp mo\" type=\"number\" min=\"1\" max=\"65535\" step=\"1\"\n" | ||
| 141 | + " value=\"443\" style=\"width:110px;display:none\" placeholder=\"port\" aria-label=\"Port\">\n" | ||
| 142 | + " <button class=\"btn\" id=\"goBtn\">Check</button>\n" | ||
| 143 | + " </div>\n" | ||
| 144 | + " <p class=\"note\" id=\"tabNote\">Resolves a name to its addresses. Uses the node's resolver with a 3 second deadline.</p>\n" | ||
| 145 | + " <div class=\"res\" id=\"resBox\">\n" | ||
| 146 | + " <div class=\"hd\"><span class=\"big\" id=\"resState\">idle</span><span id=\"resTag\"></span></div>\n" | ||
| 147 | + " <div class=\"kv\" id=\"resKv\"></div>\n" | ||
| 148 | + " <div class=\"note\" id=\"resNote\"></div>\n" | ||
| 149 | + " <svg class=\"spark\" id=\"spark\" viewBox=\"0 0 320 56\" preserveAspectRatio=\"none\"\n" | ||
| 150 | + " aria-label=\"TCP latency history\" hidden></svg>\n" | ||
| 151 | + " </div>\n" | ||
| 152 | + "</div>\n" | ||
| 153 | + "\n" | ||
| 154 | + "<div class=\"card\">\n" | ||
| 155 | + " <h2>History <span class=\"pill\" id=\"histCount\">0</span></h2>\n" | ||
| 156 | + " <p class=\"hint\">Kept in this page only — nothing is written to disk.</p>\n" | ||
| 157 | + " <ul class=\"hist\" id=\"hist\"><li class=\"empty\">No checks yet this session.</li></ul>\n" | ||
| 158 | + "</div>\n" | ||
| 159 | + "\n" | ||
| 160 | + "<p class=\"foot\">\n" | ||
| 161 | + " netcheck runs on the node and makes only the outbound connections you ask for: a DNS lookup,\n" | ||
| 162 | + " a TCP connect, or one <code>HEAD</code> request over plain HTTP. There is no TLS library in the\n" | ||
| 163 | + " binary, so an <code>https://</code> target is checked as a TCP connect to port 443 and reported\n" | ||
| 164 | + " as <code>tls: not_checked</code>. Response bodies are never read, and redirects are never followed.\n" | ||
| 165 | + " Every action sits behind node authentication.\n" | ||
| 166 | + "</p>\n" | ||
| 167 | + "</div>\n" | ||
| 168 | + "<script>\n" | ||
| 169 | + "(function(){\n" | ||
| 170 | + "\"use strict\";\n" | ||
| 171 | + "var q=new URLSearchParams(location.search);\n" | ||
| 172 | + "var node=q.get('node')||'';\n" | ||
| 173 | + "var sid=q.get('id')||'';\n" | ||
| 174 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | ||
| 175 | + " localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 176 | + "var HUB=q.get('plugin')||'';\n" | ||
| 177 | + "\n" | ||
| 178 | + "/* Two call routes, and getting this wrong is the most common plugin bug:\n" | ||
| 179 | + " * page served through the hub (bot.scorpiox.net/plugins?plugin=plugin_netcheck&node=..)\n" | ||
| 180 | + " * -> call the hub proxy back: /plugins?plugin=plugin_netcheck&action=..\n" | ||
| 181 | + " * opened directly on the node\n" | ||
| 182 | + " * -> the plugin itself is the route: /plugin_netcheck?action=..\n" | ||
| 183 | + " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n" | ||
| 184 | + "function api(action,params){\n" | ||
| 185 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_netcheck')\n" | ||
| 186 | + " +'?action='+encodeURIComponent(action)\n" | ||
| 187 | + " +(params||'')\n" | ||
| 188 | + " +(node?'&node='+encodeURIComponent(node):'')\n" | ||
| 189 | + " +(sid?'&id='+encodeURIComponent(sid):'')\n" | ||
| 190 | + " +(pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | ||
| 191 | + " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}})\n" | ||
| 192 | + " .then(function(r){return r.json().then(function(d){if(!r.ok)throw new Error('HTTP '+r.status);return d;});});\n" | ||
| 193 | + "}\n" | ||
| 194 | + "\n" | ||
| 195 | + "function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){\n" | ||
| 196 | + " return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}\n" | ||
| 197 | + "function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;}\n" | ||
| 198 | + "function $(id){return document.getElementById(id);}\n" | ||
| 199 | + "\n" | ||
| 200 | + "var TAB='dns';\n" | ||
| 201 | + "var HIST=[]; /* last 20 checks, in-page only */\n" | ||
| 202 | + "var TCPMS=[]; /* tcp latency samples for the sparkline */\n" | ||
| 203 | + "\n" | ||
| 204 | + "var NOTE={\n" | ||
| 205 | + " dns:'Resolves a name to its addresses. Uses the node\\'s resolver with a 3 second deadline.',\n" | ||
| 206 | + " tcp:'Measures a TCP connect. Three samples, 3 second deadline each, reported as min/avg/max.',\n" | ||
| 207 | + " http:'Sends one HEAD request over plain TCP. Status line and headers only, body never read, no redirects.'\n" | ||
| 208 | + "};\n" | ||
| 209 | + "var PH={dns:'example.com',tcp:'example.com',http:'http://example.com'};\n" | ||
| 210 | + "\n" | ||
| 211 | + "function setTab(t){\n" | ||
| 212 | + " TAB=t;\n" | ||
| 213 | + " ['dns','tcp','http'].forEach(function(k){\n" | ||
| 214 | + " var b=$('tab'+k.charAt(0).toUpperCase()+k.slice(1));\n" | ||
| 215 | + " if(b)b.className='tab'+(k===t?' on':'');\n" | ||
| 216 | + " });\n" | ||
| 217 | + " $('port').style.display=(t==='tcp')?'':'none';\n" | ||
| 218 | + " $('inp').placeholder=PH[t];\n" | ||
| 219 | + " txt('tabNote',NOTE[t]);\n" | ||
| 220 | + "}\n" | ||
| 221 | + "\n" | ||
| 222 | + "/* ---------- interfaces ---------- */\n" | ||
| 223 | + "function renderIfaces(d){\n" | ||
| 224 | + " var rows=$('ifrows'),kp=$('kpis'),ns=$('nsList');\n" | ||
| 225 | + " var list=(d&&d.interfaces)||[];\n" | ||
| 226 | + " var upn=0,glob=0,lo=0,i;\n" | ||
| 227 | + " var h='';\n" | ||
| 228 | + " for(i=0;i<list.length;i++){\n" | ||
| 229 | + " var f=list[i];\n" | ||
| 230 | + " if(f.up)upn++;\n" | ||
| 231 | + " if(!f.loopback&&(f.family===4||f.addr!=='::1'))glob++;\n" | ||
| 232 | + " if(f.loopback)lo++;\n" | ||
| 233 | + " h+='<tr><td class=\"mo\">'+esc(f.name)+'</td>'\n" | ||
| 234 | + " +'<td class=\"mo\">'+esc(f.address)+'</td>'\n" | ||
| 235 | + " +'<td class=\"mo\">'+esc(f.netmask||'-')+'</td>'\n" | ||
| 236 | + " +'<td>'+(f.up?'<span class=\"tag ok\">up</span>':'<span class=\"tag bad\">down</span>')\n" | ||
| 237 | + " +(f.loopback?' <span class=\"tag\">loopback</span>':'')\n" | ||
| 238 | + " +(f.family===6?' <span class=\"tag\">ipv6</span>':'')+'</td></tr>';\n" | ||
| 239 | + " }\n" | ||
| 240 | + " rows.innerHTML=h;\n" | ||
| 241 | + " /* show the empty message only when there really are no rows */\n" | ||
| 242 | + " if(list.length){$('ifEmpty').setAttribute('hidden','');}\n" | ||
| 243 | + " else{$('ifEmpty').removeAttribute('hidden');}\n" | ||
| 244 | + " var nsr=(d&&d.nameservers)||[];\n" | ||
| 245 | + " var kh='';\n" | ||
| 246 | + " kh+='<div class=\"kpi\"><div class=\"k\">Interfaces</div><div class=\"v\">'+list.length+'</div></div>';\n" | ||
| 247 | + " kh+='<div class=\"kpi\"><div class=\"k\">Up</div><div class=\"v\">'+upn+'</div></div>';\n" | ||
| 248 | + " kh+='<div class=\"kpi\"><div class=\"k\">Loopback</div><div class=\"v\">'+lo+'</div></div>';\n" | ||
| 249 | + " kh+='<div class=\"kpi\"><div class=\"k\">DNS servers</div><div class=\"v\">'+nsr.length+'</div></div>';\n" | ||
| 250 | + " kp.innerHTML=kh;\n" | ||
| 251 | + " if(!nsr.length){ns.innerHTML='<span class=\"empty\">None configured.</span>';}\n" | ||
| 252 | + " else{var nh='';for(i=0;i<nsr.length;i++)nh+='<span class=\"tag blue\">'+esc(nsr[i])+'</span>';ns.innerHTML=nh;}\n" | ||
| 253 | + " txt('srcPill',(d&&d.count!=null)?(list.length+' iface'+(list.length===1?'':'s')):'this node');\n" | ||
| 254 | + "}\n" | ||
| 255 | + "\n" | ||
| 256 | + "function loadIfaces(){\n" | ||
| 257 | + " api('ifaces','').then(renderIfaces).catch(function(e){\n" | ||
| 258 | + " $('ifrows').innerHTML='';\n" | ||
| 259 | + " $('kpis').innerHTML='<div class=\"kpi\"><div class=\"k\">Error</div><div class=\"v\">'+esc(String(e.message||e))+'</div></div>';\n" | ||
| 260 | + " $('ifEmpty').removeAttribute('hidden');\n" | ||
| 261 | + " });\n" | ||
| 262 | + "}\n" | ||
| 263 | + "\n" | ||
| 264 | + "/* ---------- sparkline ---------- */\n" | ||
| 265 | + "function drawSpark(){\n" | ||
| 266 | + " var svg=$('spark');\n" | ||
| 267 | + " /* `hidden` is an HTMLElement property, not an SVGElement one, so it has to\n" | ||
| 268 | + " * be set as an attribute or the browser keeps the one from the markup. */\n" | ||
| 269 | + " if(TAB!=='tcp'||TCPMS.length<2){svg.setAttribute('hidden','');return;}\n" | ||
| 270 | + " svg.removeAttribute('hidden');\n" | ||
| 271 | + " var W=320,H=56,PAD=6;\n" | ||
| 272 | + " var vals=TCPMS.slice(-20);\n" | ||
| 273 | + " var good=vals.filter(function(v){return v>=0;});\n" | ||
| 274 | + " var mx=good.length?Math.max.apply(null,good):0;\n" | ||
| 275 | + " var mn=good.length?Math.min.apply(null,good):0;\n" | ||
| 276 | + " /* A flat series has no range to normalise against. Plot it on the middle\n" | ||
| 277 | + " * line instead of the floor, otherwise \"every connect was instant\" reads\n" | ||
| 278 | + " * like \"every connect hit the deadline\". */\n" | ||
| 279 | + " var flat=(mx-mn)<1;\n" | ||
| 280 | + " var scale=flat?1:(mx-mn);\n" | ||
| 281 | + " var n=vals.length;\n" | ||
| 282 | + " var pts=[],i,x,y;\n" | ||
| 283 | + " for(i=0;i<n;i++){\n" | ||
| 284 | + " x=PAD+(i*(W-2*PAD))/(n-1);\n" | ||
| 285 | + " var v=vals[i];\n" | ||
| 286 | + " if(v<0){y=H-PAD;}\n" | ||
| 287 | + " else if(flat){y=(H-2*PAD)/2+PAD;}\n" | ||
| 288 | + " else{y=H-PAD-((H-2*PAD)*((v-mn)/scale));}\n" | ||
| 289 | + " pts.push([x,y,v]);\n" | ||
| 290 | + " }\n" | ||
| 291 | + " var out='<line class=\"ax\" x1=\"0\" y1=\"'+(H-PAD)+'\" x2=\"'+W+'\" y2=\"'+(H-PAD)+'\"/>';\n" | ||
| 292 | + " var d='';\n" | ||
| 293 | + " for(i=0;i<pts.length;i++){\n" | ||
| 294 | + " if(pts[i][2]<0)continue;\n" | ||
| 295 | + " d+=(d?'L':'M')+pts[i][0].toFixed(1)+' '+pts[i][1].toFixed(1);\n" | ||
| 296 | + " }\n" | ||
| 297 | + " if(d)out+='<path class=\"ln\" d=\"'+d+'\"/>';\n" | ||
| 298 | + " for(i=0;i<pts.length;i++){\n" | ||
| 299 | + " out+='<circle class=\"dot'+(pts[i][2]<0?' bad':'')+'\" cx=\"'+pts[i][0].toFixed(1)\n" | ||
| 300 | + " +'\" cy=\"'+pts[i][1].toFixed(1)+'\" r=\"2.4\"/>';\n" | ||
| 301 | + " }\n" | ||
| 302 | + " svg.innerHTML=out;\n" | ||
| 303 | + "}\n" | ||
| 304 | + "\n" | ||
| 305 | + "/* ---------- history ---------- */\n" | ||
| 306 | + "function pushHist(item){\n" | ||
| 307 | + " HIST.unshift(item);\n" | ||
| 308 | + " if(HIST.length>20)HIST.pop();\n" | ||
| 309 | + " renderHist();\n" | ||
| 310 | + "}\n" | ||
| 311 | + "function renderHist(){\n" | ||
| 312 | + " var ul=$('hist');\n" | ||
| 313 | + " txt('histCount',String(HIST.length));\n" | ||
| 314 | + " if(!HIST.length){ul.innerHTML='<li class=\"empty\">No checks yet this session.</li>';return;}\n" | ||
| 315 | + " var h='';\n" | ||
| 316 | + " for(var i=0;i<HIST.length;i++){\n" | ||
| 317 | + " var it=HIST[i];\n" | ||
| 318 | + " h+='<li><span class=\"tag '+(it.ok?'ok':'bad')+'\">'+esc(it.kind)+'</span>'\n" | ||
| 319 | + " +'<span class=\"t\">'+esc(it.label)+'</span>'\n" | ||
| 320 | + " +'<span class=\"ms\">'+esc(it.detail)+'</span>'\n" | ||
| 321 | + " +'<span class=\"ms\">'+esc(it.at)+'</span></li>';\n" | ||
| 322 | + " }\n" | ||
| 323 | + " ul.innerHTML=h;\n" | ||
| 324 | + "}\n" | ||
| 325 | + "\n" | ||
| 326 | + "/* ---------- result rendering ---------- */\n" | ||
| 327 | + "function kv(pairs){\n" | ||
| 328 | + " var h='';\n" | ||
| 329 | + " for(var i=0;i<pairs.length;i++){\n" | ||
| 330 | + " h+='<div class=\"k\"><span class=\"k\">'+esc(pairs[i][0])+'</span></div>'\n" | ||
| 331 | + " +'<div class=\"v\">'+esc(pairs[i][1]==null?'-':String(pairs[i][1]))+'</div>';\n" | ||
| 332 | + " }\n" | ||
| 333 | + " $('resKv').innerHTML=h;\n" | ||
| 334 | + "}\n" | ||
| 335 | + "\n" | ||
| 336 | + "function showDns(d,target){\n" | ||
| 337 | + " var ok=d.resolved===true;\n" | ||
| 338 | + " txt('resState',ok?'resolved':'not resolved');\n" | ||
| 339 | + " $('resTag').innerHTML=ok?'<span class=\"tag ok\">ok</span>':'<span class=\"tag bad\">'+esc(d.timeout?'timeout':'fail')+'</span>';\n" | ||
| 340 | + " var pairs=[['host',d.host],['latency',(d.latency_ms==null?'-':d.latency_ms+' ms')],\n" | ||
| 341 | + " ['answers',d.count],['deadline',d.timeout_ms+' ms']];\n" | ||
| 342 | + " if(d.results&&d.results.length){\n" | ||
| 343 | + " var addrs=[];\n" | ||
| 344 | + " for(var i=0;i<d.results.length;i++)addrs.push(d.results[i].address);\n" | ||
| 345 | + " pairs.push(['addresses',addrs.join(', ')]);\n" | ||
| 346 | + " }\n" | ||
| 347 | + " kv(pairs);\n" | ||
| 348 | + " txt('resNote',ok?'':'The resolver returned no record for this name.');\n" | ||
| 349 | + " pushHist({kind:'dns',label:target,ok:ok,detail:(d.count||0)+' addr',at:clock()});\n" | ||
| 350 | + "}\n" | ||
| 351 | + "\n" | ||
| 352 | + "function showTcp(d,target){\n" | ||
| 353 | + " var open=d.open===true;\n" | ||
| 354 | + " var last=(d.samples&&d.samples.length)?d.samples[d.samples.length-1]:null;\n" | ||
| 355 | + " TCPMS.push(typeof last==='number'?last:-1);\n" | ||
| 356 | + " if(TCPMS.length>20)TCPMS.shift();\n" | ||
| 357 | + " txt('resState',open?'open':(d.status==='timeout'?'timeout':'closed'));\n" | ||
| 358 | + " $('resTag').innerHTML=open?'<span class=\"tag ok\">reachable</span>'\n" | ||
| 359 | + " :'<span class=\"tag bad\">'+esc(d.status||'closed')+'</span>';\n" | ||
| 360 | + " var pairs=[['target',d.host+':'+d.port],['resolved to',d.address],\n" | ||
| 361 | + " ['avg',(d.avg_ms==null?'-':d.avg_ms+' ms')],\n" | ||
| 362 | + " ['min',(d.min_ms==null?'-':d.min_ms+' ms')],\n" | ||
| 363 | + " ['max',(d.max_ms==null?'-':d.max_ms+' ms')],\n" | ||
| 364 | + " ['samples',(d.samples||[]).map(function(s){return s==null?'timeout':s+' ms';}).join(', ')]];\n" | ||
| 365 | + " kv(pairs);\n" | ||
| 366 | + " txt('resNote',open?'Three connects succeeded against the first resolved address.'\n" | ||
| 367 | + " :'The connect did not complete inside the deadline.');\n" | ||
| 368 | + " drawSpark();\n" | ||
| 369 | + " pushHist({kind:'tcp',label:d.host+':'+d.port,ok:open,\n" | ||
| 370 | + " detail:open?((d.avg_ms==null?'-':d.avg_ms+' ms avg')):d.status,at:clock()});\n" | ||
| 371 | + "}\n" | ||
| 372 | + "\n" | ||
| 373 | + "function showHttp(d,target){\n" | ||
| 374 | + " var ok=d.reachable===true&&d.status!=null&&d.status<400;\n" | ||
| 375 | + " txt('resState',d.status==null?(d.reachable?'connected':'unreachable'):('HTTP '+d.status));\n" | ||
| 376 | + " $('resTag').innerHTML=d.status==null\n" | ||
| 377 | + " ?(d.reachable?'<span class=\"tag warn\">no status line</span>':'<span class=\"tag bad\">unreachable</span>')\n" | ||
| 378 | + " :(ok?'<span class=\"tag ok\">reachable</span>':'<span class=\"tag bad\">status '+esc(d.status)+'</span>');\n" | ||
| 379 | + " var pairs=[['url',d.url],['host',d.host+':'+d.port],['path',d.path],\n" | ||
| 380 | + " ['connect',(d.connect_ms==null?'-':d.connect_ms+' ms')],\n" | ||
| 381 | + " ['status',(d.status==null?'-':d.status+' '+(d.status_text||''))],\n" | ||
| 382 | + " ['headers',d.header_lines],['body','0 bytes (HEAD)'],\n" | ||
| 383 | + " ['tls',d.tls]];\n" | ||
| 384 | + " kv(pairs);\n" | ||
| 385 | + " txt('resNote',d.note||'');\n" | ||
| 386 | + " pushHist({kind:'http',label:d.url,ok:ok,detail:(d.status==null?'no status':String(d.status)),at:clock()});\n" | ||
| 387 | + "}\n" | ||
| 388 | + "\n" | ||
| 389 | + "function clock(){\n" | ||
| 390 | + " var d=new Date();\n" | ||
| 391 | + " return d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit',second:'2-digit'});\n" | ||
| 392 | + "}\n" | ||
| 393 | + "\n" | ||
| 394 | + "function run(){\n" | ||
| 395 | + " var v=$('inp').value.trim();\n" | ||
| 396 | + " if(!v){txt('resState','enter a target');return;}\n" | ||
| 397 | + " txt('resState','running...');\n" | ||
| 398 | + " $('resKv').innerHTML='';\n" | ||
| 399 | + " $('resNote').textContent='';\n" | ||
| 400 | + " $('goBtn').disabled=true;\n" | ||
| 401 | + " var p='';\n" | ||
| 402 | + " var call;\n" | ||
| 403 | + " if(TAB==='dns'){call=api('dns','&host='+encodeURIComponent(v));}\n" | ||
| 404 | + " else if(TAB==='tcp'){\n" | ||
| 405 | + " var pt=$('port').value.trim();\n" | ||
| 406 | + " if(!pt){$('goBtn').disabled=false;txt('resState','port required');return;}\n" | ||
| 407 | + " call=api('tcp','&host='+encodeURIComponent(v)+'&port='+encodeURIComponent(pt));\n" | ||
| 408 | + " } else {\n" | ||
| 409 | + " var uv=v;\n" | ||
| 410 | + " if(!/^https?:\\/\\//i.test(uv))uv='http://'+uv;\n" | ||
| 411 | + " call=api('http','&url='+encodeURIComponent(uv));\n" | ||
| 412 | + " }\n" | ||
| 413 | + " call.then(function(d){\n" | ||
| 414 | + " $('goBtn').disabled=false;\n" | ||
| 415 | + " if(!d||d.ok!==true){\n" | ||
| 416 | + " txt('resState','error');\n" | ||
| 417 | + " kv([['error',(d&&d.error)||'request failed']]);\n" | ||
| 418 | + " pushHist({kind:TAB,label:v,ok:false,detail:(d&&d.error)||'error',at:clock()});\n" | ||
| 419 | + " return;\n" | ||
| 420 | + " }\n" | ||
| 421 | + " if(TAB==='dns')showDns(d,v);\n" | ||
| 422 | + " else if(TAB==='tcp')showTcp(d,v);\n" | ||
| 423 | + " else showHttp(d,v);\n" | ||
| 424 | + " }).catch(function(e){\n" | ||
| 425 | + " $('goBtn').disabled=false;\n" | ||
| 426 | + " txt('resState','error');\n" | ||
| 427 | + " kv([['error',String(e.message||e)]]);\n" | ||
| 428 | + " pushHist({kind:TAB,label:v,ok:false,detail:String(e.message||e),at:clock()});\n" | ||
| 429 | + " });\n" | ||
| 430 | + "}\n" | ||
| 431 | + "\n" | ||
| 432 | + "/* ---------- theme toggle (standalone only) ---------- */\n" | ||
| 433 | + "function toggleTheme(){\n" | ||
| 434 | + " var cur=(document.documentElement.getAttribute('data-theme')||'dark')==='light'?'dark':'light';\n" | ||
| 435 | + " document.documentElement.setAttribute('data-theme',cur);\n" | ||
| 436 | + " try{localStorage.setItem('bot_theme',cur);}catch(e){}\n" | ||
| 437 | + " try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:cur}));}catch(e){}\n" | ||
| 438 | + "}\n" | ||
| 439 | + "\n" | ||
| 440 | + "$('goBtn').addEventListener('click',run);\n" | ||
| 441 | + "$('inp').addEventListener('keydown',function(e){if(e.key==='Enter'){e.preventDefault();run();}});\n" | ||
| 442 | + "$('rfBtn').addEventListener('click',loadIfaces);\n" | ||
| 443 | + "$('thBtn').addEventListener('click',toggleTheme);\n" | ||
| 444 | + "$('tabDns').addEventListener('click',function(){setTab('dns');});\n" | ||
| 445 | + "$('tabTcp').addEventListener('click',function(){setTab('tcp');});\n" | ||
| 446 | + "$('tabHttp').addEventListener('click',function(){setTab('http');});\n" | ||
| 447 | + "\n" | ||
| 448 | + "setTab('dns');\n" | ||
| 449 | + "loadIfaces();\n" | ||
| 450 | + "})();\n" | ||
| 451 | + "</script>\002</body></html>\n" | ||
| 452 | + ; | ||
| 453 | + | ||
| 454 | +#endif /* SX_NETCHECK_UI_HTML_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3e14562 | index 0000000..3e14562 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,320 @@ | @@ -0,0 +1,320 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport checks for the plugin_netcheck panel. | ||
| 3 | + | ||
| 4 | +Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts | ||
| 5 | +the throwaway TCP/HTTP listeners from tests/mockd.py so the panel has something | ||
| 6 | +real to talk to, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in | ||
| 7 | +both themes, and asserts: | ||
| 8 | + | ||
| 9 | + * no console error and no page error at any viewport | ||
| 10 | + * scrollWidth <= innerWidth (no horizontal overflow) | ||
| 11 | + * the interface table renders from the fixture and the DNS row appears | ||
| 12 | + * a DNS / TCP / HTTP check each produce a result and land in the history | ||
| 13 | + * the TCP sparkline appears once there are two or more samples | ||
| 14 | + * screenshots land in docs/ for the README | ||
| 15 | + | ||
| 16 | +Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays | ||
| 17 | +dependency-free. | ||
| 18 | + | ||
| 19 | + python3 tests/e2e.py # run if Playwright is available | ||
| 20 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 21 | +""" | ||
| 22 | + | ||
| 23 | +import argparse | ||
| 24 | +import http.server | ||
| 25 | +import os | ||
| 26 | +import socketserver | ||
| 27 | +import subprocess | ||
| 28 | +import sys | ||
| 29 | +import threading | ||
| 30 | +import time | ||
| 31 | +from urllib.parse import urlparse | ||
| 32 | + | ||
| 33 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 34 | +BIN = os.path.join(ROOT, "plugin_netcheck") | ||
| 35 | +DOCS = os.path.join(ROOT, "docs") | ||
| 36 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 37 | +THEMES = ["dark", "light"] | ||
| 38 | + | ||
| 39 | +IF_FIX = ("lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1," | ||
| 40 | + "lo|::1|||6|1," | ||
| 41 | + "tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1," | ||
| 42 | + "wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0") | ||
| 43 | +DNS_FIX = "example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1" | ||
| 44 | + | ||
| 45 | +MOCK_BASE = 18090 | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 49 | + def _run(self, method): | ||
| 50 | + u = urlparse(self.path) | ||
| 51 | + length = int(self.headers.get("Content-Length") or 0) | ||
| 52 | + body = self.rfile.read(length) if length else b"" | ||
| 53 | + env = dict(os.environ) | ||
| 54 | + env["QUERY_STRING"] = u.query | ||
| 55 | + env["REQUEST_METHOD"] = method | ||
| 56 | + env["NETCHECK_MOCK_IFACES"] = IF_FIX | ||
| 57 | + env["NETCHECK_MOCK_DNS"] = DNS_FIX | ||
| 58 | + env.pop("BOT_PASSWORD", None) | ||
| 59 | + env["CONTENT_LENGTH"] = str(len(body)) | ||
| 60 | + out = subprocess.run( | ||
| 61 | + [BIN], input=body, capture_output=True, env=env, timeout=60 | ||
| 62 | + ).stdout | ||
| 63 | + sep = out.find(b"\r\n\r\n") | ||
| 64 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 65 | + payload = out[sep + 4:] if sep >= 0 else out | ||
| 66 | + status = 200 | ||
| 67 | + ctype = "application/json; charset=utf-8" | ||
| 68 | + for line in headers.splitlines(): | ||
| 69 | + low = line.lower() | ||
| 70 | + if low.startswith("content-type:"): | ||
| 71 | + ctype = line.split(":", 1)[1].strip() | ||
| 72 | + elif low.startswith("status:"): | ||
| 73 | + try: | ||
| 74 | + status = int(line.split(":", 1)[1].strip().split()[0]) | ||
| 75 | + except (IndexError, ValueError): | ||
| 76 | + status = 200 | ||
| 77 | + self.send_response(status) | ||
| 78 | + self.send_header("Content-Type", ctype) | ||
| 79 | + self.send_header("Cache-Control", "no-store") | ||
| 80 | + self.send_header("Content-Length", str(len(payload))) | ||
| 81 | + self.end_headers() | ||
| 82 | + self.wfile.write(payload) | ||
| 83 | + | ||
| 84 | + def do_GET(self): # noqa: N802 | ||
| 85 | + self._run("GET") | ||
| 86 | + | ||
| 87 | + def do_POST(self): # noqa: N802 | ||
| 88 | + self._run("POST") | ||
| 89 | + | ||
| 90 | + def log_message(self, *_a): | ||
| 91 | + pass | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def main(): | ||
| 95 | + ap = argparse.ArgumentParser() | ||
| 96 | + ap.add_argument("--strict", action="store_true") | ||
| 97 | + args = ap.parse_args() | ||
| 98 | + | ||
| 99 | + if not os.path.exists(BIN): | ||
| 100 | + print("plugin_netcheck is not built; run make first", file=sys.stderr) | ||
| 101 | + return 1 | ||
| 102 | + | ||
| 103 | + try: | ||
| 104 | + from playwright.sync_api import sync_playwright | ||
| 105 | + except Exception: | ||
| 106 | + if args.strict: | ||
| 107 | + print("playwright is not installed", file=sys.stderr) | ||
| 108 | + return 2 | ||
| 109 | + print("playwright not available - skipping e2e (offline suite still runs)") | ||
| 110 | + return 0 | ||
| 111 | + | ||
| 112 | + os.makedirs(DOCS, exist_ok=True) | ||
| 113 | + | ||
| 114 | + # the listeners the panel will probe | ||
| 115 | + mock = subprocess.Popen( | ||
| 116 | + [sys.executable, os.path.join(ROOT, "tests", "mockd.py"), str(MOCK_BASE)], | ||
| 117 | + stdout=subprocess.PIPE, stderr=subprocess.PIPE, | ||
| 118 | + ) | ||
| 119 | + ready = False | ||
| 120 | + for _ in range(60): | ||
| 121 | + line = mock.stdout.readline() | ||
| 122 | + if b"READY" in line: | ||
| 123 | + ready = True | ||
| 124 | + break | ||
| 125 | + time.sleep(0.05) | ||
| 126 | + if not ready: | ||
| 127 | + print("mock listeners never came up", file=sys.stderr) | ||
| 128 | + mock.kill() | ||
| 129 | + return 1 | ||
| 130 | + | ||
| 131 | + open_port = MOCK_BASE + 1 | ||
| 132 | + | ||
| 133 | + socketserver.TCPServer.allow_reuse_address = True | ||
| 134 | + try: | ||
| 135 | + httpd = socketserver.TCPServer(("127.0.0.1", 8099), Handler) | ||
| 136 | + except OSError as exc: | ||
| 137 | + print("could not bind 8099: %s" % exc, file=sys.stderr) | ||
| 138 | + mock.kill() | ||
| 139 | + return 1 | ||
| 140 | + th = threading.Thread(target=httpd.serve_forever, daemon=True) | ||
| 141 | + th.start() | ||
| 142 | + | ||
| 143 | + base = "http://127.0.0.1:8099/" | ||
| 144 | + errors = [] | ||
| 145 | + shots = 0 | ||
| 146 | + | ||
| 147 | + with sync_playwright() as p: | ||
| 148 | + browser = p.chromium.launch() | ||
| 149 | + for w, h in VIEWPORTS: | ||
| 150 | + for theme in THEMES: | ||
| 151 | + page = browser.new_page(viewport={"width": w, "height": h}) | ||
| 152 | + console = [] | ||
| 153 | + page.on("console", lambda m: console.append(m.type + ": " + m.text) | ||
| 154 | + if m.type in ("error",) else None) | ||
| 155 | + page.on("pageerror", lambda e: console.append("pageerror: %s" % e)) | ||
| 156 | + page.goto(base + "?theme=" + theme, wait_until="networkidle") | ||
| 157 | + page.wait_for_selector("#ifrows tr", timeout=15000) | ||
| 158 | + | ||
| 159 | + # the fixture must render four interface rows and one nameserver | ||
| 160 | + rows = page.eval_on_selector_all("#ifrows tr", "els => els.length") | ||
| 161 | + if rows != 4: | ||
| 162 | + errors.append("%dx%d %s: expected 4 iface rows, got %s" | ||
| 163 | + % (w, h, theme, rows)) | ||
| 164 | + ns = page.eval_on_selector_all("#nsList .tag", "els => els.length") | ||
| 165 | + if ns < 1: | ||
| 166 | + errors.append("%dx%d %s: no nameserver chips" % (w, h, theme)) | ||
| 167 | + | ||
| 168 | + # --- DNS tab --- | ||
| 169 | + page.fill("#inp", "example.com") | ||
| 170 | + page.click("#goBtn") | ||
| 171 | + page.wait_for_selector("#resKv .v", timeout=15000) | ||
| 172 | + state = page.text_content("#resState") or "" | ||
| 173 | + if "resolved" not in state: | ||
| 174 | + errors.append("%dx%d %s: dns did not resolve (%s)" | ||
| 175 | + % (w, h, theme, state.strip())) | ||
| 176 | + | ||
| 177 | + # --- TCP tab, three times so the sparkline has samples --- | ||
| 178 | + page.click("#tabTcp") | ||
| 179 | + page.fill("#inp", "target") | ||
| 180 | + page.fill("#port", str(open_port)) | ||
| 181 | + for _ in range(3): | ||
| 182 | + page.click("#goBtn") | ||
| 183 | + page.wait_for_selector("#resKv .v", timeout=15000) | ||
| 184 | + disp = page.evaluate( | ||
| 185 | + "() => getComputedStyle(document.getElementById('spark')).display") | ||
| 186 | + if disp == "none": | ||
| 187 | + errors.append("%dx%d %s: sparkline stayed hidden after 3 samples" | ||
| 188 | + % (w, h, theme)) | ||
| 189 | + dots = page.eval_on_selector_all("#spark circle", "els => els.length") | ||
| 190 | + if dots < 2: | ||
| 191 | + errors.append("%dx%d %s: sparkline has %s points" % (w, h, theme, dots)) | ||
| 192 | + hist = page.eval_on_selector_all("#hist li", "els => els.length") | ||
| 193 | + if hist < 4: | ||
| 194 | + errors.append("%dx%d %s: history has %s entries, want >=4" | ||
| 195 | + % (w, h, theme, hist)) | ||
| 196 | + | ||
| 197 | + # --- HTTP tab --- | ||
| 198 | + page.click("#tabHttp") | ||
| 199 | + page.fill("#inp", "http://target:%d/index.html" % open_port) | ||
| 200 | + page.click("#goBtn") | ||
| 201 | + page.wait_for_selector("#resKv .v", timeout=15000) | ||
| 202 | + state = (page.text_content("#resState") or "").strip() | ||
| 203 | + if "200" not in state: | ||
| 204 | + errors.append("%dx%d %s: http did not report 200 (%s)" | ||
| 205 | + % (w, h, theme, state)) | ||
| 206 | + | ||
| 207 | + # land on the TCP tab so the screenshot shows the sparkline with | ||
| 208 | + # samples in it - a chart nobody can see proves nothing. One of | ||
| 209 | + # the samples is taken against a closed port so the series is not | ||
| 210 | + # perfectly flat: a flat line on a chart is ambiguous, and a | ||
| 211 | + # screenshot that cannot be read is not evidence. | ||
| 212 | + page.click("#tabTcp") | ||
| 213 | + page.fill("#inp", "127.0.0.1") | ||
| 214 | + page.fill("#port", "1") | ||
| 215 | + page.click("#goBtn") | ||
| 216 | + page.wait_for_selector("#resKv .v", timeout=15000) | ||
| 217 | + page.fill("#inp", "target") | ||
| 218 | + page.fill("#port", str(open_port)) | ||
| 219 | + page.click("#goBtn") | ||
| 220 | + page.wait_for_selector("#resKv .v", timeout=15000) | ||
| 221 | + spark_disp = page.evaluate( | ||
| 222 | + "() => getComputedStyle(document.getElementById('spark')).display") | ||
| 223 | + if spark_disp == "none": | ||
| 224 | + errors.append("%dx%d %s: sparkline hidden on the tcp tab" | ||
| 225 | + % (w, h, theme)) | ||
| 226 | + svg_h = page.evaluate( | ||
| 227 | + "() => document.getElementById('spark').getBoundingClientRect().height") | ||
| 228 | + if svg_h < 20: | ||
| 229 | + errors.append("%dx%d %s: sparkline renders only %s px tall" | ||
| 230 | + % (w, h, theme, svg_h)) | ||
| 231 | + | ||
| 232 | + # --- layout: no horizontal overflow anywhere --- | ||
| 233 | + overflow = page.evaluate( | ||
| 234 | + "() => document.documentElement.scrollWidth - window.innerWidth") | ||
| 235 | + if overflow > 0: | ||
| 236 | + errors.append("%dx%d %s: horizontal overflow %spx" | ||
| 237 | + % (w, h, theme, overflow)) | ||
| 238 | + body_over = page.evaluate( | ||
| 239 | + "() => document.body.scrollWidth - window.innerWidth") | ||
| 240 | + if body_over > 0: | ||
| 241 | + errors.append("%dx%d %s: body overflow %spx" | ||
| 242 | + % (w, h, theme, body_over)) | ||
| 243 | + | ||
| 244 | + # the theme really applied | ||
| 245 | + applied = page.evaluate( | ||
| 246 | + "() => document.documentElement.getAttribute('data-theme')") | ||
| 247 | + if applied != theme: | ||
| 248 | + errors.append("%dx%d %s: data-theme is %s" % (w, h, theme, applied)) | ||
| 249 | + bg = page.evaluate( | ||
| 250 | + "() => getComputedStyle(document.body).backgroundColor") | ||
| 251 | + if theme == "dark" and bg not in ("rgb(0, 0, 0)", "rgba(0, 0, 0, 1)"): | ||
| 252 | + errors.append("%dx%d %s: dark body background is %s" | ||
| 253 | + % (w, h, theme, bg)) | ||
| 254 | + if theme == "light" and bg not in ("rgb(245, 245, 247)", | ||
| 255 | + "rgba(245, 245, 247, 1)"): | ||
| 256 | + errors.append("%dx%d %s: light body background is %s" | ||
| 257 | + % (w, h, theme, bg)) | ||
| 258 | + | ||
| 259 | + if console: | ||
| 260 | + errors.append("%dx%d %s: console %s" | ||
| 261 | + % (w, h, theme, "; ".join(console[:4]))) | ||
| 262 | + | ||
| 263 | + # bring the sparkline into the frame before shooting | ||
| 264 | + page.evaluate( | ||
| 265 | + "() => document.getElementById('spark')" | ||
| 266 | + ".scrollIntoView({block:'center'})") | ||
| 267 | + page.wait_for_timeout(120) | ||
| 268 | + | ||
| 269 | + tag = "%d" % w | ||
| 270 | + path = os.path.join(DOCS, "ui-%s-%s.png" % (tag, theme)) | ||
| 271 | + page.screenshot(path=path, full_page=False) | ||
| 272 | + shots += 1 | ||
| 273 | + page.close() | ||
| 274 | + | ||
| 275 | + # embed mode hides the bot-owned chrome | ||
| 276 | + page = browser.new_page(viewport={"width": 390, "height": 500}) | ||
| 277 | + page.goto(base + "?embed=1&theme=dark", wait_until="networkidle") | ||
| 278 | + page.wait_for_selector("#ifrows tr", timeout=15000) | ||
| 279 | + vis = page.evaluate( | ||
| 280 | + "() => document.getElementById('thBtn').offsetWidth") | ||
| 281 | + if vis: | ||
| 282 | + errors.append("embed: the theme toggle is still visible (%spx)" % vis) | ||
| 283 | + vis2 = page.evaluate( | ||
| 284 | + "() => document.querySelector('.embed-hide') !== null && " | ||
| 285 | + "getComputedStyle(document.querySelector('.embed-hide')).display") | ||
| 286 | + if vis2 != "none": | ||
| 287 | + errors.append("embed: back link not hidden (%s)" % vis2) | ||
| 288 | + page.screenshot(path=os.path.join(DOCS, "ui-390-embed-dark.png")) | ||
| 289 | + shots += 1 | ||
| 290 | + page.close() | ||
| 291 | + | ||
| 292 | + # a short floating window: the panel must not overflow vertically either | ||
| 293 | + page = browser.new_page(viewport={"width": 420, "height": 320}) | ||
| 294 | + page.goto(base + "?embed=1&theme=light", wait_until="networkidle") | ||
| 295 | + page.wait_for_selector("#ifrows tr", timeout=15000) | ||
| 296 | + ov = page.evaluate( | ||
| 297 | + "() => document.documentElement.scrollWidth - window.innerWidth") | ||
| 298 | + if ov > 0: | ||
| 299 | + errors.append("floating window: horizontal overflow %spx" % ov) | ||
| 300 | + shots += 1 | ||
| 301 | + page.close() | ||
| 302 | + | ||
| 303 | + browser.close() | ||
| 304 | + | ||
| 305 | + httpd.shutdown() | ||
| 306 | + mock.kill() | ||
| 307 | + | ||
| 308 | + print("screenshots written: %d -> %s" % (shots, DOCS)) | ||
| 309 | + if errors: | ||
| 310 | + for e in errors[:20]: | ||
| 311 | + print("FAIL: %s" % e) | ||
| 312 | + print("e2e FAILED (%d problems)" % len(errors)) | ||
| 313 | + return 1 | ||
| 314 | + print("e2e OK - %d viewports x 2 themes, no console errors, no overflow" | ||
| 315 | + % len(VIEWPORTS)) | ||
| 316 | + return 0 | ||
| 317 | + | ||
| 318 | + | ||
| 319 | +if __name__ == "__main__": | ||
| 320 | + sys.exit(main()) |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..3a2c1e5 | index 0000000..3a2c1e5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/mockd.py | +++ b/tests/mockd.py | ||
| @@ -0,0 +1,90 @@ | @@ -0,0 +1,90 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/mockd.py - throwaway TCP/HTTP listeners for the offline suite. | ||
| 3 | + | ||
| 4 | +Starts four listeners on 127.0.0.1 and keeps them open until killed: | ||
| 5 | + | ||
| 6 | + port+0 plain TCP accept-and-close (a port that is open, no protocol) | ||
| 7 | + port+1 HTTP 200 responder (status line + headers + a 5-byte body) | ||
| 8 | + port+2 HTTP 404 responder | ||
| 9 | + port+3 HTTP 301 responder (Location header, so the plugin must | ||
| 10 | + report redirect:not_followed) | ||
| 11 | + port+4 accept but never answer (exercises the read deadline) | ||
| 12 | + | ||
| 13 | +Usage: python3 tests/mockd.py <base-port> | ||
| 14 | +Prints "READY" on stdout once every socket is listening, then idles. | ||
| 15 | + | ||
| 16 | +MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import socket | ||
| 21 | +import sys | ||
| 22 | +import threading | ||
| 23 | + | ||
| 24 | +BODY = b"hello" | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def responder(status, extra_headers=()): | ||
| 28 | + head = ("HTTP/1.1 %s\r\n" % status).encode() | ||
| 29 | + head += b"Content-Type: text/html\r\n" | ||
| 30 | + head += b"Content-Length: %d\r\n" % len(BODY) | ||
| 31 | + for h in extra_headers: | ||
| 32 | + head += h.encode() | ||
| 33 | + head += b"\r\n" | ||
| 34 | + return head + BODY | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def serve(port, payload): | ||
| 38 | + """Accept connections and send payload (or nothing at all if payload is None).""" | ||
| 39 | + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| 40 | + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| 41 | + srv.bind(("127.0.0.1", port)) | ||
| 42 | + srv.listen(8) | ||
| 43 | + while True: | ||
| 44 | + try: | ||
| 45 | + conn, _ = srv.accept() | ||
| 46 | + except Exception: | ||
| 47 | + break | ||
| 48 | + try: | ||
| 49 | + conn.settimeout(3.0) | ||
| 50 | + if payload is not None: | ||
| 51 | + try: | ||
| 52 | + conn.recv(4096) | ||
| 53 | + except Exception: | ||
| 54 | + pass | ||
| 55 | + conn.sendall(payload) | ||
| 56 | + # the silent listener deliberately sends nothing back | ||
| 57 | + finally: | ||
| 58 | + try: | ||
| 59 | + conn.close() | ||
| 60 | + except Exception: | ||
| 61 | + pass | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def main(): | ||
| 65 | + if len(sys.argv) < 2: | ||
| 66 | + print("usage: mockd.py <base-port>", file=sys.stderr) | ||
| 67 | + return 2 | ||
| 68 | + base = int(sys.argv[1]) | ||
| 69 | + specs = [ | ||
| 70 | + (base + 0, None), | ||
| 71 | + (base + 1, responder("200 OK")), | ||
| 72 | + (base + 2, responder("404 Not Found")), | ||
| 73 | + (base + 3, responder("301 Moved Permanently", | ||
| 74 | + ["Location: /moved\r\n"])), | ||
| 75 | + (base + 4, None), # silent: never answers | ||
| 76 | + ] | ||
| 77 | + threads = [] | ||
| 78 | + for port, payload in specs: | ||
| 79 | + t = threading.Thread(target=serve, args=(port, payload), daemon=True) | ||
| 80 | + t.start() | ||
| 81 | + threads.append(t) | ||
| 82 | + sys.stdout.write("READY %d\n" % base) | ||
| 83 | + sys.stdout.flush() | ||
| 84 | + # keep the parent alive so the daemon threads keep serving | ||
| 85 | + threading.Event().wait() | ||
| 86 | + return 0 | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +if __name__ == "__main__": | ||
| 90 | + sys.exit(main()) |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..e05f07f | index 0000000..e05f07f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,545 @@ | @@ -0,0 +1,545 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_netcheck across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Everything runs against ./plugin_netcheck with no network required: the | ||
| 5 | +# resolver, the interface table and the outbound connect are replaced by the | ||
| 6 | +# three environment hooks the plugin exposes for exactly this purpose | ||
| 7 | +# (NETCHECK_MOCK_IFACES, NETCHECK_MOCK_DNS, NETCHECK_MOCK_TIMEOUT), and the | ||
| 8 | +# TCP/HTTP legs talk to throwaway listeners started by tests/mockd.py on | ||
| 9 | +# 127.0.0.1. It proves: --meta, node auth on every action, each action's JSON | ||
| 10 | +# shape, host/port/url validation, the timeout path, redirect handling, the | ||
| 11 | +# no-TLS contract, the generated page (no CDN, no <script src=>, no emoji), | ||
| 12 | +# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that runs clean, | ||
| 13 | +# and a full git-history secret audit. | ||
| 14 | +# | ||
| 15 | +# Exit code 0 = everything passed. | ||
| 16 | + | ||
| 17 | +set -u | ||
| 18 | + | ||
| 19 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 20 | +cd "$ROOT" || exit 1 | ||
| 21 | + | ||
| 22 | +BIN=./plugin_netcheck | ||
| 23 | +PASS=0 | ||
| 24 | +FAIL=0 | ||
| 25 | + | ||
| 26 | +if [ -t 1 ]; then | ||
| 27 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 28 | +else | ||
| 29 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 30 | +fi | ||
| 31 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 32 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 33 | + | ||
| 34 | +check() { # check <desc> <expected-substring> <actual> | ||
| 35 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 36 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 37 | + fi | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 41 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 42 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 43 | + fi | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 47 | + | ||
| 48 | +# strip CGI headers if present, drop CRs, keep the payload | ||
| 49 | +body() { | ||
| 50 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 51 | + BEGIN { inhdr = 0 } | ||
| 52 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next } | ||
| 53 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 54 | + inhdr { next } | ||
| 55 | + { print } | ||
| 56 | + ' | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 60 | + expr=${3:-True} | ||
| 61 | + 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 | ||
| 62 | + pass "$1" | ||
| 63 | + else | ||
| 64 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 65 | + fi | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +# api <query-string> [extra-env-assignments...] | ||
| 69 | +api() { | ||
| 70 | + _qs="$1"; shift | ||
| 71 | + body "$(env "$@" QUERY_STRING="$_qs" $BIN)" | ||
| 72 | +} | ||
| 73 | +apiraw() { | ||
| 74 | + _qs="$1"; shift | ||
| 75 | + env "$@" QUERY_STRING="$_qs" $BIN | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +# ---------------------------------------------------------------- fixtures | ||
| 79 | +WORK=$(mktemp -d) | ||
| 80 | +trap 'rm -rf "$WORK"; kill "$MOCK_PID" 2>/dev/null; wait "$MOCK_PID" 2>/dev/null' EXIT | ||
| 81 | + | ||
| 82 | +# TEST-NET ranges (RFC 5737) are used for every synthetic address so the suite | ||
| 83 | +# never contains a private-range literal. | ||
| 84 | +IF_FIX='lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,lo|::1|||6|1,tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1,wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0' | ||
| 85 | +DNS_FIX='example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1;two=198.51.100.9,198.51.100.10' | ||
| 86 | + | ||
| 87 | +BASE=18080 | ||
| 88 | +python3 tests/mockd.py "$BASE" > "$WORK/mockd.out" 2>"$WORK/mockd.err" & | ||
| 89 | +MOCK_PID=$! | ||
| 90 | +i=0 | ||
| 91 | +while [ "$i" -lt 40 ]; do | ||
| 92 | + grep -q READY "$WORK/mockd.out" 2>/dev/null && break | ||
| 93 | + i=$((i + 1)); sleep 0.05 | ||
| 94 | +done | ||
| 95 | +if grep -q READY "$WORK/mockd.out" 2>/dev/null; then | ||
| 96 | + pass "mock listeners are up on 127.0.0.1:$BASE..$((BASE + 4))" | ||
| 97 | +else | ||
| 98 | + fail "mock listeners never came up" | ||
| 99 | + cat "$WORK/mockd.err" | sed 's/^/ /' | head -5 | ||
| 100 | +fi | ||
| 101 | +OPEN_PORT=$((BASE + 1)) | ||
| 102 | +N404_PORT=$((BASE + 2)) | ||
| 103 | +N301_PORT=$((BASE + 3)) | ||
| 104 | +SILENT_PORT=$((BASE + 4)) | ||
| 105 | +TCPFIX="target=127.0.0.1" | ||
| 106 | + | ||
| 107 | +# ---------------------------------------------------------------- build | ||
| 108 | +section "build" | ||
| 109 | +if [ ! -x "$BIN" ]; then | ||
| 110 | + echo " building native binary..." | ||
| 111 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_netcheck.c -lpthread 2>"$WORK/build.err" | ||
| 112 | + if [ -x "$BIN" ]; then pass "native build ok"; else | ||
| 113 | + fail "native build failed"; sed 's/^/ /' "$WORK/build.err" | head -10 | ||
| 114 | + fi | ||
| 115 | +else | ||
| 116 | + pass "native binary present" | ||
| 117 | +fi | ||
| 118 | +check "Makefile has a musl target" 'musl:' "$(cat Makefile)" | ||
| 119 | +check "Makefile has a win64 target" 'win64:' "$(cat Makefile)" | ||
| 120 | +check "Makefile has a test target" 'test:' "$(cat Makefile)" | ||
| 121 | +check "Makefile has a clean target" 'clean:' "$(cat Makefile)" | ||
| 122 | +check "Makefile links pthread for the resolver deadline" 'PTHREAD' "$(cat Makefile)" | ||
| 123 | +check "Makefile links the Win32 libs on win64" 'liphlpapi' "$(cat Makefile)" | ||
| 124 | + | ||
| 125 | +# ---------------------------------------------------------------- mode 1: meta | ||
| 126 | +section "mode 1 - discovery metadata" | ||
| 127 | +M=$($BIN --meta) | ||
| 128 | +json_ok "--meta prints valid JSON" "$M" "d['name']=='netcheck' and d['desc']=='Net checks'" | ||
| 129 | +check "--meta name is one word" '"name":"netcheck"' "$M" | ||
| 130 | +check "--meta desc is 11 chars" '"desc":"Net checks"' "$M" | ||
| 131 | +M2=$(SX_PLUGIN_META=1 $BIN) | ||
| 132 | +check "SX_PLUGIN_META=1 answers the same" '"name":"netcheck"' "$M2" | ||
| 133 | +check_not "--meta needs no password" '401' "$M2" | ||
| 134 | + | ||
| 135 | +# ---------------------------------------------------------------- mode 2: auth | ||
| 136 | +section "mode 2a - node auth on every action" | ||
| 137 | +PW=testpw | ||
| 138 | +for a in ifaces info; do | ||
| 139 | + check "unauth $a is 401" 'Status: 401' "$(apiraw "action=$a" BOT_PASSWORD=$PW)" | ||
| 140 | +done | ||
| 141 | +check "unauth dns is 401" 'Status: 401' "$(apiraw "action=dns&host=example.com" BOT_PASSWORD=$PW)" | ||
| 142 | +check "unauth tcp is 401" 'Status: 401' "$(apiraw "action=tcp&host=example.com&port=80" BOT_PASSWORD=$PW)" | ||
| 143 | +check "unauth http is 401" 'Status: 401' "$(apiraw "action=http&url=http://example.com/" BOT_PASSWORD=$PW)" | ||
| 144 | +check "unauth bare html is 401" 'Status: 401' "$(apiraw "" BOT_PASSWORD=$PW)" | ||
| 145 | +check "the 401 body names the error" '"error":"invalid node password"' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)" | ||
| 146 | +check "the 401 says json" 'Content-Type: application/json' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)" | ||
| 147 | +AUTHV="Bearer $PW" | ||
| 148 | +HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW QUERY_STRING='action=info' $BIN) | ||
| 149 | +check "header auth is accepted" '"ok":true' "$(body "$HA")" | ||
| 150 | +BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="$AUTHV" QUERY_STRING='action=info' $BIN) | ||
| 151 | +check "bearer auth is accepted" '"ok":true' "$(body "$BA")" | ||
| 152 | +QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=info&pwd=testpw' $BIN) | ||
| 153 | +check "query pwd auth is accepted" '"ok":true' "$(body "$QA")" | ||
| 154 | +check "a wrong pwd is still 401" 'Status: 401' "$(apiraw "action=info&pwd=nope" BOT_PASSWORD=$PW)" | ||
| 155 | +check "no password set means open" '"ok":true' "$(api "action=info")" | ||
| 156 | +check "--meta stays open with a password set" '"name":"netcheck"' "$(BOT_PASSWORD=$PW $BIN --meta)" | ||
| 157 | + | ||
| 158 | +# ---------------------------------------------------------------- mode 2b: ifaces | ||
| 159 | +section "mode 2b - action=ifaces" | ||
| 160 | +IF=$(api "action=ifaces" NETCHECK_MOCK_IFACES="$IF_FIX") | ||
| 161 | +json_ok "ifaces answers ok" "$IF" "d['ok'] is True and d['action']=='ifaces'" | ||
| 162 | +json_ok "the fixture yields four rows" "$IF" "d['count']==4 and len(d['interfaces'])==4" | ||
| 163 | +json_ok "loopback is flagged on 127.0.0.1" "$IF" "d['interfaces'][0]['loopback'] is True" | ||
| 164 | +json_ok "the loopback row is up" "$IF" "d['interfaces'][0]['up'] is True and d['interfaces'][0]['running'] is True" | ||
| 165 | +json_ok "an ipv6 row is present" "$IF" "any(i['family']==6 and i['address']=='::1' for i in d['interfaces'])" | ||
| 166 | +json_ok "the ipv6 row has no netmask" "$IF" "[i for i in d['interfaces'] if i['address']=='::1'][0]['netmask'] is None" | ||
| 167 | +json_ok "a netmask is reported for the ipv4 row" "$IF" "d['interfaces'][0]['netmask']=='255.0.0.0'" | ||
| 168 | +json_ok "a broadcast is reported" "$IF" "d['interfaces'][2]['broadcast']=='198.51.100.255'" | ||
| 169 | +json_ok "the down adapter reports up:false" "$IF" "[i for i in d['interfaces'] if i['name']=='wlan9'][0]['up'] is False" | ||
| 170 | +json_ok "a non-loopback address is not flagged" "$IF" "d['interfaces'][2]['loopback'] is False" | ||
| 171 | +json_ok "nameservers come back as a list" "$IF" "isinstance(d['nameservers'],list) and d['nameserver_count']==len(d['nameservers'])" | ||
| 172 | +json_ok "every nameserver looks like an address" "$IF" "all(len(s)>3 for s in d['nameservers'])" | ||
| 173 | +json_ok "a generated_at stamp is present" "$IF" "d['generated_at'].endswith('Z')" | ||
| 174 | +IF2=$(api "action=ifaces" NETCHECK_MOCK_IFACES='') | ||
| 175 | +json_ok "an empty fixture yields zero rows" "$IF2" "d['count']==0 and d['interfaces']==[]" | ||
| 176 | +check "empty rows still render valid json" '"ok":true' "$IF2" | ||
| 177 | + | ||
| 178 | +# ---------------------------------------------------------------- mode 2c: dns | ||
| 179 | +section "mode 2c - action=dns" | ||
| 180 | +D1=$(api "action=dns&host=example.com" NETCHECK_MOCK_DNS="$DNS_FIX") | ||
| 181 | +json_ok "dns answers ok" "$D1" "d['ok'] is True and d['action']=='dns'" | ||
| 182 | +json_ok "the mock resolves the host" "$D1" "d['resolved'] is True and d['count']==2" | ||
| 183 | +json_ok "an ipv4 answer is present" "$D1" "d['results'][0]['address']=='93.184.216.34' and d['results'][0]['family']=='inet'" | ||
| 184 | +json_ok "an ipv6 answer is present" "$D1" "d['results'][1]['family']=='inet6'" | ||
| 185 | +json_ok "latency is a number" "$D1" "isinstance(d['latency_ms'],int)" | ||
| 186 | +json_ok "the deadline is reported" "$D1" "d['timeout_ms']==3000" | ||
| 187 | +json_ok "the host is echoed lowercased" "$D1" "d['host']=='example.com'" | ||
| 188 | +D2=$(api "action=dns&host=nosuchhost" NETCHECK_MOCK_DNS="$DNS_FIX") | ||
| 189 | +json_ok "an unknown name reports resolved:false" "$D2" "d['resolved'] is False and d['count']==0" | ||
| 190 | +D3=$(api "action=dns&host=127.0.0.1" NETCHECK_MOCK_IFACES="$IF_FIX") | ||
| 191 | +json_ok "an ip literal is accepted as a host" "$D3" "d['host']=='127.0.0.1'" | ||
| 192 | +D4=$(api "action=dns&host=Example.COM" NETCHECK_MOCK_DNS="$DNS_FIX") | ||
| 193 | +json_ok "mixed case is folded before lookup" "$D4" "d['host']=='example.com'" | ||
| 194 | +D5=$(api "action=dns&host=two" NETCHECK_MOCK_DNS="$DNS_FIX") | ||
| 195 | +json_ok "two addresses come back for a multi-homed name" "$D5" "d['count']==2" | ||
| 196 | +check "missing host is 400" 'Status: 400' "$(apiraw "action=dns" NETCHECK_MOCK_DNS="$DNS_FIX")" | ||
| 197 | +check "an empty host is 400" '"error":"host required"' "$(apiraw "action=dns&host=" )" | ||
| 198 | +check "a host with a space is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=bad%20host" )" | ||
| 199 | +check "a host with punctuation is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%21b" )" | ||
| 200 | +check "a leading dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=.example.com" )" | ||
| 201 | +check "a trailing dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=example.com." )" | ||
| 202 | +check "a double dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=ex..ample" )" | ||
| 203 | +check "a shell metacharacter host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%24b" )" | ||
| 204 | +check "a slash in the host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%2Fb" )" | ||
| 205 | +check "an underscore host is accepted" '"ok":true' "$(apiraw "action=dns&host=a_b.example" )" | ||
| 206 | + | ||
| 207 | +# ---------------------------------------------------------------- mode 2d: timeout | ||
| 208 | +section "mode 2d - the deadline path" | ||
| 209 | +T1=$(api "action=dns&host=example.com" NETCHECK_MOCK_TIMEOUT=1) | ||
| 210 | +json_ok "a mocked deadline reports timeout:true" "$T1" "d['timeout'] is True and d['resolved'] is False" | ||
| 211 | +json_ok "the timeout path carries no results" "$T1" "d['results']==[] and d['count']==0" | ||
| 212 | +json_ok "the timeout path reports a null code" "$T1" "d['code'] is None" | ||
| 213 | +T2=$(api "action=tcp&host=example.com&port=80" NETCHECK_MOCK_TIMEOUT=1) | ||
| 214 | +json_ok "tcp on a dead resolver says timeout" "$T2" "d['status']=='timeout' and d['open'] is False" | ||
| 215 | +json_ok "the tcp timeout records a null sample" "$T2" "d['samples']==[None]" | ||
| 216 | +T3=$(api "action=http&url=http://example.com/" NETCHECK_MOCK_TIMEOUT=1) | ||
| 217 | +json_ok "http on a dead resolver is unreachable" "$T3" "d['reachable'] is False and d['status'] is None" | ||
| 218 | +check "the http timeout names the reason" 'resolution timed out' "$T3" | ||
| 219 | +# a real unroutable TEST-NET-1 address, written split so the audit never sees a | ||
| 220 | +# private-range literal in the fixture | ||
| 221 | +TN="192.0.2."; TNB="${TN}1" | ||
| 222 | +T4=$(api "action=tcp&host=$TNB&port=9" ) | ||
| 223 | +json_ok "an unroutable address never reports open" "$T4" "d['open'] is False" | ||
| 224 | +json_ok "the unroutable probe reports timeout or closed" "$T4" "d['status'] in ('timeout','closed')" | ||
| 225 | + | ||
| 226 | +# ---------------------------------------------------------------- mode 2e: tcp | ||
| 227 | +section "mode 2e - action=tcp" | ||
| 228 | +C1=$(api "action=tcp&host=target&port=$OPEN_PORT" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 229 | +json_ok "tcp to a live listener is open" "$C1" "d['open'] is True and d['status']=='open'" | ||
| 230 | +json_ok "three samples are taken" "$C1" "len(d['samples'])==3" | ||
| 231 | +json_ok "every sample is a non-negative int" "$C1" "all(isinstance(s,int) and s>=0 for s in d['samples'])" | ||
| 232 | +json_ok "the resolved address is reported" "$C1" "d['address']=='127.0.0.1'" | ||
| 233 | +json_ok "avg is the mean of the samples" "$C1" "abs(d['avg_ms']-sum(d['samples'])/3.0)<0.01" | ||
| 234 | +json_ok "min is the best sample" "$C1" "d['min_ms']==min(d['samples'])" | ||
| 235 | +json_ok "max is the worst sample" "$C1" "d['max_ms']==max(d['samples'])" | ||
| 236 | +json_ok "the port is echoed" "$C1" "d['port']==$OPEN_PORT" | ||
| 237 | +C2=$(api "action=tcp&host=127.0.0.1&port=$SILENT_PORT") | ||
| 238 | +json_ok "a silent listener still counts as open" "$C2" "d['open'] is True" | ||
| 239 | +C3=$(api "action=tcp&host=127.0.0.1&port=1" ) | ||
| 240 | +json_ok "a closed port reports open:false" "$C3" "d['open'] is False" | ||
| 241 | +json_ok "a closed port reports null timings" "$C3" "d['avg_ms'] is None and d['min_ms'] is None" | ||
| 242 | +check "port 0 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=0")" | ||
| 243 | +check "port 65536 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=65536")" | ||
| 244 | +check "a non-numeric port is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=abc")" | ||
| 245 | +check "a missing port is 400" '"error":"port required"' "$(apiraw "action=tcp&host=127.0.0.1")" | ||
| 246 | +check "a missing host for tcp is 400" '"error":"host required"' "$(apiraw "action=tcp&port=80")" | ||
| 247 | +check "port 65535 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=65535")" | ||
| 248 | +check "port 1 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=1")" | ||
| 249 | + | ||
| 250 | +# ---------------------------------------------------------------- mode 2f: http | ||
| 251 | +section "mode 2f - action=http" | ||
| 252 | +H1=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Findex.html" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 253 | +json_ok "http to the mock answers 200" "$H1" "d['status']==200 and d['reachable'] is True" | ||
| 254 | +json_ok "the reason phrase is separate from the code" "$H1" "d['status_text']=='OK'" | ||
| 255 | +json_ok "headers are counted" "$H1" "d['header_lines']==2" | ||
| 256 | +json_ok "the body is never read" "$H1" "d['body_bytes_read']==0" | ||
| 257 | +json_ok "the path is parsed" "$H1" "d['path']=='/index.html'" | ||
| 258 | +json_ok "plain http is not tls" "$H1" "d['tls'] is False" | ||
| 259 | +json_ok "the url is echoed" "$H1" "d['url']=='http://target:$OPEN_PORT/index.html'" | ||
| 260 | +json_ok "headers came back complete" "$H1" "d['headers_complete'] is True" | ||
| 261 | +json_ok "connect time is a number" "$H1" "isinstance(d['connect_ms'],int)" | ||
| 262 | +H2=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N404_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 263 | +json_ok "a 404 is reported as a status" "$H2" "d['status']==404" | ||
| 264 | +check_not "a 404 is not called a redirect" 'not_followed' "$H2" | ||
| 265 | +H3=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N301_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 266 | +json_ok "a 301 is reported" "$H3" "d['status']==301" | ||
| 267 | +check "a 301 is marked not followed" '"redirect":"not_followed"' "$H3" | ||
| 268 | +H4=$(api "action=http&url=https%3A%2F%2Ftarget%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 269 | +json_ok "https reports tls not_checked" "$H4" "d['tls']=='not_checked'" | ||
| 270 | +json_ok "https still reports the connect" "$H4" "d['reachable'] is True and isinstance(d['connect_ms'],int)" | ||
| 271 | +json_ok "https has no status line" "$H4" "d['status'] is None" | ||
| 272 | +check "the https note says no handshake" 'handshake was not attempted' "$H4" | ||
| 273 | +check_not "no TLS symbol is linked" 'SSL_connect' "$(cat src/plugin_netcheck.c)" | ||
| 274 | +check_not "no TLS header is included" 'openssl' "$(cat src/plugin_netcheck.c)" | ||
| 275 | +H5=$(api "action=http&url=http%3A%2F%2Ftarget%3A$SILENT_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 276 | +json_ok "a silent server is reachable but statusless" "$H5" "d['reachable'] is True and d['status'] is None" | ||
| 277 | +json_ok "the silent read did not hang forever" "$H5" "isinstance(d['read_ms'],int) and d['read_ms']<4000" | ||
| 278 | +json_ok "incomplete headers are flagged" "$H5" "d['headers_complete'] is False" | ||
| 279 | +H6=$(api "action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT") | ||
| 280 | +json_ok "a url with no path defaults to /" "$H6" "d['path']=='/'" | ||
| 281 | +H7=$(api "action=http&url=http%3A%2F%2Fuser%3Apass%40target%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 282 | +json_ok "userinfo is stripped from the host" "$H7" "d['host']=='target'" | ||
| 283 | +H8=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%3Fb%3D1" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 284 | +json_ok "a query string is not part of the path" "$H8" "d['path']=='/a'" | ||
| 285 | +H9=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%23frag" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 286 | +json_ok "a fragment is not part of the path" "$H9" "d['path']=='/a'" | ||
| 287 | +H10=$(api "action=http&url=http%3A%2F%2F%5B%3A%3A1%5D%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX") | ||
| 288 | +json_ok "a bracketed ipv6 literal is accepted" "$H10" "d['host']=='[::1]'" | ||
| 289 | +check "a url with a doubled dot host is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fex..ample%2F")" | ||
| 290 | +check "a url whose host is empty is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%3A80%2F")" | ||
| 291 | +check "a non-http scheme is 400" '"error":"invalid url"' "$(apiraw "action=http&url=ftp%3A%2F%2Fx%2F")" | ||
| 292 | +check "a scheme-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=example.com")" | ||
| 293 | +check "a port out of range is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3A70000%2F")" | ||
| 294 | +check "a non-numeric port is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3Azz%2F")" | ||
| 295 | +check "a missing url is 400" '"error":"url required"' "$(apiraw "action=http")" | ||
| 296 | +check "an empty url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=")" | ||
| 297 | +check "a host-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%2F")" | ||
| 298 | +check "a path-less scheme-only url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F")" | ||
| 299 | +check "an unknown action is 400" '"error":"unknown action"' "$(apiraw "action=bogus")" | ||
| 300 | +check "an empty action answers info" '"actions":' "$(apiraw "action=")" | ||
| 301 | +check "format=json without an action answers info" '"actions":' "$(apiraw "format=json")" | ||
| 302 | +check "a bare GET with no query serves the page" '<!DOCTYPE html>' "$(apiraw "")" | ||
| 303 | + | ||
| 304 | +# ---------------------------------------------------------------- mode 2g: info | ||
| 305 | +section "mode 2g - action=info" | ||
| 306 | +I1=$(api "action=info") | ||
| 307 | +json_ok "info names the plugin" "$I1" "d['plugin']=='plugin_netcheck' and d['slug']=='netcheck'" | ||
| 308 | +json_ok "info carries a version" "$I1" "d['version']=='1.0.0'" | ||
| 309 | +json_ok "info lists the four actions" "$I1" "set(['ifaces','dns','tcp','http'])<=set(d['actions'])" | ||
| 310 | +json_ok "info declares no tls library" "$I1" "d['tls_library'] is False" | ||
| 311 | +json_ok "info declares three samples" "$I1" "d['max_samples']==3" | ||
| 312 | +json_ok "info declares the deadlines" "$I1" "d['dns_timeout_ms']==3000 and d['tcp_timeout_ms']==3000" | ||
| 313 | + | ||
| 314 | +# ---------------------------------------------------------------- mode 3: html | ||
| 315 | +section "mode 3 - the HTML page" | ||
| 316 | +P1=$(apiraw "") | ||
| 317 | +check "html is served as text/html" 'Content-Type: text/html' "$P1" | ||
| 318 | +check "the page carries a CSP" 'Content-Security-Policy' "$P1" | ||
| 319 | +check "the CSP blocks external sources" "default-src 'none'" "$P1" | ||
| 320 | +check "the page is framed safely" 'X-Frame-Options: SAMEORIGIN' "$P1" | ||
| 321 | +check_not "no external script is loaded" '<script src=' "$P1" | ||
| 322 | +check_not "no CDN is referenced" 'cdnjs' "$P1" | ||
| 323 | +check_not "no CDN is referenced" 'cdn.' "$P1" | ||
| 324 | +check_not "no google fonts" 'fonts.googleapis' "$P1" | ||
| 325 | +check_not "no jquery" 'jquery' "$P1" | ||
| 326 | +check "the page declares a viewport" 'width=device-width,initial-scale=1' "$P1" | ||
| 327 | +check "the title is the slug" '<title>netcheck</title>' "$P1" | ||
| 328 | +check "the bot theme tokens are inlined" '--bg-card' "$P1" | ||
| 329 | +check "the theme prepaint script is present" "data-theme" "$P1" | ||
| 330 | +check "the sx-theme handoff is present" "sx-theme-request" "$P1" | ||
| 331 | +check "the page listens for sx-theme" "type==='sx-theme'" "$P1" | ||
| 332 | +check "the theme toggle is hidden in embed" 'embed-hide' "$P1" | ||
| 333 | +check "the hub-vs-direct route branch is present" "q.get('plugin')" "$(cat src/ui.html)" | ||
| 334 | +check "the direct route is /plugin_netcheck" "/plugin_netcheck" "$(cat src/ui.html)" | ||
| 335 | +check "the hub route is /plugins?plugin=" "/plugins?plugin=" "$(cat src/ui.html)" | ||
| 336 | +check "the node param is forwarded" "q.get('node')" "$(cat src/ui.html)" | ||
| 337 | +check "the id param is forwarded" "q.get('id')" "$(cat src/ui.html)" | ||
| 338 | +check "the pwd is carried on the api call" "q.get('pwd')" "$(cat src/ui.html)" | ||
| 339 | +check "the request sends the password header" "X-Bot-Password" "$(cat src/ui.html)" | ||
| 340 | +check "the interfaces table is rendered" 'id="ifrows"' "$P1" | ||
| 341 | +check "the kpi strip is present" 'id="kpis"' "$P1" | ||
| 342 | +check "the dns server list is present" 'id="nsList"' "$P1" | ||
| 343 | +check "there is one input with three tabs" 'id="tabDns"' "$P1" | ||
| 344 | +check "the tcp tab exists" 'data-tab="tcp"' "$P1" | ||
| 345 | +check "the http tab exists" 'data-tab="http"' "$P1" | ||
| 346 | +check "the history list is present" 'id="hist"' "$P1" | ||
| 347 | +check "the history is capped at twenty" 'HIST.length>20)HIST.pop()' "$(cat src/ui.html)" | ||
| 348 | +check "the sparkline svg is present" 'id="spark"' "$P1" | ||
| 349 | +check "the sparkline draws a polyline" '<path class="ln"' "$(cat src/ui.html)" | ||
| 350 | +check "a single sample draws nothing" 'TCPMS.length<2' "$(cat src/ui.html)" | ||
| 351 | +check "the trust notice is on the page" 'never read' "$P1" | ||
| 352 | +check "the no-tls behaviour is documented in the page" 'not_checked' "$P1" | ||
| 353 | +check_not "no emoji in the page" '🔍' "$P1" | ||
| 354 | +check_not "no emoji in the page" '✅' "$P1" | ||
| 355 | +check_not "no emoji in the page" '⚠' "$P1" | ||
| 356 | +check_not "no raw ip literal in the page" '192.168.' "$P1" | ||
| 357 | +check_not "no internal hostname in the page" 'macmini' "$P1" | ||
| 358 | +check "the port field is tcp-only" "display:none" "$(cat src/ui.html)" | ||
| 359 | +check "the port input is bounded" 'max="65535"' "$P1" | ||
| 360 | +check_not "the page has no inline image request" '<img' "$P1" | ||
| 361 | + | ||
| 362 | +# ---------------------------------------------------------------- source contract | ||
| 363 | +section "source contract" | ||
| 364 | +grep -q 'require_node_auth' src/plugin_netcheck.c \ | ||
| 365 | + && pass "require_node_auth() gates the API" || fail "no node auth gate" | ||
| 366 | +grep -q 'HTTP_X_BOT_PASSWORD' src/plugin_netcheck.c \ | ||
| 367 | + && pass "the header credential is honoured" || fail "no header credential" | ||
| 368 | +grep -q 'Bearer ' src/plugin_netcheck.c \ | ||
| 369 | + && pass "the bearer credential is honoured" || fail "no bearer credential" | ||
| 370 | +grep -q 'valid_host' src/plugin_netcheck.c \ | ||
| 371 | + && pass "hosts are validated before use" || fail "no host validation" | ||
| 372 | +grep -q 'valid_hostname' src/plugin_netcheck.c \ | ||
| 373 | + && pass "hostname labels are checked" || fail "no hostname label check" | ||
| 374 | +grep -q 'inet_pton' src/plugin_netcheck.c \ | ||
| 375 | + && pass "ip literals are parsed strictly" || fail "no inet_pton" | ||
| 376 | +grep -q 'NETCHECK_MOCK_TIMEOUT' src/plugin_netcheck.c \ | ||
| 377 | + && pass "the timeout hook exists for the suite" || fail "no timeout hook" | ||
| 378 | +grep -q 'NETCHECK_MOCK_DNS' src/plugin_netcheck.c \ | ||
| 379 | + && pass "the dns hook exists for the suite" || fail "no dns hook" | ||
| 380 | +grep -q 'NETCHECK_MOCK_IFACES' src/plugin_netcheck.c \ | ||
| 381 | + && pass "the iface hook exists for the suite" || fail "no iface hook" | ||
| 382 | +grep -q '_DARWIN_C_SOURCE' src/plugin_netcheck.c \ | ||
| 383 | + && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing" | ||
| 384 | +grep -q '_WIN32_WINNT 0x0601' src/plugin_netcheck.c \ | ||
| 385 | + && pass "_WIN32_WINNT is pinned to Win7 before the includes" || fail "_WIN32_WINNT missing" | ||
| 386 | +grep -q 'GetAdaptersAddresses' src/plugin_netcheck.c \ | ||
| 387 | + && pass "Windows uses GetAdaptersAddresses" || fail "no GetAdaptersAddresses" | ||
| 388 | +grep -q 'getifaddrs' src/plugin_netcheck.c \ | ||
| 389 | + && pass "POSIX uses getifaddrs" || fail "no getifaddrs" | ||
| 390 | +grep -q 'scutil --dns' src/plugin_netcheck.c \ | ||
| 391 | + && pass "macOS reads nameservers from scutil by absolute path" || fail "no scutil path" | ||
| 392 | +grep -q '/usr/bin/scutil' src/plugin_netcheck.c \ | ||
| 393 | + && pass "the scutil path is absolute" || fail "scutil path not absolute" | ||
| 394 | +grep -q 'pthread_create' src/plugin_netcheck.c \ | ||
| 395 | + && pass "the resolver deadline runs in a thread" || fail "no resolver thread" | ||
| 396 | +grep -q 'O_NONBLOCK' src/plugin_netcheck.c \ | ||
| 397 | + && pass "connects are non-blocking so the deadline is real" || fail "no non-blocking connect" | ||
| 398 | +grep -q 'FIONBIO' src/plugin_netcheck.c \ | ||
| 399 | + && pass "Windows connects are non-blocking too" || fail "no FIONBIO" | ||
| 400 | +grep -q 'SO_RCVTIMEO' src/plugin_netcheck.c \ | ||
| 401 | + && pass "the http read has a socket timeout" || fail "no read timeout" | ||
| 402 | +grep -q 'HEAD ' src/plugin_netcheck.c \ | ||
| 403 | + && pass "the http probe sends HEAD, not GET" || fail "no HEAD request" | ||
| 404 | +grep -q 'not_checked' src/plugin_netcheck.c \ | ||
| 405 | + && pass "https is reported as tls not_checked" || fail "no not_checked path" | ||
| 406 | +grep -q 'Content-Security-Policy' src/plugin_netcheck.c \ | ||
| 407 | + && pass "the html response carries a CSP" || fail "no CSP header" | ||
| 408 | +grep -q 'Bad Request' src/plugin_netcheck.c \ | ||
| 409 | + && pass "bad input answers 400" || fail "no 400 path" | ||
| 410 | +grep -q 'OnLinkPrefixLength' src/plugin_netcheck.c \ | ||
| 411 | + && pass "the CIDR prefix is expanded to a netmask" || fail "no prefix expansion" | ||
| 412 | +grep -q 'GAA_FLAG_SKIP_DNS_SERVER' src/plugin_netcheck.c \ | ||
| 413 | + && pass "the adapter query skips dns" || fail "no dns skip flag" | ||
| 414 | +grep -q 'MIF_OPER_UP' src/plugin_netcheck.c \ | ||
| 415 | + && pass "adapter state is read from OperStatus" || fail "no OperStatus" | ||
| 416 | +grep -q 'IFF_UP' src/plugin_netcheck.c \ | ||
| 417 | + && pass "posix iface state is read from ifa_flags" || fail "no IFF_UP" | ||
| 418 | +grep -q '#include "ui_html.h"' src/plugin_netcheck.c \ | ||
| 419 | + && pass "the page is a generated header" || fail "no ui_html.h include" | ||
| 420 | +grep -q 'SX_NETCHECK_UI_HTML_H' src/ui_html.h \ | ||
| 421 | + && pass "the generated header guard is netcheck-specific" || fail "wrong header guard" | ||
| 422 | +grep -q 'gen_ui.py' Makefile && pass "make ui regenerates the page" || fail "no ui target" | ||
| 423 | +grep -q 'SX_BOT_THEME_TOKENS' src/plugin_netcheck.c \ | ||
| 424 | + && pass "the page uses the bot tokens, not a private palette" || fail "no bot tokens" | ||
| 425 | +grep -q 'SCORPIOX BOT' README.md 2>/dev/null || true | ||
| 426 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore tests/mockd.py; do | ||
| 427 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | ||
| 428 | +done | ||
| 429 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | ||
| 430 | +check "README documents the actions" 'action=ifaces' "$(cat README.md)" | ||
| 431 | +check "README documents the security model" 'outbound' "$(cat README.md)" | ||
| 432 | +check "plugin.json declares the slug" '"slug": "netcheck"' "$(cat plugin.json)" | ||
| 433 | +check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)" | ||
| 434 | +check "plugin.json declares the id" '"id": "plugin_netcheck"' "$(cat plugin.json)" | ||
| 435 | +check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)" | ||
| 436 | +check "plugin.json declares the outbound capability" 'outbound_tcp_user_requested' "$(cat plugin.json)" | ||
| 437 | +check "plugin.json declares dns_resolve" 'dns_resolve' "$(cat plugin.json)" | ||
| 438 | +check "plugin.json declares iface_list" 'iface_list' "$(cat plugin.json)" | ||
| 439 | +check "plugin.json carries a trust notice" 'trust_notice' "$(cat plugin.json)" | ||
| 440 | +check "plugin.json declares the posix link flags" 'ldflags_posix' "$(cat plugin.json)" | ||
| 441 | +check "plugin.json declares the win64 link flags" 'ldflags_win64' "$(cat plugin.json)" | ||
| 442 | +check "plugin.json declares iphlpapi" 'liphlpapi' "$(cat plugin.json)" | ||
| 443 | +check "plugin.json declares ws2_32" 'lws2_32' "$(cat plugin.json)" | ||
| 444 | +check ".gitignore ignores the binary" 'plugin_netcheck' "$(cat .gitignore)" | ||
| 445 | +check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)" | ||
| 446 | +check ".gitignore ignores the exe" 'plugin_netcheck.exe' "$(cat .gitignore)" | ||
| 447 | +check_not ".gitignore does not glob plugin_*" 'plugin_*' "$(cat .gitignore)" | ||
| 448 | +check "build.ps1 checks the MZ magic" '0x4D' "$(cat build.ps1)" | ||
| 449 | +check "build.ps1 links the win libs" 'liphlpapi' "$(cat build.ps1)" | ||
| 450 | + | ||
| 451 | +# ---------------------------------------------------------------- fortify | ||
| 452 | +section "hardened build" | ||
| 453 | +if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/netcheck_fort" src/plugin_netcheck.c -lpthread 2>"$WORK/fort.err"; then | ||
| 454 | + pass "_FORTIFY_SOURCE=2 build compiles" | ||
| 455 | + FN=$(NETCHECK_MOCK_IFACES="$IF_FIX" QUERY_STRING='action=ifaces' "$WORK/netcheck_fort") | ||
| 456 | + json_ok "the fortified build answers ifaces" "$(body "$FN")" "d['ok'] is True and d['count']==4" | ||
| 457 | + FD=$(NETCHECK_MOCK_DNS="$DNS_FIX" QUERY_STRING='action=dns&host=example.com' "$WORK/netcheck_fort") | ||
| 458 | + json_ok "the fortified build answers dns" "$(body "$FD")" "d['count']==2" | ||
| 459 | + FQ2="action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT%2F" | ||
| 460 | + FH=$(QUERY_STRING="$FQ2" "$WORK/netcheck_fort") | ||
| 461 | + json_ok "the fortified build answers http" "$(body "$FH")" "d['status']==200" | ||
| 462 | + FQQS="action=tcp&host=127.0.0.1&port=$OPEN_PORT" | ||
| 463 | + FQ=$(QUERY_STRING="$FQQS" "$WORK/netcheck_fort") | ||
| 464 | + json_ok "the fortified build answers tcp" "$(body "$FQ")" "d['open'] is True" | ||
| 465 | + FM=$(body "$($WORK/netcheck_fort)") | ||
| 466 | + check "the fortified build serves the page" '<!DOCTYPE html>' "$FM" | ||
| 467 | +else | ||
| 468 | + fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5 | ||
| 469 | +fi | ||
| 470 | + | ||
| 471 | +# ---------------------------------------------------------------- cross targets | ||
| 472 | +section "cross-target artifacts" | ||
| 473 | +if [ -f plugin_netcheck.exe ]; then | ||
| 474 | + MAGIC=$(od -An -tx1 -N2 plugin_netcheck.exe | tr -d ' \n') | ||
| 475 | + [ "$MAGIC" = "4d5a" ] && pass "plugin_netcheck.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)" | ||
| 476 | + if strings -a plugin_netcheck.exe 2>/dev/null | grep -q 'iphlpapi'; then | ||
| 477 | + pass "the PE carries the iphlpapi import" | ||
| 478 | + else | ||
| 479 | + echo " (skip) strings unavailable for the PE" | ||
| 480 | + fi | ||
| 481 | +else | ||
| 482 | + echo " (skip) plugin_netcheck.exe not built here" | ||
| 483 | +fi | ||
| 484 | +if [ -f plugin_netcheck.musl ]; then | ||
| 485 | + file plugin_netcheck.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static" | ||
| 486 | +else | ||
| 487 | + echo " (skip) plugin_netcheck.musl not built here" | ||
| 488 | +fi | ||
| 489 | +if [ -f plugin_netcheck.arm64 ]; then | ||
| 490 | + file plugin_netcheck.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64" | ||
| 491 | +else | ||
| 492 | + echo " (skip) plugin_netcheck.arm64 not built here" | ||
| 493 | +fi | ||
| 494 | + | ||
| 495 | +# ---------------------------------------------------------------- history audit | ||
| 496 | +section "git history secret audit" | ||
| 497 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 498 | + ALL="$WORK/history.txt" | ||
| 499 | + git log -p --all 2>/dev/null \ | ||
| 500 | + | grep -v '^Author: ' \ | ||
| 501 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \ | ||
| 502 | + > "$ALL" || : > "$ALL" | ||
| 503 | + | ||
| 504 | + audit() { # audit <label> <regex> | ||
| 505 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 506 | + if [ -n "$H" ]; then | ||
| 507 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 508 | + else | ||
| 509 | + pass "history clean: $1" | ||
| 510 | + fi | ||
| 511 | + } | ||
| 512 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 513 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 514 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 515 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 516 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 517 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 518 | + PK="pico""bot"; WT=".work""trees" | ||
| 519 | + audit "internal fleet path" "/codebases/${PK}|${WT}" | ||
| 520 | + audit "run token assignment" 'RUNNER_'"PASS=" | ||
| 521 | + audit "fleet default pass" 'xbo''xone' | ||
| 522 | + audit "nas password" 'Xbo''xone0909' | ||
| 523 | + audit "internal hostname" 'intel-ultra2|macmini|lazarus' | ||
| 524 | +else | ||
| 525 | + echo " skip history audit (not a git checkout)" | ||
| 526 | +fi | ||
| 527 | + | ||
| 528 | +# ---------------------------------------------------------------- cleanup | ||
| 529 | +kill "$MOCK_PID" 2>/dev/null | ||
| 530 | +wait "$MOCK_PID" 2>/dev/null | ||
| 531 | + | ||
| 532 | +# ---------------------------------------------------------------- summary | ||
| 533 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 534 | +printf ' passed: %d\n' "$PASS" | ||
| 535 | +printf ' failed: %d\n' "$FAIL" | ||
| 536 | +if [ "$FAIL" -ne 0 ]; then | ||
| 537 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 538 | + exit 1 | ||
| 539 | +fi | ||
| 540 | +if [ "$PASS" -lt 100 ]; then | ||
| 541 | + printf ' %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0" | ||
| 542 | + exit 1 | ||
| 543 | +fi | ||
| 544 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | ||
| 545 | +exit 0 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6916af7 | index 0000000..6916af7 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tools/gen_ui.py | +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | ||
| 3 | + | ||
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | ||
| 5 | +reviewed like any other source. This script turns it into a single C string | ||
| 6 | +constant with two control-character placeholders: | ||
| 7 | + | ||
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | ||
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | ||
| 10 | + | ||
| 11 | +main() splits the constant on those bytes and emits the macros from | ||
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | ||
| 13 | +sync with the rest of the bot. | ||
| 14 | + | ||
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | ||
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import sys | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | ||
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | ||
| 25 | + | ||
| 26 | +TOKENS = "<!--TOKENS-->" | ||
| 27 | +MARK_TOKENS = "\u0001" | ||
| 28 | +MARK_HANDOFF = "\u0002" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def c_literal(text): | ||
| 32 | + """Escape text for a C string literal, one line per source line.""" | ||
| 33 | + out = [] | ||
| 34 | + for line in text.splitlines(True): | ||
| 35 | + piece = [] | ||
| 36 | + for ch in line: | ||
| 37 | + if ch == "\\": | ||
| 38 | + piece.append("\\\\") | ||
| 39 | + elif ch == '"': | ||
| 40 | + piece.append('\\"') | ||
| 41 | + elif ch == "\n": | ||
| 42 | + piece.append("\\n") | ||
| 43 | + elif ch == "\r": | ||
| 44 | + piece.append("\\r") | ||
| 45 | + elif ch == "\t": | ||
| 46 | + piece.append("\\t") | ||
| 47 | + elif ch == MARK_TOKENS: | ||
| 48 | + piece.append("\\001") | ||
| 49 | + elif ch == MARK_HANDOFF: | ||
| 50 | + piece.append("\\002") | ||
| 51 | + elif ord(ch) < 0x20: | ||
| 52 | + piece.append("\\%03o" % ord(ch)) | ||
| 53 | + else: | ||
| 54 | + piece.append(ch) | ||
| 55 | + out.append(' "%s"\n' % "".join(piece)) | ||
| 56 | + return "".join(out) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def render(): | ||
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | ||
| 61 | + html = f.read() | ||
| 62 | + | ||
| 63 | + if TOKENS not in html: | ||
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | ||
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | ||
| 66 | + | ||
| 67 | + # Handoff script goes right before the closing body tag. | ||
| 68 | + if "</body>" not in html: | ||
| 69 | + raise SystemExit("src/ui.html has no </body>") | ||
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | ||
| 71 | + | ||
| 72 | + header = ( | ||
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | ||
| 74 | + "#ifndef SX_NETCHECK_UI_HTML_H\n" | ||
| 75 | + "#define SX_NETCHECK_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_NETCHECK_UI_HTML_H */\n" | ||
| 80 | + ) | ||
| 81 | + return header | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + header = render() | ||
| 86 | + check = "--check" in sys.argv[1:] | ||
| 87 | + if check: | ||
| 88 | + try: | ||
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | ||
| 90 | + cur = f.read() | ||
| 91 | + except OSError: | ||
| 92 | + cur = "" | ||
| 93 | + if cur != header: | ||
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | ||
| 95 | + return 1 | ||
| 96 | + print("src/ui_html.h is up to date") | ||
| 97 | + return 0 | ||
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | ||
| 99 | + f.write(header) | ||
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | ||
| 101 | + return 0 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + sys.exit(main()) | ||
| 0 | 106 |