/* * plugin_services - SCORPIOX BOT open-source local service status board * * One clean-room C99 binary, three modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=list|show|control / ?format=json / POST -> JSON node API * 3. GET (default) -> responsive HTML board * * It reports every service the node's init system knows about: * * Linux systemd via `systemctl list-units --output=json` (falls back to the * plain table on systemd < 248), enriched by `systemctl show -p ...` * over the validated unit names. Inside a * container with no init system (no /run/systemd/system) it reports * init_system:"none" and lists the long-running daemons it can see in * /proc instead of pretending the node has none. * macOS `launchctl list` (pid / status / label), with memory and uptime * filled in from one `ps` pass over the returned pids. * Windows OpenSCManagerA + EnumServicesStatusExA and QueryServiceConfigA. * No shell, no popen, no service name ever reaches a command line. * * Read-only by default. start/stop/restart exist only when the node operator * sets SERVICES_ALLOW_CONTROL=1, requires node auth, and every unit name is * validated against [A-Za-z0-9@._:-]{1,160} before it is handed to execvp as a * separate argv element (POSIX) or the SCM (Windows). No unit name is ever * interpolated into a shell string, so `a;reboot` is a 400, not a shell escape. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must be the very first thing: advapi32's EnumServicesStatusExA and * QueryServiceConfigA are gated on _WIN32_WINNT, and MinGW defaults to 0x502 * (Server 2003) which hides them. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # define sx_popen _popen # define sx_pclose _pclose #else # include # include # include # include # define sx_popen popen # define sx_pclose pclose #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "services" #define PLUGIN_ID "plugin_services" #define PLUGIN_VER "1.0.1" #define PLUGIN_NAME "services" #define PLUGIN_DESC "System services" #define MAX_SERVICES 2048 #define NAME_SZ 192 #define DESC_SZ 192 #define STATE_SZ 32 #define EN_SZ 32 #define OUT_SZ (1024 * 1024) /* init systems */ #define INIT_NONE 0 #define INIT_SYSTEMD 1 #define INIT_LAUNCHD 2 #define INIT_SCM 3 typedef struct { char name[NAME_SZ]; /* unit / label / service name */ char desc[DESC_SZ]; char active[STATE_SZ]; /* active | inactive | failed | running | stopped */ char sub[STATE_SZ]; /* running | dead | exited | ... */ char enabled[EN_SZ]; /* enabled | disabled | static | - */ int pid; unsigned long long mem; /* bytes, 0 = unknown */ char since[40]; } svc_t; static svc_t g_svc[MAX_SERVICES]; static int g_count; static int g_init = INIT_NONE; static int g_control = 0; /* ------------------------------------------------------------------ */ /* Growable output buffer */ /* ------------------------------------------------------------------ */ typedef struct { char *p; size_t n, cap; } buf_t; static int buf_need(buf_t *b, size_t extra) { size_t want; char *np; if (b->n + extra + 1 <= b->cap) return 1; want = b->cap ? b->cap : 4096; while (want < b->n + extra + 1) want *= 2; np = (char *)realloc(b->p, want); if (!np) return 0; b->p = np; b->cap = want; return 1; } static void buf_add(buf_t *b, const char *s, size_t n) { if (!b || !s) return; if (!buf_need(b, n)) return; memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; } static void buf_puts(buf_t *b, const char *s) { if (s) buf_add(b, s, strlen(s)); } static void buf_putc(buf_t *b, char c) { buf_add(b, &c, 1); } static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } static void buf_free(buf_t *b) { if (b) { free(b->p); b->p = NULL; b->n = b->cap = 0; } } /* JSON string escaping into a buffer. */ static void json_into(buf_t *b, const char *s) { buf_putc(b, '"'); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': buf_puts(b, "\\\""); break; case '\\': buf_puts(b, "\\\\"); break; case '\n': buf_puts(b, "\\n"); break; case '\r': buf_puts(b, "\\r"); break; case '\t': buf_puts(b, "\\t"); break; default: if (c < 0x20) { char tmp[8]; snprintf(tmp, sizeof tmp, "\\u%04x", c); buf_puts(b, tmp); } else { buf_putc(b, (char)c); } } } buf_putc(b, '"'); } /* ------------------------------------------------------------------ */ /* Small string utilities */ /* ------------------------------------------------------------------ */ static void str_copy(char *dst, size_t sz, const char *src) { size_t n; if (!dst || sz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= sz) n = sz - 1; memcpy(dst, src, n); dst[n] = '\0'; } #if !defined(_WIN32) static void str_trim(char *s) { char *p; size_t n; if (!s) return; p = s; while (*p && isspace((unsigned char)*p)) p++; if (p != s) memmove(s, p, strlen(p) + 1); n = strlen(s); while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; } #endif static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } /* Unit / label / service name allowlist. Anything that could be read as shell * syntax, a path, or an option is rejected outright. */ static int valid_unit(const char *s) { size_t n; if (!s) return 0; n = strlen(s); if (n < 1 || n > 160) return 0; for (; *s; s++) { unsigned char c = (unsigned char)*s; if (isalnum(c)) continue; if (c == '@' || c == '.' || c == '_' || c == ':' || c == '-' || c == '\\') continue; return 0; } return 1; } static int is_post_request(void) { const char *m = getenv("REQUEST_METHOD"); return m && strcmp(m, "POST") == 0; } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; const char *qs; char qpwd[256]; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Command capture and argv execution */ /* ------------------------------------------------------------------ */ #if !defined(_WIN32) /* Every command string passed here is a CONSTANT defined in this file, or is * built from a value that already passed valid_unit(). Nothing user-supplied * reaches this function unvalidated. */ static int capture(const char *cmd, char *out, size_t outsz) { FILE *f; size_t n; if (!out || outsz == 0) return -1; out[0] = '\0'; f = sx_popen(cmd, "r"); if (!f) return -1; n = fread(out, 1, outsz - 1, f); out[n] = '\0'; if (sx_pclose(f) != 0) { /* still return what we read: callers check for emptiness */ } return (int)n; } /* Returns the child's exit status, or -1 when it could not be started. The * unit is a separate argv element, so no shell ever sees it. */ static int run_argv(char *const argv[]) { pid_t pid; int st = 0; pid = fork(); if (pid < 0) return -1; if (pid == 0) { execvp(argv[0], argv); _exit(127); } if (waitpid(pid, &st, 0) < 0) return -1; if (WIFEXITED(st)) return WEXITSTATUS(st); return -1; } #endif /* ------------------------------------------------------------------ */ /* Service table helpers (all platforms) */ /* ------------------------------------------------------------------ */ static void svc_add(const char *name, const char *desc, const char *active, const char *sub, int pid) { svc_t *s; if (g_count >= MAX_SERVICES) return; s = &g_svc[g_count++]; memset(s, 0, sizeof *s); str_copy(s->name, sizeof s->name, name); str_copy(s->desc, sizeof s->desc, desc); str_copy(s->active, sizeof s->active, active); str_copy(s->sub, sizeof s->sub, sub); str_copy(s->enabled, sizeof s->enabled, "-"); str_copy(s->since, sizeof s->since, "-"); s->pid = pid; } static svc_t *svc_find(const char *name) { int i; if (!name) return NULL; for (i = 0; i < g_count; i++) if (strcmp(g_svc[i].name, name) == 0) return &g_svc[i]; return NULL; } /* ------------------------------------------------------------------ */ /* Minimal JSON field extraction (for systemctl --output=json output) */ /* ------------------------------------------------------------------ */ /* The JSON readers and the systemd text parsers are Linux-only: macOS has * launchd and the Windows slice talks to the SCM, so neither parses text. */ #if defined(__linux__) static int json_read_string_at(const char **pp, char *out, size_t outsz) { const char *p = *pp; size_t i = 0; if (!p || *p != '"') return 0; p++; while (*p && *p != '"') { char c = *p; if (c == '\\' && p[1]) { p++; switch (*p) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'u': { /* keep it simple: decode the low byte of the code point */ unsigned int v = 0; int k; p++; for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) { v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) ? *p - '0' : tolower((unsigned char)*p) - 'a' + 10); } if (i + 1 < outsz) out[i++] = (char)(v & 0xff); continue; } default: c = *p; break; } p++; } else { p++; } if (i + 1 < outsz) out[i++] = c; } if (*p == '"') p++; out[i] = '\0'; *pp = p; return 1; } /* Find "key":"value" inside one flat object slice [obj, obj_end). */ static int json_field(const char *obj, const char *end, const char *key, char *out, size_t outsz) { size_t klen = strlen(key); const char *p = obj; if (!out || outsz == 0) return 0; out[0] = '\0'; while (p && p < end) { if (*p == '"' && (size_t)(end - p) > klen + 1 && strncmp(p + 1, key, klen) == 0 && p[1 + klen] == '"') { const char *q = p + klen + 2; while (q < end && isspace((unsigned char)*q)) q++; if (q < end && *q == ':') { q++; while (q < end && isspace((unsigned char)*q)) q++; if (q < end && *q == '"') return json_read_string_at(&q, out, outsz); if (q < end) { size_t i = 0; while (q < end && *q != ',' && *q != '}' && i + 1 < outsz) { if (!isspace((unsigned char)*q)) out[i++] = *q; q++; } out[i] = '\0'; return 1; } } return 0; } if (*p == '"') { char tmp[8]; const char *skip = p; json_read_string_at(&skip, tmp, sizeof tmp); p = skip; continue; } p++; } return 0; } /* ------------------------------------------------------------------ */ /* Collection: systemd (Linux) */ /* ------------------------------------------------------------------ */ /* Parse the systemctl --output=json array into g_svc. */ static void parse_json_units(const char *json) { const char *p = json; while (p && *p) { const char *start, *end; char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ]; char sub[STATE_SZ], desc[DESC_SZ]; int depth = 0; start = strchr(p, '{'); if (!start) break; end = start; while (*end) { if (*end == '"') { char tmp[2]; json_read_string_at(&end, tmp, sizeof tmp); continue; } if (*end == '{') depth++; else if (*end == '}') { depth--; if (depth == 0) { end++; break; } } end++; } unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; json_field(start, end, "unit", unit, sizeof unit); json_field(start, end, "load", load, sizeof load); json_field(start, end, "active", active, sizeof active); json_field(start, end, "sub", sub, sizeof sub); json_field(start, end, "description", desc, sizeof desc); if (unit[0] && strcmp(load, "not-found") != 0) svc_add(unit, desc, active, sub, 0); p = end; } } /* Parse the pre-248 plain table: * UNIT LOAD ACTIVE SUB DESCRIPTION * ssh.service loaded active running OpenBSD Secure Shell server */ static void parse_plain_units(const char *text) { const char *p = text; while (p && *p) { const char *nl = strchr(p, '\n'); size_t len = nl ? (size_t)(nl - p) : strlen(p); char line[1024]; char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ], sub[STATE_SZ]; char desc[DESC_SZ]; int n = 0, off = 0; if (len >= sizeof line) len = sizeof line - 1; memcpy(line, p, len); line[len] = '\0'; p = nl ? nl + 1 : p + strlen(p); if (len < 4) continue; if (strstr(line, "UNIT") && strstr(line, "LOAD")) continue; if (strstr(line, "loaded units listed")) continue; if (strstr(line, "To show all installed")) continue; unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; n = sscanf(line, "%191s %31s %31s %31s %n", unit, load, active, sub, &off); if (n < 4) continue; if (strcmp(load, "loaded") != 0 && strcmp(load, "not-found") != 0) continue; if (strcmp(load, "not-found") == 0) continue; if (off > 0 && (size_t)off < len) { str_copy(desc, sizeof desc, line + off); str_trim(desc); } if (!strchr(unit, '.')) continue; svc_add(unit, desc, active, sub, 0); } } /* Output of `systemctl show -p ...` over a batch of unit names, whose output is * key=value blocks separated by a blank line. */ static void apply_show(const char *text) { const char *p = text; while (p && *p) { char name[NAME_SZ] = {0}, pid_s[24] = {0}, since[40] = {0}; char mem_s[32] = {0}, file_state[EN_SZ] = {0}; char active[STATE_SZ] = {0}, sub[STATE_SZ] = {0}, desc[DESC_SZ] = {0}; svc_t *s; { const char *nl = strstr(p, "\n\n"); const char *end = nl ? nl : p + strlen(p); const char *line = p; while (line < end) { const char *eol = strchr(line, '\n'); if (!eol || eol > end) eol = end; { size_t l = (size_t)(eol - line); char l2[512]; char *eq; if (l < sizeof l2) { memcpy(l2, line, l); l2[l] = '\0'; eq = strchr(l2, '='); if (eq) { *eq++ = '\0'; if (strcmp(l2, "Id") == 0) str_copy(name, sizeof name, eq); else if (strcmp(l2, "MainPID") == 0) str_copy(pid_s, sizeof pid_s, eq); else if (strcmp(l2, "ActiveEnterTimestamp") == 0) str_copy(since, sizeof since, eq); else if (strcmp(l2, "MemoryCurrent") == 0) str_copy(mem_s, sizeof mem_s, eq); else if (strcmp(l2, "UnitFileState") == 0) str_copy(file_state, sizeof file_state, eq); else if (strcmp(l2, "ActiveState") == 0) str_copy(active, sizeof active, eq); else if (strcmp(l2, "SubState") == 0) str_copy(sub, sizeof sub, eq); else if (strcmp(l2, "Description") == 0) str_copy(desc, sizeof desc, eq); } } } line = eol < end ? eol + 1 : end; } p = nl ? nl + 2 : end; } if (!name[0]) continue; s = svc_find(name); if (!s) { if (desc[0] || active[0]) { svc_add(name, desc, active, sub, 0); s = svc_find(name); } } if (!s) continue; s->pid = atoi(pid_s); if (mem_s[0] && strncmp(mem_s, "18446744073709551615", 20) != 0) s->mem = strtoull(mem_s, NULL, 10); if (file_state[0]) str_copy(s->enabled, sizeof s->enabled, file_state); if (since[0] && strcmp(since, "n/a") != 0) { str_copy(s->since, sizeof s->since, since); } if (active[0] && !s->active[0]) str_copy(s->active, sizeof s->active, active); if (sub[0] && !s->sub[0]) str_copy(s->sub, sizeof s->sub, sub); if (desc[0] && !s->desc[0]) str_copy(s->desc, sizeof s->desc, desc); } } #endif /* __linux__ */ #if !defined(_WIN32) static char *read_file_all(const char *path, size_t *len) { FILE *f; char *buf; long sz; size_t n; f = fopen(path, "rb"); if (!f) return NULL; sz = 0; /* /proc files report st_size 0 and are not seekable, so only trust the * size when the seek actually works; otherwise read until EOF. */ if (fseek(f, 0, SEEK_END) == 0) { sz = ftell(f); if (sz < 0) sz = 0; if (sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } rewind(f); } buf = (char *)malloc((size_t)(sz > 0 ? sz : 4096) + 1); if (!buf) { fclose(f); return NULL; } if (sz > 0) { n = fread(buf, 1, (size_t)sz, f); } else { size_t cap = 4096; n = 0; for (;;) { size_t got; if (n == cap) { char *np; cap *= 2; if (cap > 8 * 1024 * 1024) break; np = (char *)realloc(buf, cap + 1); if (!np) break; buf = np; } got = fread(buf + n, 1, cap - n, f); if (got == 0) break; n += got; } } buf[n] = '\0'; fclose(f); if (len) *len = n; return buf; } /* Containers with no init system: list /proc/ long-running daemons. */ #if defined(__linux__) static int collect_proc_daemons(void) { const char *root = getenv("SERVICES_MOCK_PROC_DIR"); DIR *d; struct dirent *de; double uptime_s = 0.0; if (!root || !*root) root = "/proc"; { char up[64]; char path[512]; FILE *f; snprintf(path, sizeof path, "%s/uptime", root); f = fopen(path, "r"); if (f) { if (fgets(up, sizeof up, f)) uptime_s = atof(up); fclose(f); } } if (uptime_s <= 0.0) return 0; d = opendir(root); if (!d) return 0; while ((de = readdir(d)) != NULL && g_count < MAX_SERVICES) { char path[1024], comm[NAME_SZ], statline[2048]; char *buf; size_t len = 0; int pid; unsigned long long start_ticks = 0; double started_at, age; long rss_pages = 0; if (!isdigit((unsigned char)de->d_name[0])) continue; pid = atoi(de->d_name); if (pid <= 0) continue; snprintf(path, sizeof path, "%s/%s/comm", root, de->d_name); comm[0] = '\0'; buf = read_file_all(path, &len); if (!buf) continue; str_copy(comm, sizeof comm, buf); free(buf); str_trim(comm); if (!comm[0]) continue; /* field 22 (1-based) of /stat is starttime; field 2 is "(comm)" * and may contain spaces, so scan from the last ')' first. */ snprintf(path, sizeof path, "%s/%s/stat", root, de->d_name); buf = read_file_all(path, &len); if (!buf) continue; str_copy(statline, sizeof statline, buf); free(buf); { char *rp = strrchr(statline, ')'); int fld = 2; char *q = rp ? rp + 1 : statline; while (*q) { while (*q == ' ') q++; if (!*q) break; fld++; if (fld == 22) { start_ticks = strtoull(q, NULL, 10); break; } while (*q && *q != ' ') q++; } } /* /statm field 2 is the resident set in pages. */ snprintf(path, sizeof path, "%s/%s/statm", root, de->d_name); buf = read_file_all(path, &len); if (buf) { long dummy = 0; if (sscanf(buf, "%ld %ld", &dummy, &rss_pages) != 2) rss_pages = 0; free(buf); } started_at = (double)start_ticks / 100.0; age = uptime_s - started_at; if (age < 300.0) continue; svc_add(comm, "process (no init system)", "running", "running", pid); { svc_t *s = &g_svc[g_count - 1]; s->mem = (unsigned long long)rss_pages * 4096ULL; str_copy(s->enabled, sizeof s->enabled, "-"); snprintf(s->since, sizeof s->since, "up %lds", (long)age); } } closedir(d); return g_count; } static void collect_systemd(void) { const char *mock = getenv("SERVICES_MOCK_SYSTEMCTL"); char *buf = NULL; size_t len = 0; static char out[OUT_SZ]; g_init = INIT_SYSTEMD; g_count = 0; if (mock && *mock) { buf = read_file_all(mock, &len); if (buf) { const char *p = buf; while (*p && isspace((unsigned char)*p)) p++; if (*p == '[') parse_json_units(buf); else parse_plain_units(buf); free(buf); } } else { if (capture("systemctl list-units --type=service --all --no-pager " "--plain --output=json 2>/dev/null", out, sizeof out) > 0) { const char *p = out; while (*p && isspace((unsigned char)*p)) p++; if (*p == '[') parse_json_units(out); else parse_plain_units(out); } if (g_count == 0) { if (capture("systemctl list-units --type=service --all --no-pager " "--plain 2>/dev/null", out, sizeof out) > 0) parse_plain_units(out); } if (g_count == 0) { if (capture("systemctl list-unit-files --type=service --no-pager " "--plain 2>/dev/null", out, sizeof out) > 0) parse_plain_units(out); } } /* One enrichment pass, only when we have real systemd output. */ if (g_count > 0) { const char *show_mock = getenv("SERVICES_MOCK_SYSTEMCTL_SHOW"); if (show_mock && *show_mock) { char *sb = read_file_all(show_mock, &len); if (sb) { apply_show(sb); free(sb); } } else if (!mock || !*mock) { /* `systemctl show --type=service --all` prints NOTHING on systemd * 249 (verified on the fleet): the --all/--type pair silently * selects an empty set, so the first live install reported 111 * units with pid 0 and enabled "-" for every one of them. Asking * for the units by name is the form that works everywhere, and * every name is re-validated before it goes into the command, in * batches small enough to stay well inside ARG_MAX. */ char *names[MAX_SERVICES]; int i, n_names = 0; for (i = 0; i < g_count; i++) { if (!valid_unit(g_svc[i].name)) continue; names[n_names++] = g_svc[i].name; } for (i = 0; i < n_names; i += 40) { char cmd[8192]; size_t used; int k, upto = i + 40; snprintf(cmd, sizeof cmd, "systemctl show -p Id -p MainPID -p ActiveEnterTimestamp " "-p MemoryCurrent -p UnitFileState -p ActiveState " "-p SubState -p Description 2>/dev/null"); used = strlen(cmd); if (upto > n_names) upto = n_names; for (k = i; k < upto && used + NAME_SZ + 2 < sizeof cmd; k++) { cmd[used++] = ' '; str_copy(cmd + used, sizeof cmd - used, names[k]); used += strlen(names[k]); cmd[used] = '\0'; } if (capture(cmd, out, sizeof out) > 0) apply_show(out); } } } } #endif /* __linux__ */ #endif /* !_WIN32 */ /* ------------------------------------------------------------------ */ /* Collection: launchd (macOS) */ /* ------------------------------------------------------------------ */ #if !defined(_WIN32) static void collect_launchd(void) { const char *mock = getenv("SERVICES_MOCK_LAUNCHCTL"); static char out[OUT_SZ]; char *buf = NULL; g_init = INIT_LAUNCHD; g_count = 0; if (mock && *mock) { buf = read_file_all(mock, NULL); if (buf) { str_copy(out, sizeof out, buf); free(buf); } } else if (capture("launchctl list 2>/dev/null", out, sizeof out) <= 0) { out[0] = '\0'; } { const char *p = out; int first = 1; while (p && *p) { const char *nl = strchr(p, '\n'); size_t len = nl ? (size_t)(nl - p) : strlen(p); char line[512]; char pid_s[32], st_s[32], label[NAME_SZ]; int pid = 0; if (len >= sizeof line) len = sizeof line - 1; memcpy(line, p, len); line[len] = '\0'; p = nl ? nl + 1 : p + strlen(p); if (first) { first = 0; if (strstr(line, "PID") && strstr(line, "Label")) continue; } pid_s[0] = st_s[0] = label[0] = '\0'; if (sscanf(line, "%31s %31s %191[^\n]", pid_s, st_s, label) < 3) continue; str_trim(label); if (!label[0]) continue; if (strcmp(pid_s, "-") != 0) pid = atoi(pid_s); /* launchd reports a job with no pid as "". A positive * value is a real exit code and means the job failed. A NEGATIVE * value is a signal: -9 (SIGKILL) and -15 (SIGTERM) are how launchd * reaps idle on-demand agents on memory pressure, so they are * "inactive", not failures - reporting 73 of those as failed would * make the board useless on a real Mac. Any other signal is a * crash and stays failed. */ if (pid > 0) { svc_add(label, "launchd job", "running", "running", pid); } else if (st_s[0] == '-') { int sig = atoi(st_s + 1); if (sig == 9 || sig == 15) svc_add(label, "launchd job", "inactive", "exited", 0); else svc_add(label, "launchd job", "failed", "failed", 0); } else if (st_s[0] && strcmp(st_s, "0") != 0) { svc_add(label, "launchd job", "failed", "failed", 0); } else { svc_add(label, "launchd job", "inactive", "exited", 0); } { svc_t *s = &g_svc[g_count - 1]; str_copy(s->enabled, sizeof s->enabled, "launchd"); if (strcmp(st_s, "0") != 0 && strcmp(pid_s, "-") == 0) snprintf(s->since, sizeof s->since, "last exit %s", st_s); else str_copy(s->since, sizeof s->since, "-"); } if (g_count >= MAX_SERVICES) break; } } /* Fill memory (and start time) from a single ps pass over the pids we did * get. Only digits ever reach the command line here. */ if (!mock || !*mock) { char pids[512]; size_t used = 0; int i; pids[0] = '\0'; for (i = 0; i < g_count; i++) { char tmp[16]; int n; if (g_svc[i].pid <= 0) continue; n = snprintf(tmp, sizeof tmp, "%s%d", used ? "," : "", g_svc[i].pid); if (n <= 0 || used + (size_t)n + 1 >= sizeof pids) break; memcpy(pids + used, tmp, (size_t)n); used += (size_t)n; pids[used] = '\0'; } if (used > 0) { char cmd[640]; snprintf(cmd, sizeof cmd, "ps -o pid=,rss=,lstart= -p %s 2>/dev/null", pids); if (capture(cmd, out, sizeof out) > 0) { char *line = out; while (line && *line) { char *nl = strchr(line, '\n'); int pid = 0; long rss = 0; int off = 0; svc_t *s; if (nl) *nl = '\0'; if (sscanf(line, "%d %ld %n", &pid, &rss, &off) >= 2 && pid > 0) { for (i = 0; i < g_count; i++) { if (g_svc[i].pid != pid) continue; s = &g_svc[i]; s->mem = (unsigned long long)rss * 1024ULL; if (off > 0 && (size_t)off < strlen(line) && strcmp(s->since, "-") == 0) { str_copy(s->since, sizeof s->since, line + off); str_trim(s->since); } break; } } line = nl ? nl + 1 : NULL; } } } } } #endif /* !_WIN32 */ /* ------------------------------------------------------------------ */ /* Collection: Windows SCM */ /* ------------------------------------------------------------------ */ #if defined(_WIN32) static void collect_scm(void) { SC_HANDLE scm; DWORD need = 0, got = 0, resume = 0; LPBYTE buf = NULL; g_init = INIT_SCM; g_count = 0; scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE); if (!scm) return; EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, NULL, 0, &need, &got, &resume, NULL); if (need > 0) { buf = (LPBYTE)malloc(need); if (buf) { if (EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, buf, need, &need, &got, &resume, NULL)) { LPENUM_SERVICE_STATUS_PROCESSA it = (LPENUM_SERVICE_STATUS_PROCESSA)buf; DWORD i; for (i = 0; i < got && g_count < MAX_SERVICES; i++) { const char *state = "stopped"; char sub[STATE_SZ]; char enabled[EN_SZ] = "-"; SC_HANDLE svc; LPQUERY_SERVICE_CONFIGA cfg; switch (it[i].ServiceStatusProcess.dwCurrentState) { case SERVICE_RUNNING: state = "running"; break; case SERVICE_STOPPED: state = "inactive"; break; case SERVICE_PAUSED: state = "paused"; break; case SERVICE_START_PENDING: state = "starting"; break; case SERVICE_STOP_PENDING: state = "stopping"; break; default: state = "unknown"; break; } snprintf(sub, sizeof sub, "%lu", (unsigned long)it[i].ServiceStatusProcess.dwCurrentState); svc_add(it[i].lpServiceName, it[i].lpDisplayName, state, sub, 0); { svc_t *s = &g_svc[g_count - 1]; s->pid = (int)it[i].ServiceStatusProcess.dwProcessId; svc = OpenServiceA(scm, it[i].lpServiceName, SERVICE_QUERY_CONFIG); if (svc) { DWORD cneed = 0; QueryServiceConfigA(svc, NULL, 0, &cneed); cfg = (LPQUERY_SERVICE_CONFIGA)malloc(cneed ? cneed : 1); if (cfg && QueryServiceConfigA(svc, cfg, cneed, &cneed)) { switch (cfg->dwStartType) { case SERVICE_AUTO_START: enabled[0] = 0; str_copy(enabled, sizeof enabled, "automatic"); break; case SERVICE_DEMAND_START: str_copy(enabled, sizeof enabled, "manual"); break; case SERVICE_DISABLED: str_copy(enabled, sizeof enabled, "disabled"); break; case SERVICE_BOOT_START: str_copy(enabled, sizeof enabled, "boot"); break; case SERVICE_SYSTEM_START: str_copy(enabled, sizeof enabled, "system"); break; default: str_copy(enabled, sizeof enabled, "-"); break; } } free(cfg); CloseServiceHandle(svc); } str_copy(s->enabled, sizeof s->enabled, enabled); str_copy(s->since, sizeof s->since, "-"); s->mem = 0; } } } free(buf); } } CloseServiceHandle(scm); } #endif /* ------------------------------------------------------------------ */ /* Collection dispatch + ordering */ /* ------------------------------------------------------------------ */ static int svc_failed(const svc_t *s) { return strcmp(s->active, "failed") == 0 || strcmp(s->sub, "failed") == 0; } static int svc_running(const svc_t *s) { return strcmp(s->active, "running") == 0 || strcmp(s->active, "active") == 0; } static int svc_cmp(const void *a, const void *b) { const svc_t *x = (const svc_t *)a; const svc_t *y = (const svc_t *)b; int fx = svc_failed(x), fy = svc_failed(y); int rx = svc_running(x), ry = svc_running(y); if (fx != fy) return fy - fx; /* failed first */ if (rx != ry) return ry - rx; /* then running */ return strcmp(x->name, y->name); } static const char *init_name(void) { switch (g_init) { case INIT_SYSTEMD: return "systemd"; case INIT_LAUNCHD: return "launchd"; case INIT_SCM: return "windows-scm"; default: return "none"; } } static void collect_all(void) { const char *allow = getenv("SERVICES_ALLOW_CONTROL"); #if defined(__linux__) const char *force = getenv("SERVICES_FORCE_INIT"); #endif g_control = (allow && *allow && strcmp(allow, "0") != 0); g_count = 0; #if defined(_WIN32) collect_scm(); #elif defined(__APPLE__) collect_launchd(); #else if (getenv("SERVICES_MOCK_LAUNCHCTL")) { collect_launchd(); /* fixture-driven launchd path on any host */ } else if (force && strcmp(force, "none") == 0) { g_init = INIT_NONE; collect_proc_daemons(); } else if (getenv("SERVICES_MOCK_SYSTEMCTL")) { collect_systemd(); } else if (access("/run/systemd/system", F_OK) == 0) { collect_systemd(); } else { g_init = INIT_NONE; if (collect_proc_daemons() == 0) g_count = 0; } #endif if (g_count > 1) qsort(g_svc, (size_t)g_count, sizeof(svc_t), svc_cmp); } /* ------------------------------------------------------------------ */ /* JSON output */ /* ------------------------------------------------------------------ */ static void mem_json(buf_t *b, unsigned long long v) { char tmp[32]; if (v == 0) { buf_puts(b, "null"); return; } snprintf(tmp, sizeof tmp, "%llu", v); buf_puts(b, tmp); } static void emit_service(buf_t *b, const svc_t *s) { buf_puts(b, "{\"name\":"); json_into(b, s->name); buf_puts(b, ",\"description\":"); json_into(b, s->desc); buf_puts(b, ",\"active\":"); json_into(b, s->active); buf_puts(b, ",\"sub\":"); json_into(b, s->sub); buf_puts(b, ",\"enabled\":"); json_into(b, s->enabled); buf_puts(b, ",\"pid\":"); { char tmp[32]; snprintf(tmp, sizeof tmp, "%d", s->pid); buf_puts(b, tmp); } buf_puts(b, ",\"memory_bytes\":"); mem_json(b, s->mem); buf_puts(b, ",\"since\":"); json_into(b, s->since); buf_puts(b, ",\"failed\":"); buf_puts(b, svc_failed(s) ? "true" : "false"); buf_putc(b, '}'); } static void print_json_header(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } /* ------------------------------------------------------------------ */ /* HTML */ /* ------------------------------------------------------------------ */ /* Split UI_HTML on the two control-byte placeholders and expand them into the * theme macros, so the page and the bot palette can never drift apart. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } static int mode_html(void) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); return 0; } /* ------------------------------------------------------------------ */ /* Control */ /* ------------------------------------------------------------------ */ static int do_control(const char *unit, const char *op) { if (!valid_unit(unit)) return 400; if (!g_control) return 403; if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && strcmp(op, "restart") != 0) return 400; { const char *logp = getenv("SERVICES_MOCK_SYSTEMCTL_LOG"); if (logp && *logp) { FILE *f = fopen(logp, "a"); if (f) { fprintf(f, "systemctl %s %s\n", op, unit); fclose(f); } return 0; } } #if defined(_WIN32) { SC_HANDLE scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT); SC_HANDLE svc; int rc = 500; if (!scm) return 500; svc = OpenServiceA(scm, unit, strcmp(op, "stop") == 0 ? SERVICE_STOP : (SERVICE_START | SERVICE_STOP)); if (!svc) { CloseServiceHandle(scm); return 404; } if (strcmp(op, "start") == 0) { if (StartServiceA(svc, 0, NULL)) rc = 0; else if (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) rc = 0; } else { SERVICE_STATUS st; if (ControlService(svc, SERVICE_CONTROL_STOP, &st)) rc = 0; else if (GetLastError() == ERROR_SERVICE_NOT_ACTIVE) rc = 0; } CloseServiceHandle(svc); CloseServiceHandle(scm); return rc; } #elif defined(__APPLE__) { char *argv[4]; int rc; argv[0] = (char *)"launchctl"; argv[1] = (char *)(strcmp(op, "stop") == 0 ? "stop" : "kickstart"); argv[2] = (char *)("-k"); argv[3] = (char *)unit; if (strcmp(op, "stop") == 0) { argv[2] = (char *)unit; argv[3] = NULL; } rc = run_argv(argv); return rc == 0 ? 0 : 500; } #else { char *argv[4]; int rc; argv[0] = (char *)"systemctl"; argv[1] = (char *)op; argv[2] = (char *)unit; argv[3] = NULL; rc = run_argv(argv); return rc == 0 ? 0 : 500; } #endif } /* ------------------------------------------------------------------ */ /* API dispatch */ /* ------------------------------------------------------------------ */ static void err_json(int code, const char *status, const char *msg) { printf("Status: %d %s\r\n", code, status); print_json_header(); printf("{\"ok\":false,\"error\":\"%s\"}\n", msg); } static int mode_json(const char *qs) { char action[64]; char filter[32]; char unit[256]; char op[32]; action[0] = filter[0] = unit[0] = op[0] = '\0'; get_query_val(qs, "action", action, sizeof action); get_query_val(qs, "filter", filter, sizeof filter); get_query_val(qs, "unit", unit, sizeof unit); get_query_val(qs, "op", op, sizeof op); if (!action[0]) str_copy(action, sizeof action, "list"); collect_all(); if (strcmp(action, "list") == 0) { buf_t b = { 0 }; int i, shown = 0; int running = 0, failed = 0, inactive = 0; for (i = 0; i < g_count; i++) { if (svc_running(&g_svc[i])) running++; else if (svc_failed(&g_svc[i])) failed++; else inactive++; } print_json_header(); buf_puts(&b, "{\"ok\":true,\"init_system\":"); json_into(&b, init_name()); buf_puts(&b, ",\"control_enabled\":"); buf_puts(&b, g_control ? "true" : "false"); { buf_t body; char tmp[32]; memset(&body, 0, sizeof body); for (i = 0; i < g_count; i++) { const svc_t *s = &g_svc[i]; int keep = 1; if (filter[0] && strcmp(filter, "all") != 0) { if (strcmp(filter, "failed") == 0) keep = svc_failed(s); else if (strcmp(filter, "running") == 0) keep = svc_running(s); else if (strcmp(filter, "inactive") == 0) keep = !svc_running(s) && !svc_failed(s); } if (!keep) continue; if (shown) buf_putc(&body, ','); emit_service(&body, s); shown++; } buf_puts(&b, ",\"count\":"); snprintf(tmp, sizeof tmp, "%d", shown); buf_puts(&b, tmp); buf_puts(&b, ",\"summary\":{\"running\":"); snprintf(tmp, sizeof tmp, "%d", running); buf_puts(&b, tmp); buf_puts(&b, ",\"failed\":"); snprintf(tmp, sizeof tmp, "%d", failed); buf_puts(&b, tmp); buf_puts(&b, ",\"inactive\":"); snprintf(tmp, sizeof tmp, "%d", inactive); buf_puts(&b, tmp); buf_puts(&b, "},\"services\":["); buf_add(&b, buf_str(&body), body.n); buf_puts(&b, "]}\n"); buf_free(&body); } fwrite(buf_str(&b), 1, b.n, stdout); buf_free(&b); return 0; } if (strcmp(action, "show") == 0) { svc_t *s; buf_t b = { 0 }; if (!unit[0]) { err_json(400, "Bad Request", "missing unit"); return 0; } if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } s = svc_find(unit); if (!s) { err_json(404, "Not Found", "service not found"); return 0; } print_json_header(); buf_puts(&b, "{\"ok\":true,\"init_system\":"); json_into(&b, init_name()); buf_puts(&b, ",\"control_enabled\":"); buf_puts(&b, g_control ? "true" : "false"); buf_puts(&b, ",\"service\":"); emit_service(&b, s); buf_puts(&b, "}\n"); fwrite(buf_str(&b), 1, b.n, stdout); buf_free(&b); return 0; } if (strcmp(action, "control") == 0) { int rc; /* Refuse by capability before by method: a node that never opted into * control must not advertise a 405 that implies the route works. */ if (!g_control) { err_json(403, "Forbidden", "control_disabled"); return 0; } if (!is_post_request()) { err_json(405, "Method Not Allowed", "control requires POST"); return 0; } if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && strcmp(op, "restart") != 0) { err_json(400, "Bad Request", "op must be start|stop|restart"); return 0; } rc = do_control(unit, op); if (rc == 403) { err_json(403, "Forbidden", "control_disabled"); return 0; } if (rc == 400) { err_json(400, "Bad Request", "invalid request"); return 0; } if (rc == 404) { err_json(404, "Not Found", "service not found"); return 0; } if (rc != 0) { err_json(500, "Internal Server Error", "control failed"); return 0; } print_json_header(); printf("{\"ok\":true,\"unit\":\"%s\",\"op\":\"%s\"," "\"control_enabled\":true,\"init_system\":\"%s\"}\n", unit, op, init_name()); return 0; } err_json(400, "Bad Request", "unknown action"); return 0; } static int mode_meta(void) { printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); return 0; } int main(int argc, char **argv) { const char *qs; if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) return mode_meta(); if (argc > 1 && strcmp(argv[1], "--version") == 0) { printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); return 0; } require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) return mode_json(qs); return mode_html(); }