| 1 | /* |
| 2 | * plugin_disks - SCORPIOX BOT open-source local storage inspector 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=mounts | ?action=dirs&root=workspace|home | ?format=json |
| 7 | * -> JSON node API |
| 8 | * 3. GET (default) -> responsive HTML dashboard |
| 9 | * |
| 10 | * Local node only. Reads the local kernel interfaces (/proc/mounts + statvfs on |
| 11 | * Linux, getmntinfo on macOS, GetLogicalDriveStringsA + GetDiskFreeSpaceExA on |
| 12 | * Windows). Makes ZERO outbound network requests, opens no sockets, runs no |
| 13 | * remote commands and reads no credentials. |
| 14 | * |
| 15 | * Directory scanning is deliberately bounded: only the allowlisted roots |
| 16 | * /workspace and $HOME may be walked, never an arbitrary path from the query |
| 17 | * string, and the walk is capped in depth and in total entries visited. |
| 18 | * |
| 19 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 20 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 21 | * scorpiox-server on the node. |
| 22 | * |
| 23 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 24 | */ |
| 25 | |
| 26 | #if defined(__APPLE__) |
| 27 | /* sys/mount.h and friends pull BSD types that strict c99 would hide */ |
| 28 | # define _DARWIN_C_SOURCE 1 |
| 29 | #elif !defined(_WIN32) |
| 30 | # define _POSIX_C_SOURCE 200809L |
| 31 | # define _DEFAULT_SOURCE 1 |
| 32 | #endif |
| 33 | |
| 34 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 35 | # define _WIN32_WINNT 0x0601 /* GetDiskFreeSpaceEx / GetVolumeInformationA */ |
| 36 | #endif |
| 37 | |
| 38 | #include <stdio.h> |
| 39 | #include <stdlib.h> |
| 40 | #include <string.h> |
| 41 | #include <time.h> |
| 42 | #include <ctype.h> |
| 43 | #include <errno.h> |
| 44 | |
| 45 | #if defined(_WIN32) |
| 46 | |
| 47 | # define WIN32_LEAN_AND_MEAN |
| 48 | # include <windows.h> |
| 49 | # include <direct.h> |
| 50 | # include <io.h> |
| 51 | |
| 52 | #else |
| 53 | |
| 54 | # include <unistd.h> |
| 55 | # include <dirent.h> |
| 56 | # include <sys/types.h> |
| 57 | # include <sys/stat.h> |
| 58 | # include <sys/statvfs.h> |
| 59 | |
| 60 | # if defined(__APPLE__) |
| 61 | # include <sys/mount.h> |
| 62 | # include <sys/param.h> |
| 63 | # endif |
| 64 | |
| 65 | #endif |
| 66 | |
| 67 | #include "bot_theme_plugin.h" |
| 68 | |
| 69 | #define PLUGIN_SLUG "disks" |
| 70 | #define PLUGIN_ID "plugin_disks" |
| 71 | #define PLUGIN_VER "1.0.2" |
| 72 | |
| 73 | #define MAX_MOUNTS 256 |
| 74 | #define MAX_DIRS 512 |
| 75 | #define MAX_SCAN_ENTRIES 120000 |
| 76 | #define MAX_DEPTH 8 |
| 77 | #define MAX_NAME 256 |
| 78 | #define MAX_PATH 1024 |
| 79 | |
| 80 | /* ------------------------------------------------------------------ */ |
| 81 | /* Small utilities */ |
| 82 | /* ------------------------------------------------------------------ */ |
| 83 | |
| 84 | /* Percent-decode in place ('+' becomes space). */ |
| 85 | static void url_decode(char *s) |
| 86 | { |
| 87 | char *o = s; |
| 88 | if (!s) return; |
| 89 | while (*s) { |
| 90 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 91 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 92 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 93 | *o++ = (char)((hi << 4) | lo); |
| 94 | s += 3; |
| 95 | } else if (*s == '+') { |
| 96 | *o++ = ' '; |
| 97 | s++; |
| 98 | } else { |
| 99 | *o++ = *s++; |
| 100 | } |
| 101 | } |
| 102 | *o = '\0'; |
| 103 | } |
| 104 | |
| 105 | /* Read one parameter (decoded) out of a form/query string. */ |
| 106 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 107 | { |
| 108 | size_t klen; |
| 109 | const char *p; |
| 110 | |
| 111 | if (!out || outsz == 0) return 0; |
| 112 | out[0] = '\0'; |
| 113 | if (!qs || !key) return 0; |
| 114 | klen = strlen(key); |
| 115 | |
| 116 | for (p = qs; *p; ) { |
| 117 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 118 | const char *v = p + klen + 1; |
| 119 | size_t i = 0; |
| 120 | while (*v && *v != '&' && i + 1 < outsz) |
| 121 | out[i++] = *v++; |
| 122 | out[i] = '\0'; |
| 123 | url_decode(out); |
| 124 | return 1; |
| 125 | } |
| 126 | p = strchr(p, '&'); |
| 127 | if (!p) break; |
| 128 | p++; |
| 129 | } |
| 130 | return 0; |
| 131 | } |
| 132 | |
| 133 | static void json_str(const char *s) |
| 134 | { |
| 135 | putchar('"'); |
| 136 | for (; s && *s; s++) { |
| 137 | unsigned char c = (unsigned char)*s; |
| 138 | switch (c) { |
| 139 | case '"': fputs("\\\"", stdout); break; |
| 140 | case '\\': fputs("\\\\", stdout); break; |
| 141 | case '\n': fputs("\\n", stdout); break; |
| 142 | case '\r': fputs("\\r", stdout); break; |
| 143 | case '\t': fputs("\\t", stdout); break; |
| 144 | default: |
| 145 | if (c < 0x20) printf("\\u%04x", (unsigned)c); |
| 146 | else putchar((int)c); |
| 147 | } |
| 148 | } |
| 149 | putchar('"'); |
| 150 | } |
| 151 | |
| 152 | static void utc_now(char *buf, size_t sz) |
| 153 | { |
| 154 | time_t t = time(NULL); |
| 155 | struct tm tmv; |
| 156 | #if defined(_WIN32) |
| 157 | gmtime_s(&tmv, &t); |
| 158 | #else |
| 159 | gmtime_r(&t, &tmv); |
| 160 | #endif |
| 161 | if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { |
| 162 | strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); |
| 163 | buf[sz - 1] = '\0'; |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | static long node_pid(void) |
| 168 | { |
| 169 | #if defined(_WIN32) |
| 170 | return (long)GetCurrentProcessId(); |
| 171 | #else |
| 172 | return (long)getpid(); |
| 173 | #endif |
| 174 | } |
| 175 | |
| 176 | static double clamp_pct(double v) |
| 177 | { |
| 178 | if (v < 0.0) return 0.0; |
| 179 | if (v > 100.0) return 100.0; |
| 180 | return v; |
| 181 | } |
| 182 | |
| 183 | /* Monotonic-ish millisecond clock used only to report scan duration. */ |
| 184 | static long long now_ms(void) |
| 185 | { |
| 186 | #if defined(_WIN32) |
| 187 | return (long long)GetTickCount64(); |
| 188 | #else |
| 189 | struct timespec ts; |
| 190 | if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; |
| 191 | return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); |
| 192 | #endif |
| 193 | } |
| 194 | |
| 195 | static void copy_str(char *dst, size_t dstsz, const char *src) |
| 196 | { |
| 197 | size_t n; |
| 198 | if (!dst || dstsz == 0) return; |
| 199 | if (!src) { dst[0] = '\0'; return; } |
| 200 | n = strlen(src); |
| 201 | if (n >= dstsz) n = dstsz - 1; |
| 202 | memcpy(dst, src, n); |
| 203 | dst[n] = '\0'; |
| 204 | } |
| 205 | |
| 206 | /* ------------------------------------------------------------------ */ |
| 207 | /* Node authentication */ |
| 208 | /* ------------------------------------------------------------------ */ |
| 209 | |
| 210 | /* |
| 211 | * The node API on :8150 is reachable from the LAN. Every request except |
| 212 | * --meta discovery must prove it knows the node password. Accepted forms |
| 213 | * match the rest of the node API: X-Bot-Password (what bot-web proxies |
| 214 | * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). |
| 215 | * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how |
| 216 | * a developer runs it locally from a shell. |
| 217 | */ |
| 218 | static void require_node_auth(void) |
| 219 | { |
| 220 | const char *np = getenv("BOT_PASSWORD"); |
| 221 | const char *xp; |
| 222 | const char *auth; |
| 223 | char qpwd[256]; |
| 224 | const char *qs; |
| 225 | |
| 226 | if (!np || !*np) return; |
| 227 | |
| 228 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 229 | if (xp && strcmp(xp, np) == 0) return; |
| 230 | |
| 231 | auth = getenv("HTTP_AUTHORIZATION"); |
| 232 | if (auth) { |
| 233 | while (*auth == ' ') auth++; |
| 234 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 235 | auth += 7; |
| 236 | while (*auth == ' ') auth++; |
| 237 | if (strcmp(auth, np) == 0) return; |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | qs = getenv("QUERY_STRING"); |
| 242 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 243 | return; |
| 244 | |
| 245 | fputs("Status: 401 Unauthorized\r\n" |
| 246 | "Content-Type: application/json; charset=utf-8\r\n" |
| 247 | "Cache-Control: no-store\r\n" |
| 248 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 249 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 250 | exit(0); |
| 251 | } |
| 252 | |
| 253 | /* ------------------------------------------------------------------ */ |
| 254 | /* Mount table */ |
| 255 | /* ------------------------------------------------------------------ */ |
| 256 | |
| 257 | typedef struct { |
| 258 | char device[MAX_NAME]; |
| 259 | char fstype[64]; |
| 260 | char mount[MAX_PATH]; |
| 261 | unsigned long long total_bytes; |
| 262 | unsigned long long used_bytes; |
| 263 | unsigned long long free_bytes; |
| 264 | unsigned long long avail_bytes; |
| 265 | unsigned long long inodes_total; |
| 266 | unsigned long long inodes_used; |
| 267 | int has_inodes; |
| 268 | } sx_mount_t; |
| 269 | |
| 270 | #if !defined(_WIN32) |
| 271 | |
| 272 | /* Filesystems that report kernel-internal state rather than user storage. */ |
| 273 | static int pseudo_fstype(const char *fs) |
| 274 | { |
| 275 | static const char *PSEUDO[] = { |
| 276 | "proc", "sysfs", "cgroup", "cgroup2", "devpts", "devtmpfs", |
| 277 | "securityfs", "pstore", "bpf", "debugfs", "tracefs", "hugetlbfs", |
| 278 | "mqueue", "autofs", "configfs", "fusectl", "efivarfs", "rpc_pipefs", |
| 279 | "nsfs", "binfmt_misc", "selinuxfs", "fuse.gvfsd-fuse", "fuse.portal", |
| 280 | "procfs", "devfs", "none", NULL |
| 281 | }; |
| 282 | int i; |
| 283 | for (i = 0; PSEUDO[i]; i++) |
| 284 | if (strcmp(fs, PSEUDO[i]) == 0) return 1; |
| 285 | return 0; |
| 286 | } |
| 287 | |
| 288 | /* |
| 289 | * Kernel mountpoints that exist only to back kernel state. /dev, /sys, /proc |
| 290 | * and anything below them are never interesting to a user asking about |
| 291 | * storage; /run is a real tmpfs and is kept. |
| 292 | */ |
| 293 | static int pseudo_mountpoint(const char *mp) |
| 294 | { |
| 295 | static const char *PREFIX[] = { "/sys", "/proc", "/dev", NULL }; |
| 296 | int i; |
| 297 | for (i = 0; PREFIX[i]; i++) { |
| 298 | size_t n = strlen(PREFIX[i]); |
| 299 | if (strncmp(mp, PREFIX[i], n) == 0 && (mp[n] == '\0' || mp[n] == '/')) |
| 300 | return 1; |
| 301 | } |
| 302 | return 0; |
| 303 | } |
| 304 | |
| 305 | #endif /* !_WIN32 */ |
| 306 | |
| 307 | #if !defined(_WIN32) && !defined(__APPLE__) |
| 308 | |
| 309 | /* /proc/mounts and /etc/mtab escape space, tab, newline and backslash as octal. */ |
| 310 | static void unescape_mount_field(char *s) |
| 311 | { |
| 312 | char *o = s; |
| 313 | while (*s) { |
| 314 | if (*s == '\\' && s[1] >= '0' && s[1] <= '3' && |
| 315 | s[2] >= '0' && s[2] <= '7' && s[3] >= '0' && s[3] <= '7') { |
| 316 | *o++ = (char)(((s[1] - '0') << 6) | ((s[2] - '0') << 3) | (s[3] - '0')); |
| 317 | s += 4; |
| 318 | } else { |
| 319 | *o++ = *s++; |
| 320 | } |
| 321 | } |
| 322 | *o = '\0'; |
| 323 | } |
| 324 | |
| 325 | static void fill_vfs(const char *mp, sx_mount_t *m) |
| 326 | { |
| 327 | struct statvfs vfs; |
| 328 | if (statvfs(mp, &vfs) != 0) return; |
| 329 | m->total_bytes = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize; |
| 330 | m->free_bytes = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize; |
| 331 | m->avail_bytes = (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize; |
| 332 | m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; |
| 333 | if (vfs.f_files > 0) { |
| 334 | m->has_inodes = 1; |
| 335 | m->inodes_total = (unsigned long long)vfs.f_files; |
| 336 | m->inodes_used = m->inodes_total >= (unsigned long long)vfs.f_ffree |
| 337 | ? m->inodes_total - (unsigned long long)vfs.f_ffree : 0; |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | #endif /* !_WIN32 */ |
| 342 | |
| 343 | #if defined(__APPLE__) |
| 344 | |
| 345 | static int collect_mounts(sx_mount_t *out, int max) |
| 346 | { |
| 347 | struct statfs *mnt = NULL; |
| 348 | int n, i, count = 0; |
| 349 | |
| 350 | n = getmntinfo(&mnt, MNT_NOWAIT); |
| 351 | if (n <= 0) return 0; |
| 352 | |
| 353 | for (i = 0; i < n && count < max; i++) { |
| 354 | sx_mount_t *m = &out[count]; |
| 355 | unsigned long long bs = (unsigned long long)mnt[i].f_bsize; |
| 356 | if (pseudo_fstype(mnt[i].f_fstypename)) continue; |
| 357 | if (pseudo_mountpoint(mnt[i].f_mntonname)) continue; |
| 358 | memset(m, 0, sizeof(*m)); |
| 359 | copy_str(m->device, sizeof(m->device), mnt[i].f_mntfromname); |
| 360 | copy_str(m->fstype, sizeof(m->fstype), mnt[i].f_fstypename); |
| 361 | copy_str(m->mount, sizeof(m->mount), mnt[i].f_mntonname); |
| 362 | m->total_bytes = (unsigned long long)mnt[i].f_blocks * bs; |
| 363 | m->free_bytes = (unsigned long long)mnt[i].f_bfree * bs; |
| 364 | m->avail_bytes = (unsigned long long)mnt[i].f_bavail * bs; |
| 365 | m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; |
| 366 | if (mnt[i].f_files > 0) { |
| 367 | m->has_inodes = 1; |
| 368 | m->inodes_total = (unsigned long long)mnt[i].f_files; |
| 369 | m->inodes_used = m->inodes_total >= (unsigned long long)mnt[i].f_ffree |
| 370 | ? m->inodes_total - (unsigned long long)mnt[i].f_ffree : 0; |
| 371 | } |
| 372 | count++; |
| 373 | } |
| 374 | return count; |
| 375 | } |
| 376 | |
| 377 | #elif defined(_WIN32) |
| 378 | |
| 379 | static int collect_mounts(sx_mount_t *out, int max) |
| 380 | { |
| 381 | char drives[512]; |
| 382 | DWORD n; |
| 383 | int count = 0; |
| 384 | const char *p; |
| 385 | |
| 386 | n = GetLogicalDriveStringsA(sizeof(drives) - 1, drives); |
| 387 | if (n == 0) return 0; |
| 388 | |
| 389 | for (p = drives; *p && count < max; p += strlen(p) + 1) { |
| 390 | ULARGE_INTEGER avail, total, totalfree; |
| 391 | char fsname[64] = "unknown"; |
| 392 | sx_mount_t *m; |
| 393 | |
| 394 | if (GetDriveTypeA(p) == DRIVE_NO_ROOT_DIR) continue; |
| 395 | if (!GetDiskFreeSpaceExA(p, &avail, &total, &totalfree)) continue; |
| 396 | |
| 397 | m = &out[count]; |
| 398 | memset(m, 0, sizeof(*m)); |
| 399 | copy_str(m->device, sizeof(m->device), p); |
| 400 | copy_str(m->mount, sizeof(m->mount), p); |
| 401 | if (GetVolumeInformationA(p, NULL, 0, NULL, NULL, NULL, fsname, (DWORD)sizeof(fsname)) && fsname[0]) |
| 402 | copy_str(m->fstype, sizeof(m->fstype), fsname); |
| 403 | else |
| 404 | copy_str(m->fstype, sizeof(m->fstype), "win32"); |
| 405 | |
| 406 | m->total_bytes = (unsigned long long)total.QuadPart; |
| 407 | m->free_bytes = (unsigned long long)totalfree.QuadPart; |
| 408 | m->avail_bytes = (unsigned long long)avail.QuadPart; |
| 409 | m->used_bytes = m->total_bytes >= m->free_bytes ? m->total_bytes - m->free_bytes : 0; |
| 410 | count++; |
| 411 | } |
| 412 | return count; |
| 413 | } |
| 414 | |
| 415 | #else /* Linux and other POSIX */ |
| 416 | |
| 417 | static int collect_mounts(sx_mount_t *out, int max) |
| 418 | { |
| 419 | FILE *fp; |
| 420 | char line[2048]; |
| 421 | int count = 0; |
| 422 | |
| 423 | fp = fopen("/proc/mounts", "r"); |
| 424 | if (!fp) fp = fopen("/etc/mtab", "r"); |
| 425 | if (!fp) return 0; |
| 426 | |
| 427 | while (fgets(line, sizeof(line), fp) && count < max) { |
| 428 | char dev[MAX_NAME], mp[MAX_PATH], fs[64]; |
| 429 | int i = 0; |
| 430 | char *tok[3]; |
| 431 | char *p = line; |
| 432 | |
| 433 | /* split the first three whitespace-separated fields */ |
| 434 | while (i < 3) { |
| 435 | while (*p == ' ' || *p == '\t') p++; |
| 436 | if (!*p || *p == '\n') break; |
| 437 | tok[i++] = p; |
| 438 | while (*p && *p != ' ' && *p != '\t' && *p != '\n') p++; |
| 439 | if (*p) *p++ = '\0'; |
| 440 | } |
| 441 | if (i < 3) continue; |
| 442 | |
| 443 | copy_str(dev, sizeof(dev), tok[0]); |
| 444 | copy_str(mp, sizeof(mp), tok[1]); |
| 445 | copy_str(fs, sizeof(fs), tok[2]); |
| 446 | unescape_mount_field(dev); |
| 447 | unescape_mount_field(mp); |
| 448 | |
| 449 | if (pseudo_fstype(fs)) continue; |
| 450 | if (pseudo_mountpoint(mp)) continue; |
| 451 | |
| 452 | /* /proc/mounts can list the same mountpoint more than once (a bind |
| 453 | * mount, or a container overlay that repeats a host mount). Keep the |
| 454 | * first entry per mountpoint so the dashboard does not double-count. */ |
| 455 | { |
| 456 | int dup = 0, k; |
| 457 | for (k = 0; k < count; k++) { |
| 458 | if (strcmp(out[k].mount, mp) == 0) { dup = 1; break; } |
| 459 | } |
| 460 | if (dup) continue; |
| 461 | } |
| 462 | |
| 463 | memset(&out[count], 0, sizeof(out[count])); |
| 464 | copy_str(out[count].device, sizeof(out[count].device), dev); |
| 465 | copy_str(out[count].fstype, sizeof(out[count].fstype), fs); |
| 466 | copy_str(out[count].mount, sizeof(out[count].mount), mp); |
| 467 | fill_vfs(mp, &out[count]); |
| 468 | count++; |
| 469 | } |
| 470 | fclose(fp); |
| 471 | return count; |
| 472 | } |
| 473 | |
| 474 | #endif |
| 475 | |
| 476 | /* Largest first. Used for display order. */ |
| 477 | static int mount_cmp(const void *a, const void *b) |
| 478 | { |
| 479 | const sx_mount_t *x = (const sx_mount_t *)a; |
| 480 | const sx_mount_t *y = (const sx_mount_t *)b; |
| 481 | if (x->total_bytes < y->total_bytes) return 1; |
| 482 | if (x->total_bytes > y->total_bytes) return -1; |
| 483 | return strcmp(x->mount, y->mount); |
| 484 | } |
| 485 | |
| 486 | static const char *platform_name(void) |
| 487 | { |
| 488 | #if defined(_WIN32) |
| 489 | return "windows"; |
| 490 | #elif defined(__APPLE__) |
| 491 | return "macos"; |
| 492 | #else |
| 493 | return "linux"; |
| 494 | #endif |
| 495 | } |
| 496 | |
| 497 | /* ------------------------------------------------------------------ */ |
| 498 | /* Bounded 1-level directory sizing */ |
| 499 | /* ------------------------------------------------------------------ */ |
| 500 | |
| 501 | typedef struct { |
| 502 | char name[MAX_NAME]; |
| 503 | char path[MAX_PATH]; |
| 504 | unsigned long long bytes; |
| 505 | int is_dir; |
| 506 | } dir_sz_t; |
| 507 | |
| 508 | typedef struct { |
| 509 | unsigned long long visited; |
| 510 | int truncated; |
| 511 | } scan_state_t; |
| 512 | |
| 513 | static int skip_entry_name(const char *n) |
| 514 | { |
| 515 | if (!n || !*n) return 1; |
| 516 | if (strcmp(n, ".") == 0 || strcmp(n, "..") == 0) return 1; |
| 517 | return 0; |
| 518 | } |
| 519 | |
| 520 | #if defined(_WIN32) |
| 521 | |
| 522 | static unsigned long long sum_dir_win(const char *dir, int depth, scan_state_t *st) |
| 523 | { |
| 524 | char pattern[MAX_PATH]; |
| 525 | WIN32_FIND_DATAA fd; |
| 526 | HANDLE h; |
| 527 | unsigned long long total = 0; |
| 528 | |
| 529 | if (depth > MAX_DEPTH || st->truncated) return 0; |
| 530 | sprintf(pattern, "%s\\*", dir); |
| 531 | h = FindFirstFileA(pattern, &fd); |
| 532 | if (h == INVALID_HANDLE_VALUE) return 0; |
| 533 | |
| 534 | do { |
| 535 | char child[MAX_PATH]; |
| 536 | if (skip_entry_name(fd.cFileName)) continue; |
| 537 | if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue; |
| 538 | if (++st->visited > MAX_SCAN_ENTRIES) { st->truncated = 1; break; } |
| 539 | sprintf(child, "%s\\%s", dir, fd.cFileName); |
| 540 | if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) |
| 541 | total += sum_dir_win(child, depth + 1, st); |
| 542 | else |
| 543 | total += ((unsigned long long)fd.nFileSizeHigh << 32) | (unsigned long long)fd.nFileSizeLow; |
| 544 | } while (FindNextFileA(h, &fd)); |
| 545 | |
| 546 | FindClose(h); |
| 547 | return total; |
| 548 | } |
| 549 | |
| 550 | #else |
| 551 | |
| 552 | static unsigned long long sum_dir_posix(const char *dir, int depth, scan_state_t *st) |
| 553 | { |
| 554 | DIR *d; |
| 555 | struct dirent *e; |
| 556 | unsigned long long total = 0; |
| 557 | |
| 558 | if (depth > MAX_DEPTH || st->truncated) return 0; |
| 559 | d = opendir(dir); |
| 560 | if (!d) return 0; |
| 561 | |
| 562 | while ((e = readdir(d)) != NULL) { |
| 563 | char child[MAX_PATH]; |
| 564 | struct stat sb; |
| 565 | if (skip_entry_name(e->d_name)) continue; |
| 566 | if (++st->visited > MAX_SCAN_ENTRIES) { st->truncated = 1; break; } |
| 567 | if (snprintf(child, sizeof(child), "%s/%s", dir, e->d_name) >= (int)sizeof(child)) continue; |
| 568 | /* lstat: symlinks are never followed, so a link back up the tree |
| 569 | * cannot make the walk unbounded. */ |
| 570 | if (lstat(child, &sb) != 0) continue; |
| 571 | if (S_ISLNK(sb.st_mode)) continue; |
| 572 | if (S_ISDIR(sb.st_mode)) |
| 573 | total += sum_dir_posix(child, depth + 1, st); |
| 574 | else if (S_ISREG(sb.st_mode)) |
| 575 | total += (unsigned long long)sb.st_size; |
| 576 | } |
| 577 | closedir(d); |
| 578 | return total; |
| 579 | } |
| 580 | |
| 581 | #endif |
| 582 | |
| 583 | static int dir_cmp(const void *a, const void *b) |
| 584 | { |
| 585 | const dir_sz_t *x = (const dir_sz_t *)a; |
| 586 | const dir_sz_t *y = (const dir_sz_t *)b; |
| 587 | if (x->bytes < y->bytes) return 1; |
| 588 | if (x->bytes > y->bytes) return -1; |
| 589 | return strcmp(x->name, y->name); |
| 590 | } |
| 591 | |
| 592 | /* Resolve an allowlisted root token to a real path. |
| 593 | * Returns 1 resolved, |
| 594 | * 0 token is not an allowlisted root, |
| 595 | * -1 token is allowlisted but the root does not exist on this node. */ |
| 596 | static int resolve_root(const char *kind, char *out, size_t outsz, const char **label) |
| 597 | { |
| 598 | if (!kind || !*kind) return 0; |
| 599 | |
| 600 | if (strcmp(kind, "workspace") == 0) { |
| 601 | *label = "/workspace"; |
| 602 | #if defined(_WIN32) |
| 603 | return -1; /* no /workspace on a native Windows node */ |
| 604 | #else |
| 605 | if (access("/workspace", R_OK | X_OK) != 0) return -1; |
| 606 | copy_str(out, outsz, "/workspace"); |
| 607 | return 1; |
| 608 | #endif |
| 609 | } |
| 610 | |
| 611 | if (strcmp(kind, "home") == 0) { |
| 612 | #if defined(_WIN32) |
| 613 | const char *up = getenv("USERPROFILE"); |
| 614 | if (!up || !*up) return -1; |
| 615 | copy_str(out, outsz, up); |
| 616 | #else |
| 617 | const char *hp = getenv("HOME"); |
| 618 | if (!hp || !*hp) return -1; |
| 619 | copy_str(out, outsz, hp); |
| 620 | #endif |
| 621 | *label = "$HOME"; |
| 622 | return 1; |
| 623 | } |
| 624 | |
| 625 | return 0; |
| 626 | } |
| 627 | |
| 628 | static int scan_root(const char *root, dir_sz_t *out, int max, int *count_out, int *truncated, int *root_kind) |
| 629 | { |
| 630 | scan_state_t st; |
| 631 | int count = 0; |
| 632 | |
| 633 | st.visited = 0; |
| 634 | st.truncated = 0; |
| 635 | *truncated = 0; |
| 636 | *root_kind = 0; |
| 637 | (void)root_kind; |
| 638 | |
| 639 | #if defined(_WIN32) |
| 640 | { |
| 641 | char pattern[MAX_PATH]; |
| 642 | WIN32_FIND_DATAA fd; |
| 643 | HANDLE h; |
| 644 | sprintf(pattern, "%s\\*", root); |
| 645 | h = FindFirstFileA(pattern, &fd); |
| 646 | if (h == INVALID_HANDLE_VALUE) { *count_out = 0; return 0; } |
| 647 | do { |
| 648 | dir_sz_t *e; |
| 649 | if (skip_entry_name(fd.cFileName)) continue; |
| 650 | if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue; |
| 651 | if (count >= max) { st.truncated = 1; break; } |
| 652 | if (++st.visited > MAX_SCAN_ENTRIES) { st.truncated = 1; break; } |
| 653 | e = &out[count]; |
| 654 | memset(e, 0, sizeof(*e)); |
| 655 | copy_str(e->name, sizeof(e->name), fd.cFileName); |
| 656 | sprintf(e->path, "%s\\%s", root, fd.cFileName); |
| 657 | if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { |
| 658 | e->is_dir = 1; |
| 659 | e->bytes = sum_dir_win(e->path, 1, &st); |
| 660 | } else { |
| 661 | e->bytes = ((unsigned long long)fd.nFileSizeHigh << 32) | (unsigned long long)fd.nFileSizeLow; |
| 662 | } |
| 663 | count++; |
| 664 | } while (FindNextFileA(h, &fd)); |
| 665 | FindClose(h); |
| 666 | } |
| 667 | #else |
| 668 | { |
| 669 | DIR *d = opendir(root); |
| 670 | struct dirent *de; |
| 671 | if (!d) { *count_out = 0; return 0; } |
| 672 | while ((de = readdir(d)) != NULL) { |
| 673 | dir_sz_t *e; |
| 674 | struct stat sb; |
| 675 | char path[MAX_PATH]; |
| 676 | if (skip_entry_name(de->d_name)) continue; |
| 677 | if (count >= max) { st.truncated = 1; break; } |
| 678 | if (++st.visited > MAX_SCAN_ENTRIES) { st.truncated = 1; break; } |
| 679 | if (snprintf(path, sizeof(path), "%s/%s", root, de->d_name) >= (int)sizeof(path)) continue; |
| 680 | if (lstat(path, &sb) != 0) continue; |
| 681 | if (S_ISLNK(sb.st_mode)) continue; |
| 682 | e = &out[count]; |
| 683 | memset(e, 0, sizeof(*e)); |
| 684 | copy_str(e->name, sizeof(e->name), de->d_name); |
| 685 | copy_str(e->path, sizeof(e->path), path); |
| 686 | if (S_ISDIR(sb.st_mode)) { |
| 687 | e->is_dir = 1; |
| 688 | e->bytes = sum_dir_posix(path, 1, &st); |
| 689 | } else if (S_ISREG(sb.st_mode)) { |
| 690 | e->bytes = (unsigned long long)sb.st_size; |
| 691 | } |
| 692 | count++; |
| 693 | } |
| 694 | closedir(d); |
| 695 | } |
| 696 | #endif |
| 697 | |
| 698 | if (count > 1) qsort(out, (size_t)count, sizeof(out[0]), dir_cmp); |
| 699 | *truncated = st.truncated; |
| 700 | *count_out = count; |
| 701 | return 1; |
| 702 | } |
| 703 | |
| 704 | /* ------------------------------------------------------------------ */ |
| 705 | /* Modes */ |
| 706 | /* ------------------------------------------------------------------ */ |
| 707 | |
| 708 | static int mode_meta(void) |
| 709 | { |
| 710 | puts("{\"name\":\"disks\",\"desc\":\"Local storage\"}"); |
| 711 | return 0; |
| 712 | } |
| 713 | |
| 714 | static void json_header(void) |
| 715 | { |
| 716 | /* Deliberately no Content-Length - the server owns framing. */ |
| 717 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 718 | "Cache-Control: no-store\r\n" |
| 719 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 720 | } |
| 721 | |
| 722 | static void emit_mounts(void) |
| 723 | { |
| 724 | sx_mount_t mnt[MAX_MOUNTS]; |
| 725 | int i, n; |
| 726 | |
| 727 | memset(mnt, 0, sizeof(mnt)); |
| 728 | n = collect_mounts(mnt, MAX_MOUNTS); |
| 729 | if (n > 1) qsort(mnt, (size_t)n, sizeof(mnt[0]), mount_cmp); |
| 730 | |
| 731 | fputs("[", stdout); |
| 732 | for (i = 0; i < n; i++) { |
| 733 | const sx_mount_t *m = &mnt[i]; |
| 734 | double pct = 0.0, ipct = 0.0; |
| 735 | if (m->used_bytes + m->avail_bytes > 0) |
| 736 | pct = (double)m->used_bytes * 100.0 / (double)(m->used_bytes + m->avail_bytes); |
| 737 | if (m->has_inodes && m->inodes_total > 0) |
| 738 | ipct = (double)m->inodes_used * 100.0 / (double)m->inodes_total; |
| 739 | |
| 740 | if (i) fputs(",", stdout); |
| 741 | fputs("{\"device\":", stdout); |
| 742 | json_str(m->device); |
| 743 | fputs(",\"fstype\":", stdout); |
| 744 | json_str(m->fstype); |
| 745 | fputs(",\"mount\":", stdout); |
| 746 | json_str(m->mount); |
| 747 | printf(",\"total_bytes\":%llu,\"used_bytes\":%llu,\"free_bytes\":%llu," |
| 748 | "\"avail_bytes\":%llu,\"pct\":%.1f", |
| 749 | m->total_bytes, m->used_bytes, m->free_bytes, m->avail_bytes, |
| 750 | clamp_pct(pct)); |
| 751 | printf(",\"inodes_total\":%llu,\"inodes_used\":%llu," |
| 752 | "\"inodes_pct\":%.1f,\"has_inodes\":%s}", |
| 753 | m->inodes_total, m->inodes_used, clamp_pct(ipct), |
| 754 | m->has_inodes ? "true" : "false"); |
| 755 | } |
| 756 | fputs("]", stdout); |
| 757 | } |
| 758 | |
| 759 | static int mode_json(const char *qs) |
| 760 | { |
| 761 | char action[64]; |
| 762 | char rootkind[32]; |
| 763 | char utc[40]; |
| 764 | |
| 765 | action[0] = rootkind[0] = '\0'; |
| 766 | get_query_val(qs, "action", action, sizeof(action)); |
| 767 | get_query_val(qs, "root", rootkind, sizeof(rootkind)); |
| 768 | |
| 769 | if (action[0] && strcmp(action, "mounts") != 0 && |
| 770 | strcmp(action, "dirs") != 0 && strcmp(action, "info") != 0) { |
| 771 | json_header(); |
| 772 | printf("{\"ok\":false,\"error\":\"unknown_action\"," |
| 773 | "\"supported\":[\"mounts\",\"dirs\",\"info\"],\"requested\":"); |
| 774 | json_str(action); |
| 775 | fputs("}\n", stdout); |
| 776 | return 0; |
| 777 | } |
| 778 | if (!action[0]) copy_str(action, sizeof(action), "mounts"); |
| 779 | |
| 780 | utc_now(utc, sizeof(utc)); |
| 781 | |
| 782 | if (strcmp(action, "info") == 0) { |
| 783 | json_header(); |
| 784 | fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," |
| 785 | "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); |
| 786 | json_str(platform_name()); |
| 787 | fputs(",\"pid\":", stdout); |
| 788 | printf("%ld", node_pid()); |
| 789 | fputs(",\"utc\":", stdout); |
| 790 | json_str(utc); |
| 791 | fputs(",\"node_auth\":", stdout); |
| 792 | { |
| 793 | const char *np = getenv("BOT_PASSWORD"); |
| 794 | fputs((np && *np) ? "true" : "false", stdout); |
| 795 | } |
| 796 | fputs(",\"supported\":[\"mounts\",\"dirs\",\"info\"],\"zero_network\":true," |
| 797 | "\"allowed_roots\":[\"workspace\",\"home\"]," |
| 798 | "\"max_depth\":", stdout); |
| 799 | printf("%d", MAX_DEPTH); |
| 800 | fputs(",\"max_scan_entries\":", stdout); |
| 801 | printf("%d", MAX_SCAN_ENTRIES); |
| 802 | fputs("}\n", stdout); |
| 803 | return 0; |
| 804 | } |
| 805 | |
| 806 | if (strcmp(action, "dirs") == 0) { |
| 807 | char root[MAX_PATH]; |
| 808 | const char *label = ""; |
| 809 | dir_sz_t *dirs; |
| 810 | int count = 0, truncated = 0, kind = 0; |
| 811 | long long t0, t1; |
| 812 | unsigned long long total_bytes = 0, used_bytes = 0, free_bytes = 0; |
| 813 | double root_pct = 0.0; |
| 814 | int i; |
| 815 | |
| 816 | if (!rootkind[0]) { |
| 817 | json_header(); |
| 818 | fputs("{\"ok\":false,\"error\":\"missing_root\"," |
| 819 | "\"allowed_roots\":[\"workspace\",\"home\"]}\n", stdout); |
| 820 | return 0; |
| 821 | } |
| 822 | /* Strict allowlist: an arbitrary path can never be walked. */ |
| 823 | { |
| 824 | int rv = resolve_root(rootkind, root, sizeof(root), &label); |
| 825 | if (rv == 0) { |
| 826 | json_header(); |
| 827 | fputs("{\"ok\":false,\"error\":\"root_not_allowed\"," |
| 828 | "\"allowed_roots\":[\"workspace\",\"home\"],\"requested\":", stdout); |
| 829 | json_str(rootkind); |
| 830 | fputs("}\n", stdout); |
| 831 | return 0; |
| 832 | } |
| 833 | if (rv < 0) { |
| 834 | json_header(); |
| 835 | fputs("{\"ok\":false,\"error\":\"root_unavailable\"," |
| 836 | "\"allowed_roots\":[\"workspace\",\"home\"],\"requested\":", stdout); |
| 837 | json_str(rootkind); |
| 838 | fputs(",\"message\":\"this root does not exist on this node\"}\n", stdout); |
| 839 | return 0; |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | #if defined(_WIN32) |
| 844 | { |
| 845 | /* GetDiskFreeSpaceExA needs a drive root, not a deep path. */ |
| 846 | char drive[8]; |
| 847 | ULARGE_INTEGER avail, total, totalfree; |
| 848 | if (root[0] && root[1] == ':') { |
| 849 | drive[0] = root[0]; drive[1] = ':'; drive[2] = '\\'; drive[3] = '\0'; |
| 850 | if (GetDiskFreeSpaceExA(drive, &avail, &total, &totalfree)) { |
| 851 | total_bytes = (unsigned long long)total.QuadPart; |
| 852 | free_bytes = (unsigned long long)totalfree.QuadPart; |
| 853 | used_bytes = total_bytes >= free_bytes ? total_bytes - free_bytes : 0; |
| 854 | if (used_bytes + (unsigned long long)avail.QuadPart > 0) |
| 855 | root_pct = (double)used_bytes * 100.0 / |
| 856 | (double)(used_bytes + (unsigned long long)avail.QuadPart); |
| 857 | } |
| 858 | } |
| 859 | } |
| 860 | #else |
| 861 | { |
| 862 | struct statvfs vfs; |
| 863 | if (statvfs(root, &vfs) == 0) { |
| 864 | total_bytes = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize; |
| 865 | free_bytes = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize; |
| 866 | used_bytes = total_bytes >= free_bytes ? total_bytes - free_bytes : 0; |
| 867 | if (used_bytes + (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize > 0) |
| 868 | root_pct = (double)used_bytes * 100.0 / |
| 869 | (double)(used_bytes + (unsigned long long)vfs.f_bavail * (unsigned long long)vfs.f_frsize); |
| 870 | } |
| 871 | } |
| 872 | #endif |
| 873 | |
| 874 | dirs = (dir_sz_t *)calloc((size_t)MAX_DIRS, sizeof(dir_sz_t)); |
| 875 | if (!dirs) { |
| 876 | json_header(); |
| 877 | fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); |
| 878 | return 0; |
| 879 | } |
| 880 | |
| 881 | t0 = now_ms(); |
| 882 | scan_root(root, dirs, MAX_DIRS, &count, &truncated, &kind); |
| 883 | t1 = now_ms(); |
| 884 | |
| 885 | json_header(); |
| 886 | fputs("{\"ok\":true,\"action\":\"dirs\",\"plugin\":\"" PLUGIN_ID "\"," |
| 887 | "\"platform\":", stdout); |
| 888 | json_str(platform_name()); |
| 889 | fputs(",\"root_kind\":", stdout); |
| 890 | json_str(rootkind); |
| 891 | fputs(",\"root\":", stdout); |
| 892 | json_str(root); |
| 893 | fputs(",\"root_label\":", stdout); |
| 894 | json_str(label); |
| 895 | printf(",\"root_total_bytes\":%llu,\"root_used_bytes\":%llu," |
| 896 | "\"root_free_bytes\":%llu,\"root_pct\":%.1f", |
| 897 | total_bytes, used_bytes, free_bytes, clamp_pct(root_pct)); |
| 898 | printf(",\"count\":%d,\"truncated\":%s,\"max_depth\":%d," |
| 899 | "\"max_scan_entries\":%d,\"scan_ms\":%lld,\"utc\":", |
| 900 | count, truncated ? "true" : "false", MAX_DEPTH, MAX_SCAN_ENTRIES, t1 - t0); |
| 901 | json_str(utc); |
| 902 | fputs(",\"entries\":[", stdout); |
| 903 | for (i = 0; i < count; i++) { |
| 904 | double pct = total_bytes > 0 |
| 905 | ? (double)dirs[i].bytes * 100.0 / (double)total_bytes : 0.0; |
| 906 | if (i) fputs(",", stdout); |
| 907 | fputs("{\"name\":", stdout); |
| 908 | json_str(dirs[i].name); |
| 909 | fputs(",\"path\":", stdout); |
| 910 | json_str(dirs[i].path); |
| 911 | printf(",\"bytes\":%llu,\"pct\":%.1f,\"is_dir\":%s}", |
| 912 | dirs[i].bytes, clamp_pct(pct), dirs[i].is_dir ? "true" : "false"); |
| 913 | } |
| 914 | fputs("]}\n", stdout); |
| 915 | free(dirs); |
| 916 | return 0; |
| 917 | } |
| 918 | |
| 919 | /* action == mounts */ |
| 920 | { |
| 921 | sx_mount_t probe[MAX_MOUNTS]; |
| 922 | int n; |
| 923 | memset(probe, 0, sizeof(probe)); |
| 924 | n = collect_mounts(probe, MAX_MOUNTS); |
| 925 | json_header(); |
| 926 | fputs("{\"ok\":true,\"action\":\"mounts\",\"plugin\":\"" PLUGIN_ID "\"," |
| 927 | "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); |
| 928 | json_str(platform_name()); |
| 929 | printf(",\"pid\":%ld,\"count\":%d,\"utc\":", node_pid(), n); |
| 930 | json_str(utc); |
| 931 | fputs(",\"zero_network\":true,\"mounts\":", stdout); |
| 932 | emit_mounts(); |
| 933 | fputs("}\n", stdout); |
| 934 | } |
| 935 | return 0; |
| 936 | } |
| 937 | |
| 938 | /* ------------------------------------------------------------------ */ |
| 939 | /* HTML UI */ |
| 940 | /* ------------------------------------------------------------------ */ |
| 941 | |
| 942 | static int mode_html(int embed) |
| 943 | { |
| 944 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 945 | "Cache-Control: no-store\r\n" |
| 946 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 947 | |
| 948 | fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" |
| 949 | "<meta name='viewport' content='width=device-width,initial-scale=1'>" |
| 950 | "<title>disks</title>", stdout); |
| 951 | |
| 952 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout); |
| 953 | fputs( |
| 954 | "*{box-sizing:border-box}" |
| 955 | "body{margin:0;padding:16px;background:var(--bg);color:var(--text);" |
| 956 | "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" |
| 957 | "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" |
| 958 | ".wrap{max-width:1120px;margin:0 auto;min-width:0}" |
| 959 | ".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" |
| 960 | ".title{font-size:20px;font-weight:700;margin:0}" |
| 961 | ".sub{color:var(--muted);font-size:12px;font-family:var(--mono);" |
| 962 | "overflow-wrap:anywhere}" |
| 963 | ".spacer{flex:1}" |
| 964 | ".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" |
| 965 | "background:var(--surface2);color:var(--muted);border:1px solid var(--line);" |
| 966 | "white-space:nowrap}" |
| 967 | ".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" |
| 968 | ".pill.warn{color:var(--warn);border-color:rgba(255,214,10,.4)}" |
| 969 | ".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" |
| 970 | "padding:16px;margin-bottom:14px;min-width:0}" |
| 971 | ".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;" |
| 972 | "text-transform:uppercase;color:var(--muted);font-weight:600}" |
| 973 | ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:10px}" |
| 974 | ".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" |
| 975 | "padding:10px 12px;min-width:0}" |
| 976 | ".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" |
| 977 | ".kpi .v{font-size:19px;font-weight:700;font-family:var(--mono);margin-top:2px;" |
| 978 | "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" |
| 979 | "button{background:var(--accent);color:#fff;border:0;border-radius:999px;" |
| 980 | "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" |
| 981 | "button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" |
| 982 | "button:active{transform:scale(.98)}" |
| 983 | ".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" |
| 984 | ".seg{display:inline-flex;gap:4px;background:var(--surface2);" |
| 985 | "border:1px solid var(--line);border-radius:999px;padding:3px}" |
| 986 | ".seg button{background:transparent;color:var(--muted);border:0;padding:4px 11px;font-size:12px}" |
| 987 | ".seg button.on{background:var(--accent);color:#fff}" |
| 988 | ".mnt{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" |
| 989 | "padding:10px 12px;margin-bottom:8px;min-width:0}" |
| 990 | ".mnt .h{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}" |
| 991 | ".mnt .mp{font-family:var(--mono);font-weight:700;font-size:13px;" |
| 992 | "overflow-wrap:anywhere;min-width:0}" |
| 993 | ".mnt .meta{color:var(--muted);font-size:11px;font-family:var(--mono);" |
| 994 | "overflow-wrap:anywhere;min-width:0}" |
| 995 | ".bar{height:8px;border-radius:4px;background:rgba(255,255,255,.10);" |
| 996 | "overflow:hidden;margin:7px 0 5px}" |
| 997 | ".bar .fill{height:100%;border-radius:4px;background:var(--ok);transition:width .35s}" |
| 998 | ".bar .fill.warn{background:var(--warn)}" |
| 999 | ".bar .fill.danger{background:var(--danger)}" |
| 1000 | ".nums{display:flex;justify-content:space-between;gap:8px;font-size:11px;" |
| 1001 | "font-family:var(--mono);color:var(--muted);flex-wrap:wrap}" |
| 1002 | ".tblwrap{overflow-x:auto;-webkit-overflow-scrolling:touch}" |
| 1003 | "table{width:100%;border-collapse:collapse;font-size:13px}" |
| 1004 | "th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}" |
| 1005 | "th{font-size:11px;text-transform:uppercase;letter-spacing:.05em;" |
| 1006 | "color:var(--muted);font-weight:600;white-space:nowrap}" |
| 1007 | "td.num,th.num{text-align:right;font-family:var(--mono);white-space:nowrap}" |
| 1008 | "td.nm{overflow-wrap:anywhere}" |
| 1009 | ".muted{color:var(--muted)}" |
| 1010 | ".hide{display:none}" |
| 1011 | "@media(max-width:560px){body{padding:12px}.card{padding:12px}" |
| 1012 | "th.hide-sm,td.hide-sm{display:none}.kpi .v{font-size:17px}}", |
| 1013 | stdout); |
| 1014 | |
| 1015 | fputs("</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); |
| 1016 | |
| 1017 | fputs("<div class='top'>" |
| 1018 | "<h1 class='title'>disks</h1>" |
| 1019 | "<span class='pill' id='pPlatform'>—</span>" |
| 1020 | "<span class='pill' id='pState'>loading</span>" |
| 1021 | "<span class='spacer'></span>" |
| 1022 | "<div class='seg' id='segRate'>" |
| 1023 | "<button type='button' data-ms='0' class='on'>Paused</button>" |
| 1024 | "<button type='button' data-ms='5000'>5s</button>" |
| 1025 | "<button type='button' data-ms='15000'>15s</button>" |
| 1026 | "</div>" |
| 1027 | "<button type='button' class='ghost' id='btnRefresh'>Refresh</button>" |
| 1028 | "</div>", stdout); |
| 1029 | |
| 1030 | /* summary */ |
| 1031 | fputs("<div class='card'><h2>Storage summary</h2>" |
| 1032 | "<div class='grid'>" |
| 1033 | "<div class='kpi'><div class='k'>filesystems</div><div class='v' id='kCount'>—</div></div>" |
| 1034 | "<div class='kpi'><div class='k'>total capacity</div><div class='v' id='kTotal'>—</div></div>" |
| 1035 | "<div class='kpi'><div class='k'>used</div><div class='v' id='kUsed'>—</div></div>" |
| 1036 | "<div class='kpi'><div class='k'>free</div><div class='v' id='kFree'>—</div></div>" |
| 1037 | "<div class='kpi'><div class='k'>most full</div><div class='v' id='kFull'>—</div></div>" |
| 1038 | "</div>" |
| 1039 | "<div class='sub' id='nodeLine' style='margin-top:10px'></div></div>", stdout); |
| 1040 | |
| 1041 | /* mounts */ |
| 1042 | fputs("<div class='card'><h2>Mounted filesystems</h2>" |
| 1043 | "<div id='mounts'></div>" |
| 1044 | "<div id='mountEmpty' class='muted hide'>No local filesystems reported.</div></div>", stdout); |
| 1045 | |
| 1046 | /* dirs */ |
| 1047 | fputs("<div class='card'><h2>Folder breakdown</h2>" |
| 1048 | "<div class='row' style='margin-bottom:12px'>" |
| 1049 | "<div class='seg' id='segRoot'>" |
| 1050 | "<button type='button' data-root='workspace' class='on'>/workspace</button>" |
| 1051 | "<button type='button' data-root='home'>HOME</button>" |
| 1052 | "</div>" |
| 1053 | "<span class='sub' id='dirNote'></span></div>" |
| 1054 | "<div class='tblwrap'><table><thead><tr>" |
| 1055 | "<th>Name</th><th class='num'>Size</th><th class='num'>Share</th>" |
| 1056 | "<th class='num hide-sm'>Type</th>" |
| 1057 | "</tr></thead><tbody id='rows'></tbody></table></div>" |
| 1058 | "<div id='dirEmpty' class='muted hide'>Nothing to show for this root.</div></div>", stdout); |
| 1059 | |
| 1060 | fputs("<div class='card'><h2>About this plugin</h2>" |
| 1061 | "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " |
| 1062 | "<code>/proc/mounts</code> and <code>statvfs</code> on Linux, " |
| 1063 | "<code>getmntinfo</code> on macOS and <code>GetLogicalDriveStringsA</code> " |
| 1064 | "on Windows. Makes zero outbound network requests.</p>" |
| 1065 | "<p class='muted' style='margin:0'>Folder sizes are a bounded walk of one " |
| 1066 | "of two allowlisted roots; symlinks are never followed, depth is capped and " |
| 1067 | "the walk stops after a fixed number of entries.</p></div>", stdout); |
| 1068 | |
| 1069 | if (!embed) { |
| 1070 | fputs("<div class='sub' style='margin-bottom:14px'>" |
| 1071 | "Opened directly from the node API.</div>", stdout); |
| 1072 | } |
| 1073 | |
| 1074 | fputs("<script>\n(function(){\n", stdout); |
| 1075 | |
| 1076 | fputs( |
| 1077 | " var q = new URLSearchParams(location.search);\n" |
| 1078 | " var HUB = q.get('plugin') || '';\n" |
| 1079 | " var node = q.get('node') || '';\n" |
| 1080 | " var sid = q.get('id') || '';\n" |
| 1081 | " var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" |
| 1082 | " localStorage.getItem('bot_active_pwd') || '';\n" |
| 1083 | " var RATE = 0, TIMER = null, BUSY = false, ROOT = 'workspace';\n" |
| 1084 | "\n" |
| 1085 | " /* Two routes, and getting this wrong is the classic plugin bug:\n" |
| 1086 | " page served through the hub -> call the hub proxy back\n" |
| 1087 | " page opened directly on node -> the plugin IS the route */\n" |
| 1088 | " function base(action){\n" |
| 1089 | " if (HUB) return '/plugins?plugin=' + encodeURIComponent(HUB) + '&action=' + encodeURIComponent(action);\n" |
| 1090 | " return '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n" |
| 1091 | " }\n" |
| 1092 | " function withCtx(u){\n" |
| 1093 | " if (node) u += '&node=' + encodeURIComponent(node);\n" |
| 1094 | " if (sid) u += '&id=' + encodeURIComponent(sid);\n" |
| 1095 | " if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" |
| 1096 | " return u;\n" |
| 1097 | " }\n" |
| 1098 | " function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" |
| 1099 | " function $(id){ return document.getElementById(id); }\n" |
| 1100 | " function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null) ? '' : v; }\n" |
| 1101 | " function bytes(n){\n" |
| 1102 | " if (n === null || n === undefined) return '\\u2014';\n" |
| 1103 | " var u = ['B','KB','MB','GB','TB','PB'], i = 0, v = n;\n" |
| 1104 | " while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }\n" |
| 1105 | " return (i === 0 ? v.toFixed(0) : v.toFixed(v >= 100 ? 0 : 1)) + ' ' + u[i];\n" |
| 1106 | " }\n" |
| 1107 | " function cls(p){ return p >= 90 ? 'danger' : (p >= 75 ? 'warn' : ''); }\n" |
| 1108 | " function el(tag, c, t){\n" |
| 1109 | " var e = document.createElement(tag);\n" |
| 1110 | " if (c) e.className = c;\n" |
| 1111 | " if (t !== undefined) e.textContent = t;\n" |
| 1112 | " return e;\n" |
| 1113 | " }\n" |
| 1114 | "\n" |
| 1115 | " function renderMounts(m){\n" |
| 1116 | " var box = $('mounts');\n" |
| 1117 | " box.textContent = '';\n" |
| 1118 | " var total = 0, used = 0, free = 0, worst = null;\n" |
| 1119 | " (m.mounts || []).forEach(function(x){\n" |
| 1120 | " total += x.total_bytes; used += x.used_bytes; free += x.free_bytes;\n" |
| 1121 | " if (!worst || x.pct > worst.pct) worst = x;\n" |
| 1122 | " var card = el('div','mnt');\n" |
| 1123 | " var h = el('div','h');\n" |
| 1124 | " h.appendChild(el('span','mp', x.mount));\n" |
| 1125 | " h.appendChild(el('span','meta', x.device + ' \\u00b7 ' + x.fstype));\n" |
| 1126 | " h.appendChild(el('span','meta', x.pct.toFixed(0) + '%'));\n" |
| 1127 | " card.appendChild(h);\n" |
| 1128 | " var bar = el('div','bar');\n" |
| 1129 | " var fill = el('div','fill ' + cls(x.pct));\n" |
| 1130 | " fill.style.width = Math.max(0, Math.min(100, x.pct)) + '%';\n" |
| 1131 | " bar.appendChild(fill);\n" |
| 1132 | " card.appendChild(bar);\n" |
| 1133 | " var nums = el('div','nums');\n" |
| 1134 | " nums.appendChild(el('span', null, bytes(x.used_bytes) + ' used'));\n" |
| 1135 | " nums.appendChild(el('span', null, bytes(x.avail_bytes) + ' free'));\n" |
| 1136 | " nums.appendChild(el('span', null, bytes(x.total_bytes) + ' total'));\n" |
| 1137 | " nums.appendChild(el('span', null,\n" |
| 1138 | " x.has_inodes ? ('inodes ' + x.inodes_pct.toFixed(0) + '%') : 'inodes n/a'));\n" |
| 1139 | " card.appendChild(nums);\n" |
| 1140 | " box.appendChild(card);\n" |
| 1141 | " });\n" |
| 1142 | " if ((m.mounts || []).length) $('mountEmpty').classList.add('hide');\n" |
| 1143 | " else $('mountEmpty').classList.remove('hide');\n" |
| 1144 | " txt('kCount', m.count);\n" |
| 1145 | " txt('kTotal', bytes(total));\n" |
| 1146 | " txt('kUsed', bytes(used));\n" |
| 1147 | " txt('kFree', bytes(free));\n" |
| 1148 | " txt('kFull', worst ? (worst.mount + ' ' + worst.pct.toFixed(0) + '%') : '\\u2014');\n" |
| 1149 | " }\n" |
| 1150 | "\n" |
| 1151 | " function renderDirs(d, ok){\n" |
| 1152 | " var body = $('rows');\n" |
| 1153 | " body.textContent = '';\n" |
| 1154 | " if (!ok){\n" |
| 1155 | " $('dirEmpty').classList.remove('hide');\n" |
| 1156 | " txt('dirNote', d && d.error ? ('unavailable: ' + d.error) : 'unavailable');\n" |
| 1157 | " return;\n" |
| 1158 | " }\n" |
| 1159 | " var entries = d.entries || [];\n" |
| 1160 | " entries.forEach(function(e){\n" |
| 1161 | " var tr = el('tr');\n" |
| 1162 | " tr.appendChild(el('td','nm', e.name));\n" |
| 1163 | " tr.appendChild(el('td','num', bytes(e.bytes)));\n" |
| 1164 | " tr.appendChild(el('td','num', e.pct.toFixed(1) + '%'));\n" |
| 1165 | " tr.appendChild(el('td','num hide-sm', e.is_dir ? 'dir' : 'file'));\n" |
| 1166 | " body.appendChild(tr);\n" |
| 1167 | " });\n" |
| 1168 | " if (entries.length) $('dirEmpty').classList.add('hide');\n" |
| 1169 | " else $('dirEmpty').classList.remove('hide');\n" |
| 1170 | " txt('dirNote', d.root + ' \\u00b7 ' + bytes(d.root_used_bytes) + ' used of ' +\n" |
| 1171 | " bytes(d.root_total_bytes) + ' \\u00b7 ' + entries.length + ' entries \\u00b7 ' +\n" |
| 1172 | " d.scan_ms + ' ms' + (d.truncated ? ' \\u00b7 truncated' : ''));\n" |
| 1173 | " }\n" |
| 1174 | "\n" |
| 1175 | " function loadDirs(fallbackDone){\n" |
| 1176 | " var u = withCtx(base('dirs')) + '&root=' + encodeURIComponent(ROOT);\n" |
| 1177 | " return fetch(u, { headers: hdr(), cache: 'no-store' })\n" |
| 1178 | " .then(function(r){ return r.json(); })\n" |
| 1179 | " .then(function(d){\n" |
| 1180 | " /* /workspace only exists on BotCloud containers. On a plain node the\n" |
| 1181 | " first request answers root_unavailable, so fall through to HOME\n" |
| 1182 | " once instead of showing an empty panel. */\n" |
| 1183 | " if (d && d.error === 'root_unavailable' && ROOT === 'workspace' && !fallbackDone){\n" |
| 1184 | " ROOT = 'home';\n" |
| 1185 | " Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'),\n" |
| 1186 | " function(x){ x.classList.toggle('on', x.getAttribute('data-root') === 'home'); });\n" |
| 1187 | " return loadDirs(true);\n" |
| 1188 | " }\n" |
| 1189 | " renderDirs(d, d && d.ok === true);\n" |
| 1190 | " })\n" |
| 1191 | " .catch(function(e){ renderDirs({error: String(e)}, false); });\n" |
| 1192 | " }\n" |
| 1193 | "\n" |
| 1194 | " function poll(){\n" |
| 1195 | " if (BUSY) return;\n" |
| 1196 | " BUSY = true;\n" |
| 1197 | " fetch(withCtx(base('mounts')), { headers: hdr(), cache: 'no-store' })\n" |
| 1198 | " .then(function(r){ return r.json(); })\n" |
| 1199 | " .then(function(d){\n" |
| 1200 | " if (!d || d.ok === false){ txt('pState', 'error'); return; }\n" |
| 1201 | " txt('pPlatform', d.platform);\n" |
| 1202 | " txt('nodeLine', 'plugin ' + d.plugin + ' v' + d.version +\n" |
| 1203 | " ' \\u00b7 pid ' + d.pid + ' \\u00b7 ' + d.utc +\n" |
| 1204 | " ' \\u00b7 zero outbound network');\n" |
| 1205 | " renderMounts(d);\n" |
| 1206 | " })\n" |
| 1207 | " .catch(function(){ txt('pState', 'error'); })\n" |
| 1208 | " .then(function(){ BUSY = false; });\n" |
| 1209 | " loadDirs();\n" |
| 1210 | " }\n" |
| 1211 | "\n" |
| 1212 | " function schedule(){\n" |
| 1213 | " if (TIMER) { clearInterval(TIMER); TIMER = null; }\n" |
| 1214 | " var st = $('pState');\n" |
| 1215 | " if (RATE > 0){\n" |
| 1216 | " TIMER = setInterval(poll, RATE);\n" |
| 1217 | " st.textContent = 'live ' + (RATE / 1000) + 's';\n" |
| 1218 | " st.className = 'pill live';\n" |
| 1219 | " } else {\n" |
| 1220 | " st.textContent = 'paused';\n" |
| 1221 | " st.className = 'pill';\n" |
| 1222 | " }\n" |
| 1223 | " }\n" |
| 1224 | "\n" |
| 1225 | " Array.prototype.forEach.call(document.querySelectorAll('#segRate button'), function(b){\n" |
| 1226 | " b.addEventListener('click', function(){\n" |
| 1227 | " Array.prototype.forEach.call(document.querySelectorAll('#segRate button'),\n" |
| 1228 | " function(x){ x.classList.remove('on'); });\n" |
| 1229 | " b.classList.add('on');\n" |
| 1230 | " RATE = parseInt(b.getAttribute('data-ms'), 10) || 0;\n" |
| 1231 | " schedule();\n" |
| 1232 | " if (RATE > 0) poll();\n" |
| 1233 | " });\n" |
| 1234 | " });\n" |
| 1235 | "\n" |
| 1236 | " Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'), function(b){\n" |
| 1237 | " b.addEventListener('click', function(){\n" |
| 1238 | " Array.prototype.forEach.call(document.querySelectorAll('#segRoot button'),\n" |
| 1239 | " function(x){ x.classList.remove('on'); });\n" |
| 1240 | " b.classList.add('on');\n" |
| 1241 | " ROOT = b.getAttribute('data-root') || 'workspace';\n" |
| 1242 | " loadDirs();\n" |
| 1243 | " });\n" |
| 1244 | " });\n" |
| 1245 | "\n" |
| 1246 | " $('btnRefresh').addEventListener('click', poll);\n" |
| 1247 | "\n" |
| 1248 | " /* follow the hub's theme when it sets one */\n" |
| 1249 | " try {\n" |
| 1250 | " var t = localStorage.getItem('bot_theme');\n" |
| 1251 | " if (t === 'light' || t === 'dark') document.documentElement.setAttribute('data-theme', t);\n" |
| 1252 | " } catch (e) {}\n" |
| 1253 | "\n" |
| 1254 | " poll();\n" |
| 1255 | " schedule();\n" |
| 1256 | "})();\n</script></body></html>\n", stdout); |
| 1257 | |
| 1258 | return 0; |
| 1259 | } |
| 1260 | |
| 1261 | /* ------------------------------------------------------------------ */ |
| 1262 | /* main */ |
| 1263 | /* ------------------------------------------------------------------ */ |
| 1264 | |
| 1265 | int main(int argc, char **argv) |
| 1266 | { |
| 1267 | const char *qs; |
| 1268 | int embed; |
| 1269 | |
| 1270 | if (argc > 1) { |
| 1271 | if (strcmp(argv[1], "--meta") == 0) return mode_meta(); |
| 1272 | if (strcmp(argv[1], "--version") == 0) { |
| 1273 | puts(PLUGIN_VER); |
| 1274 | return 0; |
| 1275 | } |
| 1276 | if (strcmp(argv[1], "--help") == 0) { |
| 1277 | puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); |
| 1278 | puts(""); |
| 1279 | puts("Runs as a CGI-style program under scorpiox-server."); |
| 1280 | puts(" --meta print discovery metadata JSON and exit"); |
| 1281 | puts(" --version print the plugin version and exit"); |
| 1282 | puts(""); |
| 1283 | puts("Query string actions:"); |
| 1284 | puts(" (none) or action=mounts mounted filesystems with usage"); |
| 1285 | puts(" action=dirs&root=workspace|home bounded 1-level folder sizes"); |
| 1286 | puts(" action=info plugin/platform capabilities"); |
| 1287 | puts(" format=json same as an action, JSON output"); |
| 1288 | puts(" (any other) HTML dashboard"); |
| 1289 | return 0; |
| 1290 | } |
| 1291 | } |
| 1292 | |
| 1293 | if (getenv("SX_PLUGIN_META")) return mode_meta(); |
| 1294 | |
| 1295 | require_node_auth(); |
| 1296 | |
| 1297 | qs = getenv("QUERY_STRING"); |
| 1298 | if (!qs) qs = ""; |
| 1299 | |
| 1300 | if (strstr(qs, "action=") || strstr(qs, "format=json")) |
| 1301 | return mode_json(qs); |
| 1302 | |
| 1303 | embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); |
| 1304 | return mode_html(embed); |
| 1305 | } |