| 1 | /* |
| 2 | * plugin_services - SCORPIOX BOT open-source local service status board |
| 3 | * |
| 4 | * One clean-room C99 binary, three modes: |
| 5 | * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata |
| 6 | * 2. ?action=list|show|control / ?format=json / POST -> JSON node API |
| 7 | * 3. GET (default) -> responsive HTML board |
| 8 | * |
| 9 | * It reports every service the node's init system knows about: |
| 10 | * |
| 11 | * Linux systemd via `systemctl list-units --output=json` (falls back to the |
| 12 | * plain table on systemd < 248), enriched by `systemctl show -p ...` |
| 13 | * over the validated unit names. Inside a |
| 14 | * container with no init system (no /run/systemd/system) it reports |
| 15 | * init_system:"none" and lists the long-running daemons it can see in |
| 16 | * /proc instead of pretending the node has none. |
| 17 | * macOS `launchctl list` (pid / status / label), with memory and uptime |
| 18 | * filled in from one `ps` pass over the returned pids. |
| 19 | * Windows OpenSCManagerA + EnumServicesStatusExA and QueryServiceConfigA. |
| 20 | * No shell, no popen, no service name ever reaches a command line. |
| 21 | * |
| 22 | * Read-only by default. start/stop/restart exist only when the node operator |
| 23 | * sets SERVICES_ALLOW_CONTROL=1, requires node auth, and every unit name is |
| 24 | * validated against [A-Za-z0-9@._:-]{1,160} before it is handed to execvp as a |
| 25 | * separate argv element (POSIX) or the SCM (Windows). No unit name is ever |
| 26 | * interpolated into a shell string, so `a;reboot` is a 400, not a shell escape. |
| 27 | * |
| 28 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 29 | * x86_64-w64-mingw32-gcc -static. |
| 30 | * |
| 31 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 32 | */ |
| 33 | |
| 34 | /* Must be the very first thing: advapi32's EnumServicesStatusExA and |
| 35 | * QueryServiceConfigA are gated on _WIN32_WINNT, and MinGW defaults to 0x502 |
| 36 | * (Server 2003) which hides them. */ |
| 37 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 38 | # define _WIN32_WINNT 0x0601 |
| 39 | #endif |
| 40 | |
| 41 | #if !defined(_WIN32) |
| 42 | # define _POSIX_C_SOURCE 200809L |
| 43 | # define _DEFAULT_SOURCE 1 |
| 44 | # if defined(__APPLE__) |
| 45 | # define _DARWIN_C_SOURCE 1 |
| 46 | # endif |
| 47 | #endif |
| 48 | |
| 49 | #include <stdio.h> |
| 50 | #include <stdlib.h> |
| 51 | #include <string.h> |
| 52 | #include <ctype.h> |
| 53 | #include <errno.h> |
| 54 | #include <time.h> |
| 55 | |
| 56 | #if defined(_WIN32) |
| 57 | # define WIN32_LEAN_AND_MEAN |
| 58 | # include <windows.h> |
| 59 | # define sx_popen _popen |
| 60 | # define sx_pclose _pclose |
| 61 | #else |
| 62 | # include <unistd.h> |
| 63 | # include <dirent.h> |
| 64 | # include <sys/types.h> |
| 65 | # include <sys/wait.h> |
| 66 | # define sx_popen popen |
| 67 | # define sx_pclose pclose |
| 68 | #endif |
| 69 | |
| 70 | #include "bot_theme_plugin.h" |
| 71 | #include "ui_html.h" |
| 72 | |
| 73 | #define PLUGIN_SLUG "services" |
| 74 | #define PLUGIN_ID "plugin_services" |
| 75 | #define PLUGIN_VER "1.0.1" |
| 76 | |
| 77 | #define PLUGIN_NAME "services" |
| 78 | #define PLUGIN_DESC "System services" |
| 79 | |
| 80 | #define MAX_SERVICES 2048 |
| 81 | #define NAME_SZ 192 |
| 82 | #define DESC_SZ 192 |
| 83 | #define STATE_SZ 32 |
| 84 | #define EN_SZ 32 |
| 85 | #define OUT_SZ (1024 * 1024) |
| 86 | |
| 87 | /* init systems */ |
| 88 | #define INIT_NONE 0 |
| 89 | #define INIT_SYSTEMD 1 |
| 90 | #define INIT_LAUNCHD 2 |
| 91 | #define INIT_SCM 3 |
| 92 | |
| 93 | typedef struct { |
| 94 | char name[NAME_SZ]; /* unit / label / service name */ |
| 95 | char desc[DESC_SZ]; |
| 96 | char active[STATE_SZ]; /* active | inactive | failed | running | stopped */ |
| 97 | char sub[STATE_SZ]; /* running | dead | exited | ... */ |
| 98 | char enabled[EN_SZ]; /* enabled | disabled | static | - */ |
| 99 | int pid; |
| 100 | unsigned long long mem; /* bytes, 0 = unknown */ |
| 101 | char since[40]; |
| 102 | } svc_t; |
| 103 | |
| 104 | static svc_t g_svc[MAX_SERVICES]; |
| 105 | static int g_count; |
| 106 | static int g_init = INIT_NONE; |
| 107 | static int g_control = 0; |
| 108 | |
| 109 | /* ------------------------------------------------------------------ */ |
| 110 | /* Growable output buffer */ |
| 111 | /* ------------------------------------------------------------------ */ |
| 112 | |
| 113 | typedef struct { char *p; size_t n, cap; } buf_t; |
| 114 | |
| 115 | static int buf_need(buf_t *b, size_t extra) |
| 116 | { |
| 117 | size_t want; |
| 118 | char *np; |
| 119 | if (b->n + extra + 1 <= b->cap) return 1; |
| 120 | want = b->cap ? b->cap : 4096; |
| 121 | while (want < b->n + extra + 1) want *= 2; |
| 122 | np = (char *)realloc(b->p, want); |
| 123 | if (!np) return 0; |
| 124 | b->p = np; |
| 125 | b->cap = want; |
| 126 | return 1; |
| 127 | } |
| 128 | |
| 129 | static void buf_add(buf_t *b, const char *s, size_t n) |
| 130 | { |
| 131 | if (!b || !s) return; |
| 132 | if (!buf_need(b, n)) return; |
| 133 | memcpy(b->p + b->n, s, n); |
| 134 | b->n += n; |
| 135 | b->p[b->n] = '\0'; |
| 136 | } |
| 137 | |
| 138 | static void buf_puts(buf_t *b, const char *s) |
| 139 | { |
| 140 | if (s) buf_add(b, s, strlen(s)); |
| 141 | } |
| 142 | |
| 143 | static void buf_putc(buf_t *b, char c) { buf_add(b, &c, 1); } |
| 144 | |
| 145 | static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } |
| 146 | |
| 147 | static void buf_free(buf_t *b) |
| 148 | { |
| 149 | if (b) { free(b->p); b->p = NULL; b->n = b->cap = 0; } |
| 150 | } |
| 151 | |
| 152 | /* JSON string escaping into a buffer. */ |
| 153 | static void json_into(buf_t *b, const char *s) |
| 154 | { |
| 155 | buf_putc(b, '"'); |
| 156 | for (; s && *s; s++) { |
| 157 | unsigned char c = (unsigned char)*s; |
| 158 | switch (c) { |
| 159 | case '"': buf_puts(b, "\\\""); break; |
| 160 | case '\\': buf_puts(b, "\\\\"); break; |
| 161 | case '\n': buf_puts(b, "\\n"); break; |
| 162 | case '\r': buf_puts(b, "\\r"); break; |
| 163 | case '\t': buf_puts(b, "\\t"); break; |
| 164 | default: |
| 165 | if (c < 0x20) { |
| 166 | char tmp[8]; |
| 167 | snprintf(tmp, sizeof tmp, "\\u%04x", c); |
| 168 | buf_puts(b, tmp); |
| 169 | } else { |
| 170 | buf_putc(b, (char)c); |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | buf_putc(b, '"'); |
| 175 | } |
| 176 | |
| 177 | /* ------------------------------------------------------------------ */ |
| 178 | /* Small string utilities */ |
| 179 | /* ------------------------------------------------------------------ */ |
| 180 | |
| 181 | static void str_copy(char *dst, size_t sz, const char *src) |
| 182 | { |
| 183 | size_t n; |
| 184 | if (!dst || sz == 0) return; |
| 185 | if (!src) { dst[0] = '\0'; return; } |
| 186 | n = strlen(src); |
| 187 | if (n >= sz) n = sz - 1; |
| 188 | memcpy(dst, src, n); |
| 189 | dst[n] = '\0'; |
| 190 | } |
| 191 | |
| 192 | #if !defined(_WIN32) |
| 193 | static void str_trim(char *s) |
| 194 | { |
| 195 | char *p; |
| 196 | size_t n; |
| 197 | if (!s) return; |
| 198 | p = s; |
| 199 | while (*p && isspace((unsigned char)*p)) p++; |
| 200 | if (p != s) memmove(s, p, strlen(p) + 1); |
| 201 | n = strlen(s); |
| 202 | while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; |
| 203 | } |
| 204 | #endif |
| 205 | |
| 206 | static void url_decode(char *s) |
| 207 | { |
| 208 | char *o = s; |
| 209 | if (!s) return; |
| 210 | while (*s) { |
| 211 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 212 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 213 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 214 | *o++ = (char)((hi << 4) | lo); |
| 215 | s += 3; |
| 216 | } else if (*s == '+') { |
| 217 | *o++ = ' '; |
| 218 | s++; |
| 219 | } else { |
| 220 | *o++ = *s++; |
| 221 | } |
| 222 | } |
| 223 | *o = '\0'; |
| 224 | } |
| 225 | |
| 226 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 227 | { |
| 228 | size_t klen; |
| 229 | const char *p; |
| 230 | |
| 231 | if (!out || outsz == 0) return 0; |
| 232 | out[0] = '\0'; |
| 233 | if (!qs || !key) return 0; |
| 234 | klen = strlen(key); |
| 235 | |
| 236 | for (p = qs; *p; ) { |
| 237 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 238 | const char *v = p + klen + 1; |
| 239 | size_t i = 0; |
| 240 | while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; |
| 241 | out[i] = '\0'; |
| 242 | url_decode(out); |
| 243 | return 1; |
| 244 | } |
| 245 | p = strchr(p, '&'); |
| 246 | if (!p) break; |
| 247 | p++; |
| 248 | } |
| 249 | return 0; |
| 250 | } |
| 251 | |
| 252 | /* Unit / label / service name allowlist. Anything that could be read as shell |
| 253 | * syntax, a path, or an option is rejected outright. */ |
| 254 | static int valid_unit(const char *s) |
| 255 | { |
| 256 | size_t n; |
| 257 | if (!s) return 0; |
| 258 | n = strlen(s); |
| 259 | if (n < 1 || n > 160) return 0; |
| 260 | for (; *s; s++) { |
| 261 | unsigned char c = (unsigned char)*s; |
| 262 | if (isalnum(c)) continue; |
| 263 | if (c == '@' || c == '.' || c == '_' || c == ':' || c == '-' || c == '\\') |
| 264 | continue; |
| 265 | return 0; |
| 266 | } |
| 267 | return 1; |
| 268 | } |
| 269 | |
| 270 | static int is_post_request(void) |
| 271 | { |
| 272 | const char *m = getenv("REQUEST_METHOD"); |
| 273 | return m && strcmp(m, "POST") == 0; |
| 274 | } |
| 275 | |
| 276 | /* ------------------------------------------------------------------ */ |
| 277 | /* Node authentication */ |
| 278 | /* ------------------------------------------------------------------ */ |
| 279 | |
| 280 | static void require_node_auth(void) |
| 281 | { |
| 282 | const char *np = getenv("BOT_PASSWORD"); |
| 283 | const char *xp; |
| 284 | const char *auth; |
| 285 | const char *qs; |
| 286 | char qpwd[256]; |
| 287 | |
| 288 | if (!np || !*np) return; |
| 289 | |
| 290 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 291 | if (xp && strcmp(xp, np) == 0) return; |
| 292 | |
| 293 | auth = getenv("HTTP_AUTHORIZATION"); |
| 294 | if (auth) { |
| 295 | while (*auth == ' ') auth++; |
| 296 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 297 | auth += 7; |
| 298 | while (*auth == ' ') auth++; |
| 299 | if (strcmp(auth, np) == 0) return; |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | qs = getenv("QUERY_STRING"); |
| 304 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 305 | return; |
| 306 | |
| 307 | fputs("Status: 401 Unauthorized\r\n" |
| 308 | "Content-Type: application/json; charset=utf-8\r\n" |
| 309 | "Cache-Control: no-store\r\n" |
| 310 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 311 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 312 | exit(0); |
| 313 | } |
| 314 | |
| 315 | /* ------------------------------------------------------------------ */ |
| 316 | /* Command capture and argv execution */ |
| 317 | /* ------------------------------------------------------------------ */ |
| 318 | |
| 319 | #if !defined(_WIN32) |
| 320 | /* Every command string passed here is a CONSTANT defined in this file, or is |
| 321 | * built from a value that already passed valid_unit(). Nothing user-supplied |
| 322 | * reaches this function unvalidated. */ |
| 323 | static int capture(const char *cmd, char *out, size_t outsz) |
| 324 | { |
| 325 | FILE *f; |
| 326 | size_t n; |
| 327 | |
| 328 | if (!out || outsz == 0) return -1; |
| 329 | out[0] = '\0'; |
| 330 | f = sx_popen(cmd, "r"); |
| 331 | if (!f) return -1; |
| 332 | n = fread(out, 1, outsz - 1, f); |
| 333 | out[n] = '\0'; |
| 334 | if (sx_pclose(f) != 0) { |
| 335 | /* still return what we read: callers check for emptiness */ |
| 336 | } |
| 337 | return (int)n; |
| 338 | } |
| 339 | |
| 340 | /* Returns the child's exit status, or -1 when it could not be started. The |
| 341 | * unit is a separate argv element, so no shell ever sees it. */ |
| 342 | static int run_argv(char *const argv[]) |
| 343 | { |
| 344 | pid_t pid; |
| 345 | int st = 0; |
| 346 | |
| 347 | pid = fork(); |
| 348 | if (pid < 0) return -1; |
| 349 | if (pid == 0) { |
| 350 | execvp(argv[0], argv); |
| 351 | _exit(127); |
| 352 | } |
| 353 | if (waitpid(pid, &st, 0) < 0) return -1; |
| 354 | if (WIFEXITED(st)) return WEXITSTATUS(st); |
| 355 | return -1; |
| 356 | } |
| 357 | #endif |
| 358 | |
| 359 | /* ------------------------------------------------------------------ */ |
| 360 | /* Service table helpers (all platforms) */ |
| 361 | /* ------------------------------------------------------------------ */ |
| 362 | |
| 363 | static void svc_add(const char *name, const char *desc, const char *active, |
| 364 | const char *sub, int pid) |
| 365 | { |
| 366 | svc_t *s; |
| 367 | if (g_count >= MAX_SERVICES) return; |
| 368 | s = &g_svc[g_count++]; |
| 369 | memset(s, 0, sizeof *s); |
| 370 | str_copy(s->name, sizeof s->name, name); |
| 371 | str_copy(s->desc, sizeof s->desc, desc); |
| 372 | str_copy(s->active, sizeof s->active, active); |
| 373 | str_copy(s->sub, sizeof s->sub, sub); |
| 374 | str_copy(s->enabled, sizeof s->enabled, "-"); |
| 375 | str_copy(s->since, sizeof s->since, "-"); |
| 376 | s->pid = pid; |
| 377 | } |
| 378 | |
| 379 | static svc_t *svc_find(const char *name) |
| 380 | { |
| 381 | int i; |
| 382 | if (!name) return NULL; |
| 383 | for (i = 0; i < g_count; i++) |
| 384 | if (strcmp(g_svc[i].name, name) == 0) return &g_svc[i]; |
| 385 | return NULL; |
| 386 | } |
| 387 | |
| 388 | /* ------------------------------------------------------------------ */ |
| 389 | /* Minimal JSON field extraction (for systemctl --output=json output) */ |
| 390 | /* ------------------------------------------------------------------ */ |
| 391 | /* The JSON readers and the systemd text parsers are Linux-only: macOS has |
| 392 | * launchd and the Windows slice talks to the SCM, so neither parses text. */ |
| 393 | #if defined(__linux__) |
| 394 | |
| 395 | static int json_read_string_at(const char **pp, char *out, size_t outsz) |
| 396 | { |
| 397 | const char *p = *pp; |
| 398 | size_t i = 0; |
| 399 | |
| 400 | if (!p || *p != '"') return 0; |
| 401 | p++; |
| 402 | while (*p && *p != '"') { |
| 403 | char c = *p; |
| 404 | if (c == '\\' && p[1]) { |
| 405 | p++; |
| 406 | switch (*p) { |
| 407 | case 'n': c = '\n'; break; |
| 408 | case 'r': c = '\r'; break; |
| 409 | case 't': c = '\t'; break; |
| 410 | case 'b': c = '\b'; break; |
| 411 | case 'f': c = '\f'; break; |
| 412 | case 'u': { |
| 413 | /* keep it simple: decode the low byte of the code point */ |
| 414 | unsigned int v = 0; |
| 415 | int k; |
| 416 | p++; |
| 417 | for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) { |
| 418 | v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) |
| 419 | ? *p - '0' |
| 420 | : tolower((unsigned char)*p) - 'a' + 10); |
| 421 | } |
| 422 | if (i + 1 < outsz) out[i++] = (char)(v & 0xff); |
| 423 | continue; |
| 424 | } |
| 425 | default: c = *p; break; |
| 426 | } |
| 427 | p++; |
| 428 | } else { |
| 429 | p++; |
| 430 | } |
| 431 | if (i + 1 < outsz) out[i++] = c; |
| 432 | } |
| 433 | if (*p == '"') p++; |
| 434 | out[i] = '\0'; |
| 435 | *pp = p; |
| 436 | return 1; |
| 437 | } |
| 438 | |
| 439 | /* Find "key":"value" inside one flat object slice [obj, obj_end). */ |
| 440 | static int json_field(const char *obj, const char *end, const char *key, |
| 441 | char *out, size_t outsz) |
| 442 | { |
| 443 | size_t klen = strlen(key); |
| 444 | const char *p = obj; |
| 445 | |
| 446 | if (!out || outsz == 0) return 0; |
| 447 | out[0] = '\0'; |
| 448 | |
| 449 | while (p && p < end) { |
| 450 | if (*p == '"' && (size_t)(end - p) > klen + 1 && |
| 451 | strncmp(p + 1, key, klen) == 0 && p[1 + klen] == '"') { |
| 452 | const char *q = p + klen + 2; |
| 453 | while (q < end && isspace((unsigned char)*q)) q++; |
| 454 | if (q < end && *q == ':') { |
| 455 | q++; |
| 456 | while (q < end && isspace((unsigned char)*q)) q++; |
| 457 | if (q < end && *q == '"') |
| 458 | return json_read_string_at(&q, out, outsz); |
| 459 | if (q < end) { |
| 460 | size_t i = 0; |
| 461 | while (q < end && *q != ',' && *q != '}' && |
| 462 | i + 1 < outsz) { |
| 463 | if (!isspace((unsigned char)*q)) out[i++] = *q; |
| 464 | q++; |
| 465 | } |
| 466 | out[i] = '\0'; |
| 467 | return 1; |
| 468 | } |
| 469 | } |
| 470 | return 0; |
| 471 | } |
| 472 | if (*p == '"') { |
| 473 | char tmp[8]; |
| 474 | const char *skip = p; |
| 475 | json_read_string_at(&skip, tmp, sizeof tmp); |
| 476 | p = skip; |
| 477 | continue; |
| 478 | } |
| 479 | p++; |
| 480 | } |
| 481 | return 0; |
| 482 | } |
| 483 | |
| 484 | /* ------------------------------------------------------------------ */ |
| 485 | /* Collection: systemd (Linux) */ |
| 486 | /* ------------------------------------------------------------------ */ |
| 487 | |
| 488 | /* Parse the systemctl --output=json array into g_svc. */ |
| 489 | static void parse_json_units(const char *json) |
| 490 | { |
| 491 | const char *p = json; |
| 492 | |
| 493 | while (p && *p) { |
| 494 | const char *start, *end; |
| 495 | char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ]; |
| 496 | char sub[STATE_SZ], desc[DESC_SZ]; |
| 497 | int depth = 0; |
| 498 | |
| 499 | start = strchr(p, '{'); |
| 500 | if (!start) break; |
| 501 | end = start; |
| 502 | while (*end) { |
| 503 | if (*end == '"') { |
| 504 | char tmp[2]; |
| 505 | json_read_string_at(&end, tmp, sizeof tmp); |
| 506 | continue; |
| 507 | } |
| 508 | if (*end == '{') depth++; |
| 509 | else if (*end == '}') { |
| 510 | depth--; |
| 511 | if (depth == 0) { end++; break; } |
| 512 | } |
| 513 | end++; |
| 514 | } |
| 515 | unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; |
| 516 | json_field(start, end, "unit", unit, sizeof unit); |
| 517 | json_field(start, end, "load", load, sizeof load); |
| 518 | json_field(start, end, "active", active, sizeof active); |
| 519 | json_field(start, end, "sub", sub, sizeof sub); |
| 520 | json_field(start, end, "description", desc, sizeof desc); |
| 521 | if (unit[0] && strcmp(load, "not-found") != 0) |
| 522 | svc_add(unit, desc, active, sub, 0); |
| 523 | p = end; |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | /* Parse the pre-248 plain table: |
| 528 | * UNIT LOAD ACTIVE SUB DESCRIPTION |
| 529 | * ssh.service loaded active running OpenBSD Secure Shell server |
| 530 | */ |
| 531 | static void parse_plain_units(const char *text) |
| 532 | { |
| 533 | const char *p = text; |
| 534 | |
| 535 | while (p && *p) { |
| 536 | const char *nl = strchr(p, '\n'); |
| 537 | size_t len = nl ? (size_t)(nl - p) : strlen(p); |
| 538 | char line[1024]; |
| 539 | char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ], sub[STATE_SZ]; |
| 540 | char desc[DESC_SZ]; |
| 541 | int n = 0, off = 0; |
| 542 | |
| 543 | if (len >= sizeof line) len = sizeof line - 1; |
| 544 | memcpy(line, p, len); |
| 545 | line[len] = '\0'; |
| 546 | p = nl ? nl + 1 : p + strlen(p); |
| 547 | |
| 548 | if (len < 4) continue; |
| 549 | if (strstr(line, "UNIT") && strstr(line, "LOAD")) continue; |
| 550 | if (strstr(line, "loaded units listed")) continue; |
| 551 | if (strstr(line, "To show all installed")) continue; |
| 552 | |
| 553 | unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; |
| 554 | n = sscanf(line, "%191s %31s %31s %31s %n", |
| 555 | unit, load, active, sub, &off); |
| 556 | if (n < 4) continue; |
| 557 | if (strcmp(load, "loaded") != 0 && strcmp(load, "not-found") != 0) continue; |
| 558 | if (strcmp(load, "not-found") == 0) continue; |
| 559 | if (off > 0 && (size_t)off < len) { |
| 560 | str_copy(desc, sizeof desc, line + off); |
| 561 | str_trim(desc); |
| 562 | } |
| 563 | if (!strchr(unit, '.')) continue; |
| 564 | svc_add(unit, desc, active, sub, 0); |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | /* Output of `systemctl show -p ...` over a batch of unit names, whose output is |
| 569 | * key=value blocks separated by a blank line. */ |
| 570 | static void apply_show(const char *text) |
| 571 | { |
| 572 | const char *p = text; |
| 573 | |
| 574 | while (p && *p) { |
| 575 | char name[NAME_SZ] = {0}, pid_s[24] = {0}, since[40] = {0}; |
| 576 | char mem_s[32] = {0}, file_state[EN_SZ] = {0}; |
| 577 | char active[STATE_SZ] = {0}, sub[STATE_SZ] = {0}, desc[DESC_SZ] = {0}; |
| 578 | svc_t *s; |
| 579 | |
| 580 | { |
| 581 | const char *nl = strstr(p, "\n\n"); |
| 582 | const char *end = nl ? nl : p + strlen(p); |
| 583 | const char *line = p; |
| 584 | while (line < end) { |
| 585 | const char *eol = strchr(line, '\n'); |
| 586 | if (!eol || eol > end) eol = end; |
| 587 | { |
| 588 | size_t l = (size_t)(eol - line); |
| 589 | char l2[512]; |
| 590 | char *eq; |
| 591 | if (l < sizeof l2) { |
| 592 | memcpy(l2, line, l); |
| 593 | l2[l] = '\0'; |
| 594 | eq = strchr(l2, '='); |
| 595 | if (eq) { |
| 596 | *eq++ = '\0'; |
| 597 | if (strcmp(l2, "Id") == 0) str_copy(name, sizeof name, eq); |
| 598 | else if (strcmp(l2, "MainPID") == 0) str_copy(pid_s, sizeof pid_s, eq); |
| 599 | else if (strcmp(l2, "ActiveEnterTimestamp") == 0) str_copy(since, sizeof since, eq); |
| 600 | else if (strcmp(l2, "MemoryCurrent") == 0) str_copy(mem_s, sizeof mem_s, eq); |
| 601 | else if (strcmp(l2, "UnitFileState") == 0) str_copy(file_state, sizeof file_state, eq); |
| 602 | else if (strcmp(l2, "ActiveState") == 0) str_copy(active, sizeof active, eq); |
| 603 | else if (strcmp(l2, "SubState") == 0) str_copy(sub, sizeof sub, eq); |
| 604 | else if (strcmp(l2, "Description") == 0) str_copy(desc, sizeof desc, eq); |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | line = eol < end ? eol + 1 : end; |
| 609 | } |
| 610 | p = nl ? nl + 2 : end; |
| 611 | } |
| 612 | |
| 613 | if (!name[0]) continue; |
| 614 | s = svc_find(name); |
| 615 | if (!s) { |
| 616 | if (desc[0] || active[0]) { |
| 617 | svc_add(name, desc, active, sub, 0); |
| 618 | s = svc_find(name); |
| 619 | } |
| 620 | } |
| 621 | if (!s) continue; |
| 622 | s->pid = atoi(pid_s); |
| 623 | if (mem_s[0] && strncmp(mem_s, "18446744073709551615", 20) != 0) |
| 624 | s->mem = strtoull(mem_s, NULL, 10); |
| 625 | if (file_state[0]) str_copy(s->enabled, sizeof s->enabled, file_state); |
| 626 | if (since[0] && strcmp(since, "n/a") != 0) { |
| 627 | str_copy(s->since, sizeof s->since, since); |
| 628 | } |
| 629 | if (active[0] && !s->active[0]) str_copy(s->active, sizeof s->active, active); |
| 630 | if (sub[0] && !s->sub[0]) str_copy(s->sub, sizeof s->sub, sub); |
| 631 | if (desc[0] && !s->desc[0]) str_copy(s->desc, sizeof s->desc, desc); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | #endif /* __linux__ */ |
| 636 | |
| 637 | #if !defined(_WIN32) |
| 638 | static char *read_file_all(const char *path, size_t *len) |
| 639 | { |
| 640 | FILE *f; |
| 641 | char *buf; |
| 642 | long sz; |
| 643 | size_t n; |
| 644 | |
| 645 | f = fopen(path, "rb"); |
| 646 | if (!f) return NULL; |
| 647 | sz = 0; |
| 648 | /* /proc files report st_size 0 and are not seekable, so only trust the |
| 649 | * size when the seek actually works; otherwise read until EOF. */ |
| 650 | if (fseek(f, 0, SEEK_END) == 0) { |
| 651 | sz = ftell(f); |
| 652 | if (sz < 0) sz = 0; |
| 653 | if (sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } |
| 654 | rewind(f); |
| 655 | } |
| 656 | buf = (char *)malloc((size_t)(sz > 0 ? sz : 4096) + 1); |
| 657 | if (!buf) { fclose(f); return NULL; } |
| 658 | if (sz > 0) { |
| 659 | n = fread(buf, 1, (size_t)sz, f); |
| 660 | } else { |
| 661 | size_t cap = 4096; |
| 662 | n = 0; |
| 663 | for (;;) { |
| 664 | size_t got; |
| 665 | if (n == cap) { |
| 666 | char *np; |
| 667 | cap *= 2; |
| 668 | if (cap > 8 * 1024 * 1024) break; |
| 669 | np = (char *)realloc(buf, cap + 1); |
| 670 | if (!np) break; |
| 671 | buf = np; |
| 672 | } |
| 673 | got = fread(buf + n, 1, cap - n, f); |
| 674 | if (got == 0) break; |
| 675 | n += got; |
| 676 | } |
| 677 | } |
| 678 | buf[n] = '\0'; |
| 679 | fclose(f); |
| 680 | if (len) *len = n; |
| 681 | return buf; |
| 682 | } |
| 683 | |
| 684 | /* Containers with no init system: list /proc/<pid> long-running daemons. */ |
| 685 | #if defined(__linux__) |
| 686 | static int collect_proc_daemons(void) |
| 687 | { |
| 688 | const char *root = getenv("SERVICES_MOCK_PROC_DIR"); |
| 689 | DIR *d; |
| 690 | struct dirent *de; |
| 691 | double uptime_s = 0.0; |
| 692 | |
| 693 | if (!root || !*root) root = "/proc"; |
| 694 | |
| 695 | { |
| 696 | char up[64]; |
| 697 | char path[512]; |
| 698 | FILE *f; |
| 699 | snprintf(path, sizeof path, "%s/uptime", root); |
| 700 | f = fopen(path, "r"); |
| 701 | if (f) { |
| 702 | if (fgets(up, sizeof up, f)) uptime_s = atof(up); |
| 703 | fclose(f); |
| 704 | } |
| 705 | } |
| 706 | if (uptime_s <= 0.0) return 0; |
| 707 | |
| 708 | d = opendir(root); |
| 709 | if (!d) return 0; |
| 710 | while ((de = readdir(d)) != NULL && g_count < MAX_SERVICES) { |
| 711 | char path[1024], comm[NAME_SZ], statline[2048]; |
| 712 | char *buf; |
| 713 | size_t len = 0; |
| 714 | int pid; |
| 715 | unsigned long long start_ticks = 0; |
| 716 | double started_at, age; |
| 717 | long rss_pages = 0; |
| 718 | |
| 719 | if (!isdigit((unsigned char)de->d_name[0])) continue; |
| 720 | pid = atoi(de->d_name); |
| 721 | if (pid <= 0) continue; |
| 722 | |
| 723 | snprintf(path, sizeof path, "%s/%s/comm", root, de->d_name); |
| 724 | comm[0] = '\0'; |
| 725 | buf = read_file_all(path, &len); |
| 726 | if (!buf) continue; |
| 727 | str_copy(comm, sizeof comm, buf); |
| 728 | free(buf); |
| 729 | str_trim(comm); |
| 730 | if (!comm[0]) continue; |
| 731 | |
| 732 | /* field 22 (1-based) of <pid>/stat is starttime; field 2 is "(comm)" |
| 733 | * and may contain spaces, so scan from the last ')' first. */ |
| 734 | snprintf(path, sizeof path, "%s/%s/stat", root, de->d_name); |
| 735 | buf = read_file_all(path, &len); |
| 736 | if (!buf) continue; |
| 737 | str_copy(statline, sizeof statline, buf); |
| 738 | free(buf); |
| 739 | { |
| 740 | char *rp = strrchr(statline, ')'); |
| 741 | int fld = 2; |
| 742 | char *q = rp ? rp + 1 : statline; |
| 743 | while (*q) { |
| 744 | while (*q == ' ') q++; |
| 745 | if (!*q) break; |
| 746 | fld++; |
| 747 | if (fld == 22) { start_ticks = strtoull(q, NULL, 10); break; } |
| 748 | while (*q && *q != ' ') q++; |
| 749 | } |
| 750 | } |
| 751 | |
| 752 | /* <pid>/statm field 2 is the resident set in pages. */ |
| 753 | snprintf(path, sizeof path, "%s/%s/statm", root, de->d_name); |
| 754 | buf = read_file_all(path, &len); |
| 755 | if (buf) { |
| 756 | long dummy = 0; |
| 757 | if (sscanf(buf, "%ld %ld", &dummy, &rss_pages) != 2) rss_pages = 0; |
| 758 | free(buf); |
| 759 | } |
| 760 | |
| 761 | started_at = (double)start_ticks / 100.0; |
| 762 | age = uptime_s - started_at; |
| 763 | if (age < 300.0) continue; |
| 764 | |
| 765 | svc_add(comm, "process (no init system)", "running", "running", pid); |
| 766 | { |
| 767 | svc_t *s = &g_svc[g_count - 1]; |
| 768 | s->mem = (unsigned long long)rss_pages * 4096ULL; |
| 769 | str_copy(s->enabled, sizeof s->enabled, "-"); |
| 770 | snprintf(s->since, sizeof s->since, "up %lds", (long)age); |
| 771 | } |
| 772 | } |
| 773 | closedir(d); |
| 774 | return g_count; |
| 775 | } |
| 776 | |
| 777 | static void collect_systemd(void) |
| 778 | { |
| 779 | const char *mock = getenv("SERVICES_MOCK_SYSTEMCTL"); |
| 780 | char *buf = NULL; |
| 781 | size_t len = 0; |
| 782 | static char out[OUT_SZ]; |
| 783 | |
| 784 | g_init = INIT_SYSTEMD; |
| 785 | g_count = 0; |
| 786 | |
| 787 | if (mock && *mock) { |
| 788 | buf = read_file_all(mock, &len); |
| 789 | if (buf) { |
| 790 | const char *p = buf; |
| 791 | while (*p && isspace((unsigned char)*p)) p++; |
| 792 | if (*p == '[') parse_json_units(buf); |
| 793 | else parse_plain_units(buf); |
| 794 | free(buf); |
| 795 | } |
| 796 | } else { |
| 797 | if (capture("systemctl list-units --type=service --all --no-pager " |
| 798 | "--plain --output=json 2>/dev/null", out, sizeof out) > 0) { |
| 799 | const char *p = out; |
| 800 | while (*p && isspace((unsigned char)*p)) p++; |
| 801 | if (*p == '[') parse_json_units(out); |
| 802 | else parse_plain_units(out); |
| 803 | } |
| 804 | if (g_count == 0) { |
| 805 | if (capture("systemctl list-units --type=service --all --no-pager " |
| 806 | "--plain 2>/dev/null", out, sizeof out) > 0) |
| 807 | parse_plain_units(out); |
| 808 | } |
| 809 | if (g_count == 0) { |
| 810 | if (capture("systemctl list-unit-files --type=service --no-pager " |
| 811 | "--plain 2>/dev/null", out, sizeof out) > 0) |
| 812 | parse_plain_units(out); |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | /* One enrichment pass, only when we have real systemd output. */ |
| 817 | if (g_count > 0) { |
| 818 | const char *show_mock = getenv("SERVICES_MOCK_SYSTEMCTL_SHOW"); |
| 819 | if (show_mock && *show_mock) { |
| 820 | char *sb = read_file_all(show_mock, &len); |
| 821 | if (sb) { apply_show(sb); free(sb); } |
| 822 | } else if (!mock || !*mock) { |
| 823 | /* `systemctl show --type=service --all` prints NOTHING on systemd |
| 824 | * 249 (verified on the fleet): the --all/--type pair silently |
| 825 | * selects an empty set, so the first live install reported 111 |
| 826 | * units with pid 0 and enabled "-" for every one of them. Asking |
| 827 | * for the units by name is the form that works everywhere, and |
| 828 | * every name is re-validated before it goes into the command, in |
| 829 | * batches small enough to stay well inside ARG_MAX. */ |
| 830 | char *names[MAX_SERVICES]; |
| 831 | int i, n_names = 0; |
| 832 | for (i = 0; i < g_count; i++) { |
| 833 | if (!valid_unit(g_svc[i].name)) continue; |
| 834 | names[n_names++] = g_svc[i].name; |
| 835 | } |
| 836 | for (i = 0; i < n_names; i += 40) { |
| 837 | char cmd[8192]; |
| 838 | size_t used; |
| 839 | int k, upto = i + 40; |
| 840 | snprintf(cmd, sizeof cmd, |
| 841 | "systemctl show -p Id -p MainPID -p ActiveEnterTimestamp " |
| 842 | "-p MemoryCurrent -p UnitFileState -p ActiveState " |
| 843 | "-p SubState -p Description 2>/dev/null"); |
| 844 | used = strlen(cmd); |
| 845 | if (upto > n_names) upto = n_names; |
| 846 | for (k = i; k < upto && used + NAME_SZ + 2 < sizeof cmd; k++) { |
| 847 | cmd[used++] = ' '; |
| 848 | str_copy(cmd + used, sizeof cmd - used, names[k]); |
| 849 | used += strlen(names[k]); |
| 850 | cmd[used] = '\0'; |
| 851 | } |
| 852 | if (capture(cmd, out, sizeof out) > 0) apply_show(out); |
| 853 | } |
| 854 | } |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | #endif /* __linux__ */ |
| 859 | #endif /* !_WIN32 */ |
| 860 | |
| 861 | /* ------------------------------------------------------------------ */ |
| 862 | /* Collection: launchd (macOS) */ |
| 863 | /* ------------------------------------------------------------------ */ |
| 864 | |
| 865 | #if !defined(_WIN32) |
| 866 | static void collect_launchd(void) |
| 867 | { |
| 868 | const char *mock = getenv("SERVICES_MOCK_LAUNCHCTL"); |
| 869 | static char out[OUT_SZ]; |
| 870 | char *buf = NULL; |
| 871 | |
| 872 | g_init = INIT_LAUNCHD; |
| 873 | g_count = 0; |
| 874 | |
| 875 | if (mock && *mock) { |
| 876 | buf = read_file_all(mock, NULL); |
| 877 | if (buf) { str_copy(out, sizeof out, buf); free(buf); } |
| 878 | } else if (capture("launchctl list 2>/dev/null", out, sizeof out) <= 0) { |
| 879 | out[0] = '\0'; |
| 880 | } |
| 881 | |
| 882 | { |
| 883 | const char *p = out; |
| 884 | int first = 1; |
| 885 | while (p && *p) { |
| 886 | const char *nl = strchr(p, '\n'); |
| 887 | size_t len = nl ? (size_t)(nl - p) : strlen(p); |
| 888 | char line[512]; |
| 889 | char pid_s[32], st_s[32], label[NAME_SZ]; |
| 890 | int pid = 0; |
| 891 | |
| 892 | if (len >= sizeof line) len = sizeof line - 1; |
| 893 | memcpy(line, p, len); |
| 894 | line[len] = '\0'; |
| 895 | p = nl ? nl + 1 : p + strlen(p); |
| 896 | |
| 897 | if (first) { |
| 898 | first = 0; |
| 899 | if (strstr(line, "PID") && strstr(line, "Label")) continue; |
| 900 | } |
| 901 | pid_s[0] = st_s[0] = label[0] = '\0'; |
| 902 | if (sscanf(line, "%31s %31s %191[^\n]", pid_s, st_s, label) < 3) continue; |
| 903 | str_trim(label); |
| 904 | if (!label[0]) continue; |
| 905 | if (strcmp(pid_s, "-") != 0) pid = atoi(pid_s); |
| 906 | /* launchd reports a job with no pid as "<last status>". A positive |
| 907 | * value is a real exit code and means the job failed. A NEGATIVE |
| 908 | * value is a signal: -9 (SIGKILL) and -15 (SIGTERM) are how launchd |
| 909 | * reaps idle on-demand agents on memory pressure, so they are |
| 910 | * "inactive", not failures - reporting 73 of those as failed would |
| 911 | * make the board useless on a real Mac. Any other signal is a |
| 912 | * crash and stays failed. */ |
| 913 | if (pid > 0) { |
| 914 | svc_add(label, "launchd job", "running", "running", pid); |
| 915 | } else if (st_s[0] == '-') { |
| 916 | int sig = atoi(st_s + 1); |
| 917 | if (sig == 9 || sig == 15) |
| 918 | svc_add(label, "launchd job", "inactive", "exited", 0); |
| 919 | else |
| 920 | svc_add(label, "launchd job", "failed", "failed", 0); |
| 921 | } else if (st_s[0] && strcmp(st_s, "0") != 0) { |
| 922 | svc_add(label, "launchd job", "failed", "failed", 0); |
| 923 | } else { |
| 924 | svc_add(label, "launchd job", "inactive", "exited", 0); |
| 925 | } |
| 926 | { |
| 927 | svc_t *s = &g_svc[g_count - 1]; |
| 928 | str_copy(s->enabled, sizeof s->enabled, "launchd"); |
| 929 | if (strcmp(st_s, "0") != 0 && strcmp(pid_s, "-") == 0) |
| 930 | snprintf(s->since, sizeof s->since, "last exit %s", st_s); |
| 931 | else |
| 932 | str_copy(s->since, sizeof s->since, "-"); |
| 933 | } |
| 934 | if (g_count >= MAX_SERVICES) break; |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | /* Fill memory (and start time) from a single ps pass over the pids we did |
| 939 | * get. Only digits ever reach the command line here. */ |
| 940 | if (!mock || !*mock) { |
| 941 | char pids[512]; |
| 942 | size_t used = 0; |
| 943 | int i; |
| 944 | |
| 945 | pids[0] = '\0'; |
| 946 | for (i = 0; i < g_count; i++) { |
| 947 | char tmp[16]; |
| 948 | int n; |
| 949 | if (g_svc[i].pid <= 0) continue; |
| 950 | n = snprintf(tmp, sizeof tmp, "%s%d", used ? "," : "", g_svc[i].pid); |
| 951 | if (n <= 0 || used + (size_t)n + 1 >= sizeof pids) break; |
| 952 | memcpy(pids + used, tmp, (size_t)n); |
| 953 | used += (size_t)n; |
| 954 | pids[used] = '\0'; |
| 955 | } |
| 956 | if (used > 0) { |
| 957 | char cmd[640]; |
| 958 | snprintf(cmd, sizeof cmd, "ps -o pid=,rss=,lstart= -p %s 2>/dev/null", pids); |
| 959 | if (capture(cmd, out, sizeof out) > 0) { |
| 960 | char *line = out; |
| 961 | while (line && *line) { |
| 962 | char *nl = strchr(line, '\n'); |
| 963 | int pid = 0; |
| 964 | long rss = 0; |
| 965 | int off = 0; |
| 966 | svc_t *s; |
| 967 | if (nl) *nl = '\0'; |
| 968 | if (sscanf(line, "%d %ld %n", &pid, &rss, &off) >= 2 && pid > 0) { |
| 969 | for (i = 0; i < g_count; i++) { |
| 970 | if (g_svc[i].pid != pid) continue; |
| 971 | s = &g_svc[i]; |
| 972 | s->mem = (unsigned long long)rss * 1024ULL; |
| 973 | if (off > 0 && (size_t)off < strlen(line) && |
| 974 | strcmp(s->since, "-") == 0) { |
| 975 | str_copy(s->since, sizeof s->since, line + off); |
| 976 | str_trim(s->since); |
| 977 | } |
| 978 | break; |
| 979 | } |
| 980 | } |
| 981 | line = nl ? nl + 1 : NULL; |
| 982 | } |
| 983 | } |
| 984 | } |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | #endif /* !_WIN32 */ |
| 989 | |
| 990 | /* ------------------------------------------------------------------ */ |
| 991 | /* Collection: Windows SCM */ |
| 992 | /* ------------------------------------------------------------------ */ |
| 993 | |
| 994 | #if defined(_WIN32) |
| 995 | static void collect_scm(void) |
| 996 | { |
| 997 | SC_HANDLE scm; |
| 998 | DWORD need = 0, got = 0, resume = 0; |
| 999 | LPBYTE buf = NULL; |
| 1000 | |
| 1001 | g_init = INIT_SCM; |
| 1002 | g_count = 0; |
| 1003 | |
| 1004 | scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE); |
| 1005 | if (!scm) return; |
| 1006 | |
| 1007 | EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, |
| 1008 | SERVICE_STATE_ALL, NULL, 0, &need, &got, &resume, NULL); |
| 1009 | if (need > 0) { |
| 1010 | buf = (LPBYTE)malloc(need); |
| 1011 | if (buf) { |
| 1012 | if (EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, |
| 1013 | SERVICE_STATE_ALL, buf, need, &need, |
| 1014 | &got, &resume, NULL)) { |
| 1015 | LPENUM_SERVICE_STATUS_PROCESSA it = (LPENUM_SERVICE_STATUS_PROCESSA)buf; |
| 1016 | DWORD i; |
| 1017 | for (i = 0; i < got && g_count < MAX_SERVICES; i++) { |
| 1018 | const char *state = "stopped"; |
| 1019 | char sub[STATE_SZ]; |
| 1020 | char enabled[EN_SZ] = "-"; |
| 1021 | SC_HANDLE svc; |
| 1022 | LPQUERY_SERVICE_CONFIGA cfg; |
| 1023 | |
| 1024 | switch (it[i].ServiceStatusProcess.dwCurrentState) { |
| 1025 | case SERVICE_RUNNING: state = "running"; break; |
| 1026 | case SERVICE_STOPPED: state = "inactive"; break; |
| 1027 | case SERVICE_PAUSED: state = "paused"; break; |
| 1028 | case SERVICE_START_PENDING: state = "starting"; break; |
| 1029 | case SERVICE_STOP_PENDING: state = "stopping"; break; |
| 1030 | default: state = "unknown"; break; |
| 1031 | } |
| 1032 | snprintf(sub, sizeof sub, "%lu", |
| 1033 | (unsigned long)it[i].ServiceStatusProcess.dwCurrentState); |
| 1034 | |
| 1035 | svc_add(it[i].lpServiceName, it[i].lpDisplayName, state, sub, 0); |
| 1036 | { |
| 1037 | svc_t *s = &g_svc[g_count - 1]; |
| 1038 | s->pid = (int)it[i].ServiceStatusProcess.dwProcessId; |
| 1039 | svc = OpenServiceA(scm, it[i].lpServiceName, |
| 1040 | SERVICE_QUERY_CONFIG); |
| 1041 | if (svc) { |
| 1042 | DWORD cneed = 0; |
| 1043 | QueryServiceConfigA(svc, NULL, 0, &cneed); |
| 1044 | cfg = (LPQUERY_SERVICE_CONFIGA)malloc(cneed ? cneed : 1); |
| 1045 | if (cfg && QueryServiceConfigA(svc, cfg, cneed, &cneed)) { |
| 1046 | switch (cfg->dwStartType) { |
| 1047 | case SERVICE_AUTO_START: enabled[0] = 0; str_copy(enabled, sizeof enabled, "automatic"); break; |
| 1048 | case SERVICE_DEMAND_START: str_copy(enabled, sizeof enabled, "manual"); break; |
| 1049 | case SERVICE_DISABLED: str_copy(enabled, sizeof enabled, "disabled"); break; |
| 1050 | case SERVICE_BOOT_START: str_copy(enabled, sizeof enabled, "boot"); break; |
| 1051 | case SERVICE_SYSTEM_START: str_copy(enabled, sizeof enabled, "system"); break; |
| 1052 | default: str_copy(enabled, sizeof enabled, "-"); break; |
| 1053 | } |
| 1054 | } |
| 1055 | free(cfg); |
| 1056 | CloseServiceHandle(svc); |
| 1057 | } |
| 1058 | str_copy(s->enabled, sizeof s->enabled, enabled); |
| 1059 | str_copy(s->since, sizeof s->since, "-"); |
| 1060 | s->mem = 0; |
| 1061 | } |
| 1062 | } |
| 1063 | } |
| 1064 | free(buf); |
| 1065 | } |
| 1066 | } |
| 1067 | CloseServiceHandle(scm); |
| 1068 | } |
| 1069 | #endif |
| 1070 | |
| 1071 | /* ------------------------------------------------------------------ */ |
| 1072 | /* Collection dispatch + ordering */ |
| 1073 | /* ------------------------------------------------------------------ */ |
| 1074 | |
| 1075 | static int svc_failed(const svc_t *s) |
| 1076 | { |
| 1077 | return strcmp(s->active, "failed") == 0 || |
| 1078 | strcmp(s->sub, "failed") == 0; |
| 1079 | } |
| 1080 | |
| 1081 | static int svc_running(const svc_t *s) |
| 1082 | { |
| 1083 | return strcmp(s->active, "running") == 0 || |
| 1084 | strcmp(s->active, "active") == 0; |
| 1085 | } |
| 1086 | |
| 1087 | static int svc_cmp(const void *a, const void *b) |
| 1088 | { |
| 1089 | const svc_t *x = (const svc_t *)a; |
| 1090 | const svc_t *y = (const svc_t *)b; |
| 1091 | int fx = svc_failed(x), fy = svc_failed(y); |
| 1092 | int rx = svc_running(x), ry = svc_running(y); |
| 1093 | |
| 1094 | if (fx != fy) return fy - fx; /* failed first */ |
| 1095 | if (rx != ry) return ry - rx; /* then running */ |
| 1096 | return strcmp(x->name, y->name); |
| 1097 | } |
| 1098 | |
| 1099 | static const char *init_name(void) |
| 1100 | { |
| 1101 | switch (g_init) { |
| 1102 | case INIT_SYSTEMD: return "systemd"; |
| 1103 | case INIT_LAUNCHD: return "launchd"; |
| 1104 | case INIT_SCM: return "windows-scm"; |
| 1105 | default: return "none"; |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | static void collect_all(void) |
| 1110 | { |
| 1111 | const char *allow = getenv("SERVICES_ALLOW_CONTROL"); |
| 1112 | #if defined(__linux__) |
| 1113 | const char *force = getenv("SERVICES_FORCE_INIT"); |
| 1114 | #endif |
| 1115 | |
| 1116 | g_control = (allow && *allow && strcmp(allow, "0") != 0); |
| 1117 | g_count = 0; |
| 1118 | |
| 1119 | #if defined(_WIN32) |
| 1120 | collect_scm(); |
| 1121 | #elif defined(__APPLE__) |
| 1122 | collect_launchd(); |
| 1123 | #else |
| 1124 | if (getenv("SERVICES_MOCK_LAUNCHCTL")) { |
| 1125 | collect_launchd(); /* fixture-driven launchd path on any host */ |
| 1126 | } else if (force && strcmp(force, "none") == 0) { |
| 1127 | g_init = INIT_NONE; |
| 1128 | collect_proc_daemons(); |
| 1129 | } else if (getenv("SERVICES_MOCK_SYSTEMCTL")) { |
| 1130 | collect_systemd(); |
| 1131 | } else if (access("/run/systemd/system", F_OK) == 0) { |
| 1132 | collect_systemd(); |
| 1133 | } else { |
| 1134 | g_init = INIT_NONE; |
| 1135 | if (collect_proc_daemons() == 0) g_count = 0; |
| 1136 | } |
| 1137 | #endif |
| 1138 | |
| 1139 | if (g_count > 1) qsort(g_svc, (size_t)g_count, sizeof(svc_t), svc_cmp); |
| 1140 | } |
| 1141 | |
| 1142 | /* ------------------------------------------------------------------ */ |
| 1143 | /* JSON output */ |
| 1144 | /* ------------------------------------------------------------------ */ |
| 1145 | |
| 1146 | static void mem_json(buf_t *b, unsigned long long v) |
| 1147 | { |
| 1148 | char tmp[32]; |
| 1149 | if (v == 0) { buf_puts(b, "null"); return; } |
| 1150 | snprintf(tmp, sizeof tmp, "%llu", v); |
| 1151 | buf_puts(b, tmp); |
| 1152 | } |
| 1153 | |
| 1154 | static void emit_service(buf_t *b, const svc_t *s) |
| 1155 | { |
| 1156 | buf_puts(b, "{\"name\":"); |
| 1157 | json_into(b, s->name); |
| 1158 | buf_puts(b, ",\"description\":"); |
| 1159 | json_into(b, s->desc); |
| 1160 | buf_puts(b, ",\"active\":"); |
| 1161 | json_into(b, s->active); |
| 1162 | buf_puts(b, ",\"sub\":"); |
| 1163 | json_into(b, s->sub); |
| 1164 | buf_puts(b, ",\"enabled\":"); |
| 1165 | json_into(b, s->enabled); |
| 1166 | buf_puts(b, ",\"pid\":"); |
| 1167 | { |
| 1168 | char tmp[32]; |
| 1169 | snprintf(tmp, sizeof tmp, "%d", s->pid); |
| 1170 | buf_puts(b, tmp); |
| 1171 | } |
| 1172 | buf_puts(b, ",\"memory_bytes\":"); |
| 1173 | mem_json(b, s->mem); |
| 1174 | buf_puts(b, ",\"since\":"); |
| 1175 | json_into(b, s->since); |
| 1176 | buf_puts(b, ",\"failed\":"); |
| 1177 | buf_puts(b, svc_failed(s) ? "true" : "false"); |
| 1178 | buf_putc(b, '}'); |
| 1179 | } |
| 1180 | |
| 1181 | static void print_json_header(void) |
| 1182 | { |
| 1183 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 1184 | "Cache-Control: no-store\r\n" |
| 1185 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1186 | } |
| 1187 | |
| 1188 | /* ------------------------------------------------------------------ */ |
| 1189 | /* HTML */ |
| 1190 | /* ------------------------------------------------------------------ */ |
| 1191 | |
| 1192 | /* Split UI_HTML on the two control-byte placeholders and expand them into the |
| 1193 | * theme macros, so the page and the bot palette can never drift apart. */ |
| 1194 | static void emit_ui(void) |
| 1195 | { |
| 1196 | const char *p = UI_HTML; |
| 1197 | |
| 1198 | while (*p) { |
| 1199 | if (*p == '\001') { |
| 1200 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS |
| 1201 | ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);" |
| 1202 | "--ac:var(--blue);--sf:var(--bg-card);--sf2:var(--surface-2)}" |
| 1203 | "</style>", stdout); |
| 1204 | p++; |
| 1205 | } else if (*p == '\002') { |
| 1206 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1207 | p++; |
| 1208 | } else { |
| 1209 | putchar(*p++); |
| 1210 | } |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | static int mode_html(void) |
| 1215 | { |
| 1216 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1217 | "Cache-Control: no-store\r\n" |
| 1218 | "X-Content-Type-Options: nosniff\r\n" |
| 1219 | "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " |
| 1220 | "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " |
| 1221 | "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); |
| 1222 | emit_ui(); |
| 1223 | return 0; |
| 1224 | } |
| 1225 | |
| 1226 | /* ------------------------------------------------------------------ */ |
| 1227 | /* Control */ |
| 1228 | /* ------------------------------------------------------------------ */ |
| 1229 | |
| 1230 | static int do_control(const char *unit, const char *op) |
| 1231 | { |
| 1232 | if (!valid_unit(unit)) return 400; |
| 1233 | if (!g_control) return 403; |
| 1234 | if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && |
| 1235 | strcmp(op, "restart") != 0) |
| 1236 | return 400; |
| 1237 | |
| 1238 | { |
| 1239 | const char *logp = getenv("SERVICES_MOCK_SYSTEMCTL_LOG"); |
| 1240 | if (logp && *logp) { |
| 1241 | FILE *f = fopen(logp, "a"); |
| 1242 | if (f) { |
| 1243 | fprintf(f, "systemctl %s %s\n", op, unit); |
| 1244 | fclose(f); |
| 1245 | } |
| 1246 | return 0; |
| 1247 | } |
| 1248 | } |
| 1249 | |
| 1250 | #if defined(_WIN32) |
| 1251 | { |
| 1252 | SC_HANDLE scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT); |
| 1253 | SC_HANDLE svc; |
| 1254 | int rc = 500; |
| 1255 | if (!scm) return 500; |
| 1256 | svc = OpenServiceA(scm, unit, |
| 1257 | strcmp(op, "stop") == 0 ? SERVICE_STOP |
| 1258 | : (SERVICE_START | SERVICE_STOP)); |
| 1259 | if (!svc) { CloseServiceHandle(scm); return 404; } |
| 1260 | if (strcmp(op, "start") == 0) { |
| 1261 | if (StartServiceA(svc, 0, NULL)) rc = 0; |
| 1262 | else if (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) rc = 0; |
| 1263 | } else { |
| 1264 | SERVICE_STATUS st; |
| 1265 | if (ControlService(svc, SERVICE_CONTROL_STOP, &st)) rc = 0; |
| 1266 | else if (GetLastError() == ERROR_SERVICE_NOT_ACTIVE) rc = 0; |
| 1267 | } |
| 1268 | CloseServiceHandle(svc); |
| 1269 | CloseServiceHandle(scm); |
| 1270 | return rc; |
| 1271 | } |
| 1272 | #elif defined(__APPLE__) |
| 1273 | { |
| 1274 | char *argv[4]; |
| 1275 | int rc; |
| 1276 | argv[0] = (char *)"launchctl"; |
| 1277 | argv[1] = (char *)(strcmp(op, "stop") == 0 ? "stop" : "kickstart"); |
| 1278 | argv[2] = (char *)("-k"); |
| 1279 | argv[3] = (char *)unit; |
| 1280 | if (strcmp(op, "stop") == 0) { argv[2] = (char *)unit; argv[3] = NULL; } |
| 1281 | rc = run_argv(argv); |
| 1282 | return rc == 0 ? 0 : 500; |
| 1283 | } |
| 1284 | #else |
| 1285 | { |
| 1286 | char *argv[4]; |
| 1287 | int rc; |
| 1288 | argv[0] = (char *)"systemctl"; |
| 1289 | argv[1] = (char *)op; |
| 1290 | argv[2] = (char *)unit; |
| 1291 | argv[3] = NULL; |
| 1292 | rc = run_argv(argv); |
| 1293 | return rc == 0 ? 0 : 500; |
| 1294 | } |
| 1295 | #endif |
| 1296 | } |
| 1297 | |
| 1298 | /* ------------------------------------------------------------------ */ |
| 1299 | /* API dispatch */ |
| 1300 | /* ------------------------------------------------------------------ */ |
| 1301 | |
| 1302 | static void err_json(int code, const char *status, const char *msg) |
| 1303 | { |
| 1304 | printf("Status: %d %s\r\n", code, status); |
| 1305 | print_json_header(); |
| 1306 | printf("{\"ok\":false,\"error\":\"%s\"}\n", msg); |
| 1307 | } |
| 1308 | |
| 1309 | static int mode_json(const char *qs) |
| 1310 | { |
| 1311 | char action[64]; |
| 1312 | char filter[32]; |
| 1313 | char unit[256]; |
| 1314 | char op[32]; |
| 1315 | |
| 1316 | action[0] = filter[0] = unit[0] = op[0] = '\0'; |
| 1317 | get_query_val(qs, "action", action, sizeof action); |
| 1318 | get_query_val(qs, "filter", filter, sizeof filter); |
| 1319 | get_query_val(qs, "unit", unit, sizeof unit); |
| 1320 | get_query_val(qs, "op", op, sizeof op); |
| 1321 | |
| 1322 | if (!action[0]) str_copy(action, sizeof action, "list"); |
| 1323 | |
| 1324 | collect_all(); |
| 1325 | |
| 1326 | if (strcmp(action, "list") == 0) { |
| 1327 | buf_t b = { 0 }; |
| 1328 | int i, shown = 0; |
| 1329 | int running = 0, failed = 0, inactive = 0; |
| 1330 | |
| 1331 | for (i = 0; i < g_count; i++) { |
| 1332 | if (svc_running(&g_svc[i])) running++; |
| 1333 | else if (svc_failed(&g_svc[i])) failed++; |
| 1334 | else inactive++; |
| 1335 | } |
| 1336 | |
| 1337 | print_json_header(); |
| 1338 | buf_puts(&b, "{\"ok\":true,\"init_system\":"); |
| 1339 | json_into(&b, init_name()); |
| 1340 | buf_puts(&b, ",\"control_enabled\":"); |
| 1341 | buf_puts(&b, g_control ? "true" : "false"); |
| 1342 | { |
| 1343 | buf_t body; |
| 1344 | char tmp[32]; |
| 1345 | memset(&body, 0, sizeof body); |
| 1346 | for (i = 0; i < g_count; i++) { |
| 1347 | const svc_t *s = &g_svc[i]; |
| 1348 | int keep = 1; |
| 1349 | if (filter[0] && strcmp(filter, "all") != 0) { |
| 1350 | if (strcmp(filter, "failed") == 0) keep = svc_failed(s); |
| 1351 | else if (strcmp(filter, "running") == 0) keep = svc_running(s); |
| 1352 | else if (strcmp(filter, "inactive") == 0) |
| 1353 | keep = !svc_running(s) && !svc_failed(s); |
| 1354 | } |
| 1355 | if (!keep) continue; |
| 1356 | if (shown) buf_putc(&body, ','); |
| 1357 | emit_service(&body, s); |
| 1358 | shown++; |
| 1359 | } |
| 1360 | buf_puts(&b, ",\"count\":"); |
| 1361 | snprintf(tmp, sizeof tmp, "%d", shown); |
| 1362 | buf_puts(&b, tmp); |
| 1363 | buf_puts(&b, ",\"summary\":{\"running\":"); |
| 1364 | snprintf(tmp, sizeof tmp, "%d", running); buf_puts(&b, tmp); |
| 1365 | buf_puts(&b, ",\"failed\":"); |
| 1366 | snprintf(tmp, sizeof tmp, "%d", failed); buf_puts(&b, tmp); |
| 1367 | buf_puts(&b, ",\"inactive\":"); |
| 1368 | snprintf(tmp, sizeof tmp, "%d", inactive); buf_puts(&b, tmp); |
| 1369 | buf_puts(&b, "},\"services\":["); |
| 1370 | buf_add(&b, buf_str(&body), body.n); |
| 1371 | buf_puts(&b, "]}\n"); |
| 1372 | buf_free(&body); |
| 1373 | } |
| 1374 | fwrite(buf_str(&b), 1, b.n, stdout); |
| 1375 | buf_free(&b); |
| 1376 | return 0; |
| 1377 | } |
| 1378 | |
| 1379 | if (strcmp(action, "show") == 0) { |
| 1380 | svc_t *s; |
| 1381 | buf_t b = { 0 }; |
| 1382 | |
| 1383 | if (!unit[0]) { err_json(400, "Bad Request", "missing unit"); return 0; } |
| 1384 | if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } |
| 1385 | s = svc_find(unit); |
| 1386 | if (!s) { err_json(404, "Not Found", "service not found"); return 0; } |
| 1387 | |
| 1388 | print_json_header(); |
| 1389 | buf_puts(&b, "{\"ok\":true,\"init_system\":"); |
| 1390 | json_into(&b, init_name()); |
| 1391 | buf_puts(&b, ",\"control_enabled\":"); |
| 1392 | buf_puts(&b, g_control ? "true" : "false"); |
| 1393 | buf_puts(&b, ",\"service\":"); |
| 1394 | emit_service(&b, s); |
| 1395 | buf_puts(&b, "}\n"); |
| 1396 | fwrite(buf_str(&b), 1, b.n, stdout); |
| 1397 | buf_free(&b); |
| 1398 | return 0; |
| 1399 | } |
| 1400 | |
| 1401 | if (strcmp(action, "control") == 0) { |
| 1402 | int rc; |
| 1403 | |
| 1404 | /* Refuse by capability before by method: a node that never opted into |
| 1405 | * control must not advertise a 405 that implies the route works. */ |
| 1406 | if (!g_control) { err_json(403, "Forbidden", "control_disabled"); return 0; } |
| 1407 | if (!is_post_request()) { |
| 1408 | err_json(405, "Method Not Allowed", "control requires POST"); |
| 1409 | return 0; |
| 1410 | } |
| 1411 | if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } |
| 1412 | if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && |
| 1413 | strcmp(op, "restart") != 0) { |
| 1414 | err_json(400, "Bad Request", "op must be start|stop|restart"); |
| 1415 | return 0; |
| 1416 | } |
| 1417 | rc = do_control(unit, op); |
| 1418 | if (rc == 403) { err_json(403, "Forbidden", "control_disabled"); return 0; } |
| 1419 | if (rc == 400) { err_json(400, "Bad Request", "invalid request"); return 0; } |
| 1420 | if (rc == 404) { err_json(404, "Not Found", "service not found"); return 0; } |
| 1421 | if (rc != 0) { err_json(500, "Internal Server Error", "control failed"); return 0; } |
| 1422 | |
| 1423 | print_json_header(); |
| 1424 | printf("{\"ok\":true,\"unit\":\"%s\",\"op\":\"%s\"," |
| 1425 | "\"control_enabled\":true,\"init_system\":\"%s\"}\n", |
| 1426 | unit, op, init_name()); |
| 1427 | return 0; |
| 1428 | } |
| 1429 | |
| 1430 | err_json(400, "Bad Request", "unknown action"); |
| 1431 | return 0; |
| 1432 | } |
| 1433 | |
| 1434 | static int mode_meta(void) |
| 1435 | { |
| 1436 | printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); |
| 1437 | return 0; |
| 1438 | } |
| 1439 | |
| 1440 | int main(int argc, char **argv) |
| 1441 | { |
| 1442 | const char *qs; |
| 1443 | |
| 1444 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || |
| 1445 | (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) |
| 1446 | return mode_meta(); |
| 1447 | |
| 1448 | if (argc > 1 && strcmp(argv[1], "--version") == 0) { |
| 1449 | printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); |
| 1450 | return 0; |
| 1451 | } |
| 1452 | |
| 1453 | require_node_auth(); |
| 1454 | |
| 1455 | qs = getenv("QUERY_STRING"); |
| 1456 | if (!qs) qs = ""; |
| 1457 | |
| 1458 | if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) |
| 1459 | return mode_json(qs); |
| 1460 | |
| 1461 | return mode_html(); |
| 1462 | } |