scorpiox-bot-plugin-docker
←plugin_docker.cc
1161 lines · 42 KBHEADBlameDownload
1/*
2 * plugin_docker — SCORPIOX BOT open-source container dashboard plugin
3 *
4 * A single clean-room C99 binary that serves THREE modes:
5 * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery
6 * 2. ?action=... | ?format=json -> JSON node API (list / logs / control / info)
7 * 3. GET (default) -> responsive HTML container dashboard
8 *
9 * Local node only. Auto-detects `docker` or `podman` on PATH (or DOCKER_BIN).
10 * Every container identifier is validated against [A-Za-z0-9_.-]{1,128} with a
11 * leading-dash rejection BEFORE it can reach a shell, so neither flag injection
12 * (`cid=--help`) nor command injection (`cid=a;id`) is reachable.
13 *
14 * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
15 * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
16 * scorpiox-server on the node.
17 *
18 * MIT License. Copyright (c) 2026 SCORPIOX INC.
19 */
20
21#if !defined(_WIN32)
22# define _POSIX_C_SOURCE 200809L
23# define _DEFAULT_SOURCE 1
24#endif
25
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <time.h>
30#include <ctype.h>
31#include <errno.h>
32
33#if defined(_WIN32)
34# define WIN32_LEAN_AND_MEAN
35# include <windows.h>
36# include <io.h>
37# define sx_popen _popen
38# define sx_pclose _pclose
39# define sx_access _access
40# define SX_X_OK 0
41# define SX_PATH_SEP ';'
42#else
43# include <unistd.h>
44# include <sys/wait.h>
45# include <sys/stat.h>
46# define sx_popen popen
47# define sx_pclose pclose
48# define sx_access access
49# define SX_X_OK X_OK
50# define SX_PATH_SEP ':'
51#endif
52
53#include "bot_theme_plugin.h"
54
55#define PLUGIN_SLUG "docker"
56#define PLUGIN_ID "plugin_docker"
57#define PLUGIN_VER "1.1.3"
58
59#define MAX_CONTAINERS 256
60#define LOG_TAIL 100
61
62/* ------------------------------------------------------------------ */
63/* Small utilities */
64/* ------------------------------------------------------------------ */
65
66
67/* Percent-decode in place ('+' becomes space). */
68static void url_decode(char *s)
69{
70 char *o = s;
71 if (!s) return;
72 while (*s) {
73 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
74 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
75 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
76 *o++ = (char)((hi << 4) | lo);
77 s += 3;
78 } else if (*s == '+') {
79 *o++ = ' ';
80 s++;
81 } else {
82 *o++ = *s++;
83 }
84 }
85 *o = '\0';
86}
87
88/* Read one parameter (decoded) out of a form/query string. */
89static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
90{
91 size_t klen;
92 const char *p;
93
94 if (!out || outsz == 0) return 0;
95 out[0] = '\0';
96 if (!qs || !key) return 0;
97 klen = strlen(key);
98
99 for (p = qs; *p; ) {
100 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
101 const char *v = p + klen + 1;
102 size_t i = 0;
103 while (*v && *v != '&' && i + 1 < outsz)
104 out[i++] = *v++;
105 out[i] = '\0';
106 url_decode(out);
107 return 1;
108 }
109 p = strchr(p, '&');
110 if (!p) break;
111 p++;
112 }
113 return 0;
114}
115
116static void json_str(const char *s)
117{
118 putchar('"');
119 for (; s && *s; s++) {
120 unsigned char c = (unsigned char)*s;
121 switch (c) {
122 case '"': fputs("\\\"", stdout); break;
123 case '\\': fputs("\\\\", stdout); break;
124 case '\n': fputs("\\n", stdout); break;
125 case '\r': fputs("\\r", stdout); break;
126 case '\t': fputs("\\t", stdout); break;
127 default:
128 if (c < 0x20) printf("\\u%04x", (unsigned)c);
129 else putchar((int)c);
130 }
131 }
132 putchar('"');
133}
134
135static void utc_now(char *buf, size_t sz)
136{
137 time_t t = time(NULL);
138 struct tm tmv;
139#if defined(_WIN32)
140 gmtime_s(&tmv, &t);
141#else
142 gmtime_r(&t, &tmv);
143#endif
144 if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) {
145 strncpy(buf, "1970-01-01T00:00:00Z", sz - 1);
146 buf[sz - 1] = '\0';
147 }
148}
149
150static long node_pid(void)
151{
152#if defined(_WIN32)
153 return (long)GetCurrentProcessId();
154#else
155 return (long)getpid();
156#endif
157}
158
159/* ------------------------------------------------------------------ */
160/* Strict identifier validation */
161/* ------------------------------------------------------------------ */
162
163/*
164 * Container identifiers (IDs, names, short IDs) must match
165 * [A-Za-z0-9_.-]{1,128} and must not start with '-' or '.'.
166 * Anything else is refused before it can reach a command line.
167 */
168static int valid_cid(const char *s)
169{
170 size_t n, i;
171 if (!s || !*s) return 0;
172 n = strlen(s);
173 if (n > 128) return 0;
174 if (s[0] == '-' || s[0] == '.') return 0;
175 for (i = 0; i < n; i++) {
176 unsigned char c = (unsigned char)s[i];
177 if (isalnum(c) || c == '_' || c == '.' || c == '-') continue;
178 return 0;
179 }
180 return 1;
181}
182
183/* The runtime binary path must not contain quoting hazards. */
184static int valid_runtime_path(const char *s)
185{
186 if (!s || !*s) return 0;
187 if (strchr(s, '\'') || strchr(s, '\n') || strchr(s, '\r')) return 0;
188 return 1;
189}
190
191static int valid_op(const char *s)
192{
193 return s && (strcmp(s, "start") == 0 || strcmp(s, "stop") == 0 ||
194 strcmp(s, "restart") == 0);
195}
196
197/* ------------------------------------------------------------------ */
198/* Command execution */
199/* ------------------------------------------------------------------ */
200
201/* Run a shell command, capture stdout+stderr. Returns malloc'd text. */
202static char *run_capture(const char *cmd, int *exit_code)
203{
204 FILE *fp;
205 char *buf = NULL;
206 size_t len = 0, cap = 0, chunk;
207 char tmp[4096];
208 int status = 0;
209
210 if (exit_code) *exit_code = -1;
211 fp = sx_popen(cmd, "r");
212 if (!fp) return NULL;
213
214 while ((chunk = fread(tmp, 1, sizeof(tmp), fp)) > 0) {
215 if (len + chunk + 1 > cap) {
216 size_t ncap = cap ? cap * 2 : 8192;
217 char *nb;
218 while (ncap < len + chunk + 1) ncap *= 2;
219 nb = (char *)realloc(buf, ncap);
220 if (!nb) { free(buf); sx_pclose(fp); return NULL; }
221 buf = nb;
222 cap = ncap;
223 }
224 memcpy(buf + len, tmp, chunk);
225 len += chunk;
226 }
227 if (!buf) {
228 buf = (char *)malloc(1);
229 if (!buf) { sx_pclose(fp); return NULL; }
230 cap = 1;
231 }
232 buf[len] = '\0';
233
234 status = sx_pclose(fp);
235#if defined(_WIN32)
236 if (exit_code) *exit_code = status;
237#else
238 if (exit_code) {
239 if (WIFEXITED(status)) *exit_code = WEXITSTATUS(status);
240 else *exit_code = -1;
241 }
242#endif
243 return buf;
244}
245
246/* ------------------------------------------------------------------ */
247/* Runtime detection */
248/* ------------------------------------------------------------------ */
249
250static int path_has_exec(const char *name)
251{
252 const char *env = getenv("PATH");
253 char candidate[1024];
254
255 if (!env) return 0;
256 while (*env) {
257 const char *end = strchr(env, SX_PATH_SEP);
258 size_t dlen = end ? (size_t)(end - env) : strlen(env);
259 if (dlen > 0 && dlen + strlen(name) + 2 < sizeof(candidate)) {
260 memcpy(candidate, env, dlen);
261 candidate[dlen] = '\0';
262#if defined(_WIN32)
263 snprintf(candidate + dlen, sizeof(candidate) - dlen, "\\%s.exe", name);
264#else
265 snprintf(candidate + dlen, sizeof(candidate) - dlen, "/%s", name);
266#endif
267 if (sx_access(candidate, SX_X_OK) == 0) return 1;
268 }
269 if (!end) break;
270 env = end + 1;
271 }
272 return 0;
273}
274
275/* Resolve the container runtime. Returns 1 when something is usable. */
276static int detect_runtime(char *bin, size_t binsz, char *label, size_t labelsz)
277{
278 const char *ovr = getenv("DOCKER_BIN");
279
280 bin[0] = '\0';
281 label[0] = '\0';
282
283 if (ovr && *ovr) {
284 if (!valid_runtime_path(ovr)) return 0;
285 snprintf(bin, binsz, "%s", ovr);
286 snprintf(label, labelsz, "custom");
287 return 1;
288 }
289 if (path_has_exec("docker")) {
290 snprintf(bin, binsz, "docker");
291 snprintf(label, labelsz, "docker");
292 return 1;
293 }
294 if (path_has_exec("podman")) {
295 snprintf(bin, binsz, "podman");
296 snprintf(label, labelsz, "podman");
297 return 1;
298 }
299 return 0;
300}
301
302/* ------------------------------------------------------------------ */
303/* Container list */
304/* ------------------------------------------------------------------ */
305
306typedef struct {
307 char id[80];
308 char name[192];
309 char image[192];
310 char state[32];
311 char status[192];
312 char ports[512];
313 char cpu[32];
314 char mem[96];
315} container_t;
316
317static container_t g_containers[MAX_CONTAINERS];
318static int g_container_count;
319
320/* Split on '|' in place into up to max fields. */
321static int split_pipe(char *line, char **out, int max)
322{
323 int n = 0;
324 char *p = line;
325 if (max <= 0) return 0;
326 out[n++] = p;
327 while (*p && n < max) {
328 if (*p == '|') {
329 *p = '\0';
330 out[n++] = p + 1;
331 }
332 p++;
333 }
334 /* consume the remainder of the last field up to a newline */
335 if (n > 0) {
336 char *e = out[n - 1];
337 while (*e && *e != '\n' && *e != '\r') e++;
338 *e = '\0';
339 }
340 return n;
341}
342
343static void copy_field(char *dst, size_t dstsz, const char *src)
344{
345 size_t i = 0;
346 if (!dst || dstsz == 0) return;
347 if (!src) { dst[0] = '\0'; return; }
348 while (src[i] && i + 1 < dstsz) { dst[i] = src[i]; i++; }
349 dst[i] = '\0';
350}
351
352/* Normalise the runtime's state word.
353 *
354 * docker reports a tidy lowercase state ("running", "exited", "paused"), but
355 * podman 3.x does not implement {{.State}} at all and substitutes the human
356 * Status text ("Up 4 months ago"). Normalising here keeps the JSON contract
357 * identical no matter which runtime produced the line.
358 */
359static void normalize_state(char *dst, size_t dstsz, const char *raw)
360{
361 char low[64];
362 size_t i = 0;
363
364 if (!raw) raw = "";
365 while (raw[i] && i + 1 < sizeof(low)) {
366 low[i] = (char)tolower((unsigned char)raw[i]);
367 i++;
368 }
369 low[i] = '\0';
370
371 if (strstr(low, "paused")) copy_field(dst, dstsz, "paused");
372 else if (strstr(low, "restart")) copy_field(dst, dstsz, "restarting");
373 else if (strstr(low, "dead")) copy_field(dst, dstsz, "dead");
374 else if (strstr(low, "created")) copy_field(dst, dstsz, "created");
375 else if (strstr(low, "exited") || strstr(low, "stopped") || strstr(low, "exit"))
376 copy_field(dst, dstsz, "exited");
377 else if (strstr(low, "up") || strstr(low, "running"))
378 copy_field(dst, dstsz, "running");
379 else if (low[0]) copy_field(dst, dstsz, low);
380 else copy_field(dst, dstsz, "");
381}
382
383/* Parse `ps -a` output into g_containers. Returns line count parsed. */
384static int parse_ps(const char *text)
385{
386 const char *p = text;
387 int count = 0;
388
389 g_container_count = 0;
390 while (*p && g_container_count < MAX_CONTAINERS) {
391 char line[1600];
392 size_t i = 0;
393 char *fields[6];
394 int nf;
395
396 while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++;
397 line[i] = '\0';
398 while (*p == '\n' || *p == '\r') p++;
399
400 if (i == 0) continue;
401 /* skip a header row if the runtime emitted one */
402 if (strncmp(line, "CONTAINER ID", 12) == 0) continue;
403
404 nf = split_pipe(line, fields, 6);
405 if (nf < 2) continue;
406
407 {
408 container_t *c = &g_containers[g_container_count];
409 memset(c, 0, sizeof(*c));
410 copy_field(c->id, sizeof(c->id), fields[0]);
411 copy_field(c->name, sizeof(c->name), nf > 1 ? fields[1] : "");
412 copy_field(c->image, sizeof(c->image), nf > 2 ? fields[2] : "");
413 {
414 char raw[64];
415 copy_field(raw, sizeof(raw), nf > 3 ? fields[3] : "");
416 normalize_state(c->state, sizeof(c->state), raw);
417 }
418 copy_field(c->status, sizeof(c->status), nf > 4 ? fields[4] : "");
419 copy_field(c->ports, sizeof(c->ports), nf > 5 ? fields[5] : "");
420 g_container_count++;
421 count++;
422 }
423 }
424 return count;
425}
426
427/* Merge `stats --no-stream --format {{.ID}}|{{.CPUPerc}}|{{.MemUsage}}`. */
428static void merge_stats(const char *text)
429{
430 const char *p = text;
431 while (*p) {
432 char line[600];
433 size_t i = 0;
434 char *fields[3];
435 int nf, k;
436
437 while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++;
438 line[i] = '\0';
439 while (*p == '\n' || *p == '\r') p++;
440 if (i == 0) continue;
441
442 nf = split_pipe(line, fields, 3);
443 if (nf < 3) continue;
444
445 for (k = 0; k < g_container_count; k++) {
446 if (strncmp(g_containers[k].id, fields[0], strlen(fields[0])) == 0 ||
447 strcmp(g_containers[k].id, fields[0]) == 0) {
448 copy_field(g_containers[k].cpu, sizeof(g_containers[k].cpu), fields[1]);
449 copy_field(g_containers[k].mem, sizeof(g_containers[k].mem), fields[2]);
450 break;
451 }
452 }
453 }
454}
455
456static int container_is(const container_t *c, const char *state)
457{
458 return strcmp(c->state, state) == 0;
459}
460
461/* ------------------------------------------------------------------ */
462/* Modes */
463/* ------------------------------------------------------------------ */
464
465static int mode_meta(void)
466{
467 puts("{\"name\":\"docker\",\"desc\":\"Containers\"}");
468 return 0;
469}
470
471static void json_header(void)
472{
473 /* Deliberately no Content-Length — the server owns framing. */
474 fputs("Content-Type: application/json; charset=utf-8\r\n"
475 "Cache-Control: no-store\r\n"
476 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
477}
478
479static void json_header_status(const char *status_line)
480{
481 fputs("Status: ", stdout);
482 fputs(status_line, stdout);
483 fputs("\r\n", stdout);
484 json_header();
485}
486
487/* Emit the runtime block (shared by info + list). */
488static void emit_runtime_block(const char *bin, const char *label, int available)
489{
490 fputs("\"runtime\":{", stdout);
491 fputs("\"available\":", stdout);
492 fputs(available ? "true" : "false", stdout);
493 fputs(",\"bin\":", stdout); json_str(available ? bin : "");
494 fputs(",\"label\":", stdout); json_str(available ? label : "");
495 fputs("}", stdout);
496}
497
498static int mode_json(const char *qs, const char *body, int is_post)
499{
500 char action[64];
501 char cid[192];
502 char op[32];
503 char format[32];
504
505 char bin[512], label[64];
506 int available;
507
508 action[0] = cid[0] = op[0] = format[0] = '\0';
509 get_query_val(qs, "action", action, sizeof(action));
510 get_query_val(qs, "cid", cid, sizeof(cid));
511 get_query_val(qs, "op", op, sizeof(op));
512 get_query_val(qs, "format", format, sizeof(format));
513
514 /* fall back to POST body parameters when the query is empty */
515 if (body && *body) {
516 if (!action[0]) get_query_val(body, "action", action, sizeof(action));
517 if (!cid[0]) get_query_val(body, "cid", cid, sizeof(cid));
518 if (!op[0]) get_query_val(body, "op", op, sizeof(op));
519 if (!format[0]) get_query_val(body, "format", format, sizeof(format));
520 }
521
522 available = detect_runtime(bin, sizeof(bin), label, sizeof(label));
523
524 /* ---- control (POST only) ---- */
525 if (strcmp(action, "control") == 0) {
526 int code = 0;
527 char *out;
528
529 if (!is_post) {
530 json_header_status("405 Method Not Allowed");
531 fputs("{\"ok\":false,\"error\":\"control_requires_post\","
532 "\"hint\":\"POST ?action=control&op=start|stop|restart&cid=<id>\"}\n", stdout);
533 return 0;
534 }
535 if (!available) {
536 json_header_status("503 Service Unavailable");
537 fputs("{\"ok\":false,\"error\":\"runtime_available\",\"runtime\":{\"available\":false},"
538 "\"message\":\"Neither docker nor podman was found on this node\"}\n", stdout);
539 return 0;
540 }
541 if (!valid_op(op)) {
542 json_header_status("400 Bad Request");
543 fputs("{\"ok\":false,\"error\":\"invalid_op\","
544 "\"supported\":[\"start\",\"stop\",\"restart\"]}\n", stdout);
545 return 0;
546 }
547 if (!valid_cid(cid)) {
548 json_header_status("400 Bad Request");
549 fputs("{\"ok\":false,\"error\":\"invalid_cid\","
550 "\"message\":\"cid must match [A-Za-z0-9_.-]{1,128} and may not start with - or .\"}\n",
551 stdout);
552 return 0;
553 }
554 {
555 char cmd[1024];
556 snprintf(cmd, sizeof(cmd), "'%s' %s %s 2>&1", bin, op, cid);
557 out = run_capture(cmd, &code);
558 }
559 {
560 char ts[64];
561 utc_now(ts, sizeof(ts));
562 if (code != 0) json_header_status("409 Conflict");
563 else json_header();
564 fputs("{\"ok\":", stdout);
565 fputs(code == 0 ? "true" : "false", stdout);
566 fputs(",\"action\":\"control\",\"op\":", stdout); json_str(op);
567 fputs(",\"cid\":", stdout); json_str(cid);
568 printf(",\"exit_code\":%d", code);
569 fputs(",\"output\":", stdout); json_str(out ? out : "");
570 fputs(",\"utc\":", stdout); json_str(ts);
571 fputs("}\n", stdout);
572 }
573 free(out);
574 return 0;
575 }
576
577 /* ---- logs ---- */
578 if (strcmp(action, "logs") == 0) {
579 if (!valid_cid(cid)) {
580 json_header_status("400 Bad Request");
581 fputs("{\"ok\":false,\"error\":\"invalid_cid\",\"cid\":", stdout);
582 json_str(cid);
583 fputs("}\n", stdout);
584 return 0;
585 }
586 if (!available) {
587 json_header_status("503 Service Unavailable");
588 fputs("{\"ok\":false,\"error\":\"runtime_available\",\"runtime\":{\"available\":false},"
589 "\"message\":\"Neither docker nor podman was found on this node\"}\n", stdout);
590 return 0;
591 }
592 {
593 char cmd[1024];
594 char *out;
595 int code = 0;
596 const char *p;
597
598 snprintf(cmd, sizeof(cmd), "'%s' logs --tail %d %s 2>&1", bin, LOG_TAIL, cid);
599 out = run_capture(cmd, &code);
600
601 if (code != 0) json_header_status("409 Conflict");
602 else json_header();
603 fputs("{\"ok\":", stdout);
604 fputs(code == 0 ? "true" : "false", stdout);
605 fputs(",\"action\":\"logs\",\"cid\":", stdout); json_str(cid);
606 printf(",\"tail\":%d,\"exit_code\":%d", LOG_TAIL, code);
607 fputs(",\"lines\":[", stdout);
608 if (out) {
609 int first = 1;
610 p = out;
611 while (*p) {
612 char line[2048];
613 size_t i = 0;
614 while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++;
615 line[i] = '\0';
616 while (*p == '\n' || *p == '\r') p++;
617 if (!first) fputs(",", stdout);
618 first = 0;
619 json_str(line);
620 }
621 }
622 fputs("],\"text\":", stdout); json_str(out ? out : "");
623 fputs("}\n", stdout);
624 free(out);
625 }
626 return 0;
627 }
628
629 /* ---- info / list / unknown ---- */
630 if (action[0] && strcmp(action, "info") != 0 && strcmp(action, "list") != 0) {
631 json_header_status("400 Bad Request");
632 fputs("{\"ok\":false,\"error\":\"unknown_action\",\"action\":", stdout);
633 json_str(action);
634 fputs(",\"supported\":[\"list\",\"info\",\"logs\",\"control\"]}\n", stdout);
635 return 0;
636 }
637
638 if (strcmp(action, "info") == 0 && strcmp(format, "list") == 0) {
639 /* not meaningful; treat as list */
640 }
641
642 if (strcmp(action, "info") == 0) {
643 char ts[64];
644 utc_now(ts, sizeof(ts));
645 json_header();
646 fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\","
647 "\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",", stdout);
648 emit_runtime_block(bin, label, available);
649 printf(",\"pid\":%ld", node_pid());
650 fputs(",\"utc\":", stdout); json_str(ts);
651 fputs(",\"supported\":[\"list\",\"info\",\"logs\",\"control\"],"
652 "\"control\":{\"method\":\"POST\",\"ops\":[\"start\",\"stop\",\"restart\"]}}\n", stdout);
653 return 0;
654 }
655
656 /* list */
657 {
658 char *psout = NULL;
659 char *statsout = NULL;
660 int pscode = 0, statscode = 0;
661 char ts[64];
662 int total = 0, running = 0, exited = 0, paused = 0, other = 0;
663 int i;
664
665 if (available) {
666 char cmd[1024];
667 snprintf(cmd, sizeof(cmd),
668 "'%s' ps -a --format '{{.ID}}|{{.Names}}|{{.Image}}|{{.State}}|{{.Status}}|{{.Ports}}' 2>&1",
669 bin);
670 psout = run_capture(cmd, &pscode);
671 if (psout && pscode == 0) parse_ps(psout);
672
673 snprintf(cmd, sizeof(cmd),
674 "'%s' stats --no-stream --format '{{.ID}}|{{.CPUPerc}}|{{.MemUsage}}' 2>&1",
675 bin);
676 statsout = run_capture(cmd, &statscode);
677 if (statsout && statscode == 0 && g_container_count > 0) merge_stats(statsout);
678 }
679
680 for (i = 0; i < g_container_count; i++) {
681 total++;
682 if (container_is(&g_containers[i], "running")) running++;
683 else if (container_is(&g_containers[i], "exited")) exited++;
684 else if (container_is(&g_containers[i], "paused")) paused++;
685 else other++;
686 }
687
688 utc_now(ts, sizeof(ts));
689 json_header();
690 fputs("{\"ok\":true,\"action\":\"list\",\"plugin\":\"" PLUGIN_ID "\","
691 "\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",", stdout);
692 emit_runtime_block(bin, label, available);
693 if (!available) {
694 fputs(",\"message\":\"Neither docker nor podman was found on this node. "
695 "Install a container runtime, or set DOCKER_BIN to an explicit binary path.\"", stdout);
696 } else if (psout && pscode != 0) {
697 fputs(",\"daemon_available\":false,\"error\":", stdout);
698 json_str(psout);
699 } else {
700 fputs(",\"daemon_available\":true", stdout);
701 }
702 fputs(",\"utc\":", stdout); json_str(ts);
703 printf(",\"count\":%d,\"summary\":{\"total\":%d,\"running\":%d,\"exited\":%d,"
704 "\"paused\":%d,\"other\":%d}", g_container_count, total, running, exited, paused, other);
705 fputs(",\"containers\":[", stdout);
706 for (i = 0; i < g_container_count; i++) {
707 container_t *c = &g_containers[i];
708 if (i) fputs(",", stdout);
709 fputs("{", stdout);
710 fputs("\"id\":", stdout); json_str(c->id);
711 fputs(",\"short\":", stdout); json_str(c->id[0] ? c->id : "");
712 fputs(",\"name\":", stdout); json_str(c->name);
713 fputs(",\"image\":", stdout); json_str(c->image);
714 fputs(",\"state\":", stdout); json_str(c->state);
715 fputs(",\"status\":", stdout);json_str(c->status);
716 fputs(",\"ports\":", stdout); json_str(c->ports);
717 fputs(",\"cpu\":", stdout); json_str(c->cpu);
718 fputs(",\"mem\":", stdout); json_str(c->mem);
719 fputs("}", stdout);
720 }
721 fputs("]}\n", stdout);
722
723 free(psout);
724 free(statsout);
725 }
726 return 0;
727}
728
729/* ------------------------------------------------------------------ */
730/* HTML UI */
731/* ------------------------------------------------------------------ */
732
733static int mode_html(int embed)
734{
735 fputs("Content-Type: text/html; charset=utf-8\r\n"
736 "Cache-Control: no-store\r\n"
737 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
738
739 fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>"
740 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
741 "<title>docker</title>", stdout);
742
743 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout);
744 fputs(
745"*{box-sizing:border-box}"
746"body{margin:0;padding:16px;background:var(--bg);color:var(--text);"
747 "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;"
748 "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}"
749".wrap{max-width:1080px;margin:0 auto}"
750".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}"
751".title{font-size:20px;font-weight:700;margin:0}"
752".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;"
753 "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}"
754".pill.on{color:var(--accent2);border-color:rgba(48,209,88,.4)}"
755".pill.off{color:var(--danger);border-color:rgba(255,69,58,.4)}"
756".spacer{flex:1}"
757".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
758 "padding:16px;margin-bottom:14px}"
759".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;"
760 "color:var(--muted);font-weight:600}"
761".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}"
762".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}"
763".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}"
764".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px}"
765".kpi .v.run{color:var(--accent2)}.kpi .v.exit{color:var(--muted)}"
766"button{background:var(--accent);color:#fff;border:0;border-radius:999px;"
767 "padding:7px 14px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}"
768"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}"
769"button.danger{background:var(--danger)}"
770"button.sm{padding:4px 10px;font-size:12px}"
771"button:active{transform:scale(.98)}"
772"button:disabled{opacity:.45;cursor:not-allowed}"
773"input,select{background:var(--surface2);border:1px solid var(--line);"
774 "border-radius:10px;padding:8px 12px;color:var(--text);font-size:13px;"
775 "font-family:inherit}"
776"input{flex:1;min-width:140px;font-family:var(--mono)}"
777"input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}"
778".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}"
779"table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}"
780"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;"
781 "color:var(--muted);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);"
782 "white-space:nowrap}"
783"td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle}"
784"td.mono{font-family:var(--mono);font-size:12px;word-break:break-all}"
785"tr:last-child td{border-bottom:0}"
786".state{font-size:11px;font-weight:700;padding:2px 8px;border-radius:999px;"
787 "text-transform:uppercase;letter-spacing:.04em;display:inline-block}"
788".state.running{background:rgba(48,209,88,.16);color:var(--accent2)}"
789".state.exited{background:rgba(255,255,255,.08);color:var(--muted)}"
790".state.paused{background:rgba(255,214,10,.16);color:var(--warn)}"
791".state.created,.state.restarting,.state.dead{background:rgba(255,69,58,.16);color:var(--danger)}"
792".acts{display:flex;gap:6px;flex-wrap:wrap}"
793".tblwrap{overflow-x:auto}"
794"pre{background:var(--surface2);border:1px solid var(--line);border-radius:10px;"
795 "padding:12px;overflow:auto;font-family:var(--mono);font-size:12px;margin:0;"
796 "max-height:380px;white-space:pre-wrap;word-break:break-word}"
797".muted{color:var(--muted)}"
798".empty{padding:22px 8px;text-align:center;color:var(--muted)}"
799".hide{display:none}"
800"@media(max-width:640px){body{padding:10px}.card{padding:12px}"
801 ".tblwrap{overflow-x:visible}"
802 "th:nth-child(1),td:nth-child(1),th:nth-child(3),td:nth-child(3),"
803 "th:nth-child(5),td:nth-child(5),th:nth-child(6),td:nth-child(6){display:none}"
804 "td{padding:8px 4px}th{padding:6px 4px}"
805 "td:nth-child(2){white-space:nowrap;font-weight:600}"
806 ".acts{gap:4px}button.sm{padding:4px 8px;font-size:11px}}"
807"</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout);
808
809 if (!embed)
810 fputs("<div class='top'><a href='/' style='color:var(--accent);text-decoration:none;"
811 "font-weight:600'>&#8592; Back to Bot</a></div>", stdout);
812
813 fputs("<div class='top'><h1 class='title'>docker</h1>"
814 "<span class='pill'>" PLUGIN_VER "</span>"
815 "<span class='pill' id='badge'>connecting</span>"
816 "<span class='spacer'></span>"
817 "<button class='ghost embed-hide' id='themeBtn' type='button'>Theme</button>"
818 "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>", stdout);
819
820 /* KPIs */
821 fputs("<div class='card'><h2>Containers</h2><div class='grid'>"
822 "<div class='kpi'><div class='k'>total</div><div class='v' id='k-total'>&mdash;</div></div>"
823 "<div class='kpi'><div class='k'>running</div><div class='v run' id='k-run'>&mdash;</div></div>"
824 "<div class='kpi'><div class='k'>exited</div><div class='v exit' id='k-exit'>&mdash;</div></div>"
825 "<div class='kpi'><div class='k'>paused</div><div class='v' id='k-pause'>&mdash;</div></div>"
826 "<div class='kpi'><div class='k'>runtime</div><div class='v' id='k-rt'>&mdash;</div></div>"
827 "</div>"
828 "<div class='row' style='margin-top:12px'>"
829 "<input id='q' type='text' placeholder='search name, image, id, port'>"
830 "<select id='state'><option value=''>all states</option>"
831 "<option value='running'>running</option><option value='exited'>exited</option>"
832 "<option value='paused'>paused</option><option value='created'>created</option>"
833 "</select>"
834 "<button id='refreshBtn' type='button'>Apply</button></div>"
835 "<div id='note' class='muted' style='margin-top:10px'></div>"
836 "<div class='tblwrap'><table><thead><tr>"
837 "<th>ID</th><th>Name</th><th>Image</th><th>State</th><th>CPU</th><th>Mem</th><th>Actions</th>"
838 "</tr></thead><tbody id='rows'></tbody></table></div>"
839 "<div id='empty' class='empty hide'>No containers to show.</div>"
840 "</div>", stdout);
841
842 /* log viewer */
843 fputs("<div class='card hide' id='logCard'><h2 id='logTitle'>Logs</h2>"
844 "<pre id='logBody'>loading&hellip;</pre>"
845 "<div class='row' style='margin-top:10px'>"
846 "<button class='ghost sm' id='logReload' type='button'>Reload</button>"
847 "<button class='ghost sm' id='logClose' type='button'>Close</button></div></div>", stdout);
848
849 /* footer */
850 fputs("<div class='card'><h2>About this plugin</h2>"
851 "<p class='muted' style='margin:0 0 8px'>Local node only. Reads "
852 "<code>docker</code> or <code>podman</code> on this machine and makes zero "
853 "outbound network requests. Source is MIT licensed.</p>"
854 "<p class='muted' style='margin:0'><code>list</code>, <code>logs</code> and "
855 "<code>control</code> are the only supported actions; container identifiers are "
856 "validated before they ever reach a command line.</p></div>", stdout);
857
858 /* script */
859 fputs(
860"<script>\n"
861"(function(){\n"
862" var q = new URLSearchParams(location.search);\n"
863" var HUB = q.get('plugin') || '';\n"
864" var node = q.get('node') || '';\n"
865" var sid = q.get('id') || '';\n"
866" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n"
867" localStorage.getItem('bot_active_pwd') || '';\n"
868"\n"
869" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_docker'; }\n"
870" function withCtx(u){\n"
871" if (node) u += '&node=' + encodeURIComponent(node);\n"
872" if (sid) u += '&id=' + encodeURIComponent(sid);\n"
873" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n"
874" return u;\n"
875" }\n"
876" function headers(extra){\n"
877" var h = extra || {};\n"
878" if (pwd) h['X-Bot-Password'] = pwd;\n"
879" return h;\n"
880" }\n"
881" function get(action, extra){\n"
882" var u = withCtx(base() + '?action=' + encodeURIComponent(action) + (extra || ''));\n"
883" return fetch(u, { headers: headers() }).then(function(r){ return r.json(); });\n"
884" }\n"
885" function post(action, form){\n"
886" var u = withCtx(base() + '?action=' + encodeURIComponent(action));\n"
887" return fetch(u, { method:'POST',\n"
888" headers: headers({'Content-Type':'application/x-www-form-urlencoded'}),\n"
889" body: form }).then(function(r){ return r.json(); });\n"
890" }\n"
891" function $(id){ return document.getElementById(id); }\n"
892" function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : String(v); }\n"
893" function el(tag, cls, text){\n"
894" var e = document.createElement(tag);\n"
895" if (cls) e.className = cls;\n"
896" if (text !== undefined && text !== null) e.textContent = String(text);\n"
897" return e;\n"
898" }\n"
899"\n"
900" var DATA = { containers: [], summary: {} };\n"
901" var LOG_CID = '', LOG_NAME = '';\n"
902"\n"
903" function theme(t){\n"
904" if (t) { document.documentElement.setAttribute('data-theme', t); localStorage.setItem('bot_theme', t); }\n"
905" }\n"
906" theme(localStorage.getItem('bot_theme') || 'dark');\n"
907" $('themeBtn').addEventListener('click', function(){\n"
908" theme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light');\n"
909" });\n"
910"\n"
911" function badge(ok, text){\n"
912" var b = $('badge');\n"
913" b.textContent = text;\n"
914" b.className = 'pill ' + (ok ? 'on' : 'off');\n"
915" }\n"
916"\n"
917" function matches(c){\n"
918" var s = ($('state').value || '').toLowerCase();\n"
919" if (s && (c.state || '').toLowerCase() !== s) return false;\n"
920" var k = ($('q').value || '').trim().toLowerCase();\n"
921" if (!k) return true;\n"
922" var hay = ((c.name||'') + ' ' + (c.image||'') + ' ' + (c.id||'') + ' ' + (c.ports||'')).toLowerCase();\n"
923" return hay.indexOf(k) >= 0;\n"
924" }\n"
925"\n"
926" function act(c, op){\n"
927" var label = op + ' ' + (c.name || c.id);\n"
928" if (op !== 'start' && !window.confirm(label + '?')) return;\n"
929" post('control', 'op=' + encodeURIComponent(op) + '&cid=' + encodeURIComponent(c.id))\n"
930" .then(function(d){\n"
931" if (!d.ok) { $('note').textContent = (d.error || 'failed') + (d.output ? ': ' + d.output : ''); }\n"
932" else { $('note').textContent = op + ' ' + (c.name || c.id) + ' ok'; }\n"
933" refresh();\n"
934" })\n"
935" .catch(function(e){ $('note').textContent = 'request failed: ' + e; });\n"
936" }\n"
937"\n"
938" function openLogs(c){\n"
939" LOG_CID = c.id; LOG_NAME = c.name || c.id;\n"
940" $('logCard').classList.remove('hide');\n"
941" $('logTitle').textContent = 'Logs \\u2014 ' + LOG_NAME + ' (last 100 lines)';\n"
942" $('logBody').textContent = 'loading\\u2026';\n"
943" get('logs', '&cid=' + encodeURIComponent(c.id)).then(function(d){\n"
944" $('logBody').textContent = d.ok ? (d.text || '(empty)') : ('error: ' + (d.error || 'unknown'));\n"
945" }).catch(function(e){ $('logBody').textContent = 'request failed: ' + e; });\n"
946" }\n"
947"\n"
948" function render(){\n"
949" var tb = $('rows');\n"
950" while (tb.firstChild) tb.removeChild(tb.firstChild);\n"
951" var shown = 0;\n"
952" (DATA.containers || []).forEach(function(c){\n"
953" if (!matches(c)) return;\n"
954" shown++;\n"
955" var tr = el('tr');\n"
956" tr.appendChild(el('td', 'mono', (c.id || '').slice(0, 12)));\n"
957" tr.appendChild(el('td', '', c.name || ''));\n"
958" tr.appendChild(el('td', 'mono', c.image || ''));\n"
959" var tdState = el('td');\n"
960" tdState.appendChild(el('span', 'state ' + (c.state || '').toLowerCase(), c.state || ''));\n"
961" tr.appendChild(tdState);\n"
962" tr.appendChild(el('td', 'mono', c.cpu || '\\u2014'));\n"
963" tr.appendChild(el('td', 'mono', c.mem || '\\u2014'));\n"
964" var tdAct = el('td');\n"
965" var box = el('div', 'acts');\n"
966" function btn(op, cls){ var b = el('button', 'sm ' + cls, op);\n"
967" b.type = 'button'; b.addEventListener('click', function(){ act(c, op); }); return b; }\n"
968" function logBtn(){ var b = el('button', 'sm ghost', 'logs');\n"
969" b.type = 'button'; b.addEventListener('click', function(){ openLogs(c); }); return b; }\n"
970" var running = (c.state || '').toLowerCase() === 'running';\n"
971" if (running) {\n"
972" box.appendChild(btn('stop', 'danger'));\n"
973" box.appendChild(btn('restart', 'ghost'));\n"
974" } else {\n"
975" box.appendChild(btn('start', ''));\n"
976" }\n"
977" box.appendChild(logBtn());\n"
978" tdAct.appendChild(box);\n"
979" tr.appendChild(tdAct);\n"
980" tb.appendChild(tr);\n"
981" });\n"
982" $('empty').classList.toggle('hide', shown !== 0);\n"
983" }\n"
984"\n"
985" function refresh(){\n"
986" get('list').then(function(d){\n"
987" DATA = d;\n"
988" var s = d.summary || {};\n"
989" txt('k-total', s.total);\n"
990" txt('k-run', s.running);\n"
991" txt('k-exit', s.exited);\n"
992" txt('k-pause', s.paused);\n"
993" var rt = d.runtime || {};\n"
994" txt('k-rt', rt.available ? (rt.label || 'yes') : 'none');\n"
995" if (!rt.available) {\n"
996" badge(false, 'no runtime');\n"
997" $('note').textContent = d.message || 'neither docker nor podman found on this node';\n"
998" } else if (d.daemon_available === false) {\n"
999" badge(false, 'daemon down');\n"
1000" $('note').textContent = d.error || 'runtime daemon is not reachable';\n"
1001" } else {\n"
1002" badge(true, rt.label || 'ready');\n"
1003" $('note').textContent = (s.total || 0) + ' container(s) on this node';\n"
1004" }\n"
1005" render();\n"
1006" }).catch(function(e){\n"
1007" badge(false, 'error');\n"
1008" $('note').textContent = 'request failed: ' + e;\n"
1009" });\n"
1010" }\n"
1011"\n"
1012" $('refreshBtn').addEventListener('click', refresh);\n"
1013" $('reloadBtn').addEventListener('click', refresh);\n"
1014" $('q').addEventListener('input', render);\n"
1015" $('q').addEventListener('keydown', function(e){ if (e.key === 'Enter') refresh(); });\n"
1016" $('state').addEventListener('change', render);\n"
1017" $('logClose').addEventListener('click', function(){ $('logCard').classList.add('hide'); });\n"
1018" $('logReload').addEventListener('click', function(){\n"
1019" if (LOG_CID) get('logs', '&cid=' + encodeURIComponent(LOG_CID)).then(function(d){\n"
1020" $('logBody').textContent = d.ok ? (d.text || '(empty)') : ('error: ' + (d.error || 'unknown'));\n"
1021" });\n"
1022" });\n"
1023"\n"
1024" refresh();\n"
1025"})();\n"
1026"</script></body></html>\n", stdout);
1027 return 0;
1028}
1029/* ------------------------------------------------------------------ */
1030/* Node auth */
1031/* ------------------------------------------------------------------ */
1032
1033/*
1034 * Every node plugin must refuse an unauthenticated caller before it touches
1035 * the container runtime. scorpiox-server runs plugins as CGI on the node API
1036 * (:8150), which is reachable from the LAN, so without this a POST
1037 * ?action=control would let anyone stop containers without knowing the node
1038 * password. Accepted forms, matching the rest of the node API:
1039 *
1040 * X-Bot-Password: <pwd> (what bot-web proxies with)
1041 * Authorization: Bearer <pwd>
1042 * ?pwd=<pwd> (what the plugin iframe appends)
1043 *
1044 * If BOT_PASSWORD is unset the node is running in explicitly open mode and the
1045 * check is a no-op, exactly like terminal_tmux.c and node_rdp.c.
1046 */
1047static void require_node_auth(void)
1048{
1049 const char *np = getenv("BOT_PASSWORD");
1050 const char *xp;
1051 const char *auth;
1052 char qpwd[256];
1053 const char *qs;
1054
1055 if (!np || !*np) return;
1056
1057 xp = getenv("HTTP_X_BOT_PASSWORD");
1058 if (xp && strcmp(xp, np) == 0) return;
1059
1060 auth = getenv("HTTP_AUTHORIZATION");
1061 if (auth) {
1062 while (*auth == ' ') auth++;
1063 if (strncmp(auth, "Bearer ", 7) == 0) {
1064 auth += 7;
1065 while (*auth == ' ') auth++;
1066 if (strcmp(auth, np) == 0) return;
1067 }
1068 }
1069
1070 qs = getenv("QUERY_STRING");
1071 if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
1072 return;
1073
1074 fputs("Status: 401 Unauthorized\r\n"
1075 "Content-Type: application/json; charset=utf-8\r\n"
1076 "Cache-Control: no-store\r\n"
1077 "X-Content-Type-Options: nosniff\r\n\r\n"
1078 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
1079 exit(0);
1080}
1081
1082/* ------------------------------------------------------------------ */
1083/* POST body */
1084/* ------------------------------------------------------------------ */
1085
1086/* ------------------------------------------------------------------ */
1087/* POST body */
1088/* ------------------------------------------------------------------ */
1089
1090static char *read_post_body(void)
1091{
1092 const char *cl = getenv("CONTENT_LENGTH");
1093 long want;
1094 size_t got = 0;
1095 char *buf;
1096
1097 if (!cl || !*cl) return NULL;
1098 want = strtol(cl, NULL, 10);
1099 if (want <= 0) return NULL;
1100 if (want > 8192) want = 8192;
1101
1102 buf = (char *)malloc((size_t)want + 1);
1103 if (!buf) return NULL;
1104 while (got < (size_t)want) {
1105 size_t n = fread(buf + got, 1, (size_t)want - got, stdin);
1106 if (n == 0) break;
1107 got += n;
1108 }
1109 buf[got] = '\0';
1110 return buf;
1111}
1112
1113/* ------------------------------------------------------------------ */
1114/* main */
1115/* ------------------------------------------------------------------ */
1116
1117static int is_post_request(void)
1118{
1119 const char *m = getenv("REQUEST_METHOD");
1120 return m && strcmp(m, "POST") == 0;
1121}
1122
1123int main(int argc, char **argv)
1124{
1125 const char *qs;
1126 char *body = NULL;
1127
1128 if (argc > 1) {
1129 if (strcmp(argv[1], "--meta") == 0) return mode_meta();
1130 if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; }
1131 if (strcmp(argv[1], "--help") == 0) {
1132 puts("plugin_docker " PLUGIN_VER);
1133 puts("usage: plugin_docker [--meta|--version|--help]");
1134 puts(" QUERY_STRING='action=list|info|logs&cid=<id>' plugin_docker");
1135 return 0;
1136 }
1137 }
1138 if (getenv("SX_PLUGIN_META")) return mode_meta();
1139
1140 require_node_auth();
1141
1142 qs = getenv("QUERY_STRING");
1143 if (!qs) qs = "";
1144
1145 if (is_post_request()) body = read_post_body();
1146
1147 if (strstr(qs, "action=") || strstr(qs, "format=json") || (body && strstr(body, "action="))) {
1148 int rc = mode_json(qs, body, is_post_request());
1149 free(body);
1150 return rc;
1151 }
1152
1153 {
1154 char embedv[16];
1155 free(body);
1156 embedv[0] = '\0';
1157 if (get_query_val(qs, "embed", embedv, sizeof(embedv)))
1158 return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0);
1159 }
1160 return mode_html(0);
1161}