/* * plugin_sysmon - SCORPIOX BOT open-source local system monitor plugin * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery * 2. ?action=metrics | ?format=json -> JSON node API (local CPU, memory, swap, * uptime, load average and top processes) * 3. GET (default) -> responsive HTML dashboard * * Local node only. Reads the local kernel interfaces (/proc on Linux, mach and * sysctl on macOS, Win32 APIs on Windows). Makes ZERO outbound network * requests, opens no sockets, runs no remote commands, reads no credentials. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(__APPLE__) /* sysctl.h pulls in BSD types (u_int) that strict c99 would hide */ # define _DARWIN_C_SOURCE 1 #elif !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 #endif #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 /* GetTickCount64 needs Vista or later; must precede windows.h */ #endif #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include # include #else # include # include # include #endif #if defined(__APPLE__) # include # include # include # include #endif #include "bot_theme_plugin.h" #define PLUGIN_SLUG "sysmon" #define PLUGIN_ID "plugin_sysmon" #define PLUGIN_VER "1.0.2" #define MAX_CORES 256 #define MAX_PROCS 4096 #define TOP_DEFAULT 25 #define SAMPLE_MS 80 /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ /* Percent-decode in place ('+' becomes space). */ static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } /* Read one parameter (decoded) out of a form/query string. */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static void json_str(const char *s) { putchar('"'); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': fputs("\\\"", stdout); break; case '\\': fputs("\\\\", stdout); break; case '\n': fputs("\\n", stdout); break; case '\r': fputs("\\r", stdout); break; case '\t': fputs("\\t", stdout); break; default: if (c < 0x20) printf("\\u%04x", (unsigned)c); else putchar((int)c); } } putchar('"'); } static void utc_now(char *buf, size_t sz) { time_t t = time(NULL); struct tm tmv; #if defined(_WIN32) gmtime_s(&tmv, &t); #else gmtime_r(&t, &tmv); #endif if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); buf[sz - 1] = '\0'; } } static long node_pid(void) { #if defined(_WIN32) return (long)GetCurrentProcessId(); #else return (long)getpid(); #endif } static void sx_sleep_ms(int ms) { #if defined(_WIN32) Sleep((DWORD)ms); #else struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (long)(ms % 1000) * 1000000L; nanosleep(&ts, NULL); #endif } static double clamp_pct(double v) { if (v < 0.0) return 0.0; if (v > 100.0) return 100.0; return v; } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ /* * The node API on :8150 is reachable from the LAN. Every request except * --meta discovery must prove it knows the node password. Accepted forms * match the rest of the node API: X-Bot-Password (what bot-web proxies * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how * a developer runs it locally from a shell. */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; char qpwd[256]; const char *qs; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Collected snapshot */ /* ------------------------------------------------------------------ */ typedef struct { int core; double pct; } core_t; typedef struct { long pid; char name[64]; double cpu; /* percent of one core */ long rss_kb; char state; } proc_t; typedef struct { int ok; char platform[16]; /* linux | macos | windows */ char host[128]; double cpu_pct; core_t cores[MAX_CORES]; int ncores; char cpu_model[128]; double mem_total_kb; double mem_used_kb; double mem_free_kb; double mem_cached_kb; double swap_total_kb; double swap_used_kb; double uptime_sec; double load1, load5, load15; int load_available; proc_t procs[MAX_PROCS]; int nprocs; } sys_t; /* ------------------------------------------------------------------ */ /* Linux sampling */ /* ------------------------------------------------------------------ */ #if !defined(_WIN32) && !defined(__APPLE__) typedef struct { unsigned long long user, nice, system, idle, iowait, irq, softirq, steal; } cpu_raw_t; /* * /proc/stat reports st_size == 0, so seeking to the end and measuring is * meaningless. Always stream with fgets until EOF. */ static int read_proc_stat(cpu_raw_t *agg, cpu_raw_t *cores, int maxcores) { FILE *fp; char line[512]; int n = 0; fp = fopen("/proc/stat", "r"); if (!fp) return -1; memset(agg, 0, sizeof(*agg)); while (fgets(line, sizeof(line), fp)) { if (strncmp(line, "cpu", 3) != 0) break; if (line[3] == ' ') { (void)sscanf(line + 4, "%llu %llu %llu %llu %llu %llu %llu %llu", &agg->user, &agg->nice, &agg->system, &agg->idle, &agg->iowait, &agg->irq, &agg->softirq, &agg->steal); continue; } if (isdigit((unsigned char)line[3])) { cpu_raw_t r; int idx = 0; memset(&r, 0, sizeof(r)); if (sscanf(line + 3, "%d %llu %llu %llu %llu %llu %llu %llu %llu", &idx, &r.user, &r.nice, &r.system, &r.idle, &r.iowait, &r.irq, &r.softirq, &r.steal) >= 5) { if (n < maxcores) cores[n] = r; n++; } } } fclose(fp); return n; } static double cpu_busy_pct(const cpu_raw_t *a, const cpu_raw_t *b) { unsigned long long ta = a->user + a->nice + a->system + a->idle + a->iowait + a->irq + a->softirq + a->steal; unsigned long long tb = b->user + b->nice + b->system + b->idle + b->iowait + b->irq + b->softirq + b->steal; unsigned long long ba = a->user + a->nice + a->system + a->irq + a->softirq + a->steal; unsigned long long bb = b->user + b->nice + b->system + b->irq + b->softirq + b->steal; unsigned long long dt, db; if (tb <= ta) return 0.0; dt = tb - ta; db = bb >= ba ? bb - ba : 0; return clamp_pct(100.0 * (double)db / (double)dt); } static void read_meminfo(sys_t *s) { FILE *fp; char line[256]; s->mem_total_kb = s->mem_free_kb = s->mem_cached_kb = 0.0; s->swap_total_kb = s->swap_used_kb = 0.0; fp = fopen("/proc/meminfo", "r"); if (!fp) return; { unsigned long long total = 0, free_kb = 0, avail = 0, cached = 0, sreclaim = 0; unsigned long long swap_total = 0, swap_free = 0; while (fgets(line, sizeof(line), fp)) { unsigned long long v = 0; if (sscanf(line, "MemTotal: %llu kB", &v) == 1) total = v; else if (sscanf(line, "MemFree: %llu kB", &v) == 1) free_kb = v; else if (sscanf(line, "MemAvailable: %llu kB", &v) == 1) avail = v; else if (sscanf(line, "Cached: %llu kB", &v) == 1) cached = v; else if (sscanf(line, "SReclaimable: %llu kB", &v) == 1) sreclaim = v; else if (sscanf(line, "SwapTotal: %llu kB", &v) == 1) swap_total = v; else if (sscanf(line, "SwapFree: %llu kB", &v) == 1) swap_free = v; } fclose(fp); s->mem_total_kb = (double)total; s->mem_free_kb = (double)(avail ? avail : free_kb); s->mem_cached_kb = (double)(cached + sreclaim); s->mem_used_kb = (double)total - s->mem_free_kb; if (s->mem_used_kb < 0.0) s->mem_used_kb = 0.0; s->swap_total_kb = (double)swap_total; s->swap_used_kb = (double)(swap_total > swap_free ? swap_total - swap_free : 0); } } static void read_uptime(sys_t *s) { FILE *fp = fopen("/proc/uptime", "r"); double up = 0.0; if (fp) { if (fscanf(fp, "%lf", &up) != 1) up = 0.0; fclose(fp); } s->uptime_sec = up; } static void read_load(sys_t *s) { FILE *fp = fopen("/proc/loadavg", "r"); if (fp) { if (fscanf(fp, "%lf %lf %lf", &s->load1, &s->load5, &s->load15) == 3) s->load_available = 1; fclose(fp); } } static void read_cpu_model(sys_t *s) { FILE *fp = fopen("/proc/cpuinfo", "r"); char line[512]; s->cpu_model[0] = '\0'; if (!fp) return; while (fgets(line, sizeof(line), fp)) { char *colon; if (!(strncmp(line, "model name", 10) == 0 || strncmp(line, "Model", 5) == 0)) continue; colon = strchr(line, ':'); if (!colon) continue; colon++; while (*colon == ' ' || *colon == '\t') colon++; { size_t i = 0; while (*colon && *colon != '\n' && i + 1 < sizeof(s->cpu_model)) s->cpu_model[i++] = *colon++; s->cpu_model[i] = '\0'; while (i > 0 && (s->cpu_model[i - 1] == ' ' || s->cpu_model[i - 1] == '\t')) s->cpu_model[--i] = '\0'; } break; } fclose(fp); } static void read_hostname(sys_t *s) { if (gethostname(s->host, sizeof(s->host)) != 0) s->host[0] = '\0'; s->host[sizeof(s->host) - 1] = '\0'; } /* One process: utime+stime ticks, rss pages, state char. */ static int read_pid_stat(const char *pid, unsigned long long *ticks, long *rss_pages, char *state) { char path[64]; char buf[4096]; FILE *fp; size_t got; char *p; int field; unsigned long long utime = 0, stime = 0; long rss = 0; snprintf(path, sizeof(path), "/proc/%s/stat", pid); fp = fopen(path, "r"); if (!fp) return 0; got = fread(buf, 1, sizeof(buf) - 1, fp); fclose(fp); buf[got] = '\0'; p = strrchr(buf, ')'); if (!p || !p[1]) return 0; p++; while (*p == ' ') p++; if (state) *state = *p; /* fields after comm: state is 3, utime 14, stime 15, rss 24 */ field = 3; while (*p) { char *end; long long v; while (*p == ' ') p++; if (!*p) break; if (field == 3) { /* skip the single-letter state token */ while (*p && *p != ' ') p++; field++; continue; } v = strtoll(p, &end, 10); if (end == p) break; if (field == 14) utime = (unsigned long long)v; else if (field == 15) stime = (unsigned long long)v; else if (field == 24) rss = (long)v; if (field >= 24) break; p = end; field++; } *ticks = utime + stime; *rss_pages = rss; return 1; } static void read_pid_name(const char *pid, char *out, size_t outsz) { char path[64]; FILE *fp; size_t n; out[0] = '\0'; snprintf(path, sizeof(path), "/proc/%s/comm", pid); fp = fopen(path, "r"); if (!fp) return; n = fread(out, 1, outsz - 1, fp); fclose(fp); out[n] = '\0'; while (n > 0 && (out[n - 1] == '\n' || out[n - 1] == '\r')) out[--n] = '\0'; } /* * Two-pass scan of /proc. The second pass is what produces a live CPU * percentage, because /proc//stat only exposes cumulative ticks. */ typedef struct { long pid; unsigned long long ticks; long rss_pages; char state; } psnap_t; static int scan_procs_linux(psnap_t *out, int max) { DIR *d; struct dirent *e; int n = 0; d = opendir("/proc"); if (!d) return 0; while ((e = readdir(d)) != NULL) { if (!isdigit((unsigned char)e->d_name[0])) continue; if (n >= max) break; if (!read_pid_stat(e->d_name, &out[n].ticks, &out[n].rss_pages, &out[n].state)) continue; out[n].pid = (long)strtol(e->d_name, NULL, 10); n++; } closedir(d); return n; } static void sample_linux(sys_t *s) { static psnap_t snap0[MAX_PROCS], snap1[MAX_PROCS]; cpu_raw_t agg0, agg1; cpu_raw_t c0[MAX_CORES], c1[MAX_CORES]; int n0, n1, p0, p1, i, j, k; long hz = sysconf(_SC_CLK_TCK); long page_kb = (long)(sysconf(_SC_PAGESIZE) / 1024); double window = (double)SAMPLE_MS / 1000.0; strcpy(s->platform, "linux"); read_hostname(s); read_cpu_model(s); memset(c0, 0, sizeof(c0)); memset(c1, 0, sizeof(c1)); n0 = read_proc_stat(&agg0, c0, MAX_CORES); p0 = scan_procs_linux(snap0, MAX_PROCS); sx_sleep_ms(SAMPLE_MS); n1 = read_proc_stat(&agg1, c1, MAX_CORES); p1 = scan_procs_linux(snap1, MAX_PROCS); if (hz <= 0) hz = 100; if (n0 > 0 && n1 > 0) { s->cpu_pct = cpu_busy_pct(&agg0, &agg1); s->ncores = n1 < MAX_CORES ? n1 : MAX_CORES; for (i = 0; i < s->ncores; i++) { s->cores[i].core = i; s->cores[i].pct = cpu_busy_pct(&c0[i], &c1[i]); } } /* Processes: RSS is instantaneous, CPU needs a delta over the window. */ s->nprocs = 0; for (j = 0; j < p1 && s->nprocs < MAX_PROCS; j++) { char name[64]; unsigned long long dt = 0; char pidbuf[24]; for (k = 0; k < p0; k++) { if (snap0[k].pid == snap1[j].pid) { dt = snap1[j].ticks > snap0[k].ticks ? snap1[j].ticks - snap0[k].ticks : 0; break; } } snprintf(pidbuf, sizeof(pidbuf), "%ld", snap1[j].pid); read_pid_name(pidbuf, name, sizeof(name)); s->procs[s->nprocs].pid = snap1[j].pid; s->procs[s->nprocs].cpu = clamp_pct(100.0 * (double)dt / ((double)hz * window)); s->procs[s->nprocs].rss_kb = snap1[j].rss_pages * page_kb; s->procs[s->nprocs].state = snap1[j].state; memcpy(s->procs[s->nprocs].name, name, sizeof(name)); s->nprocs++; } read_meminfo(s); read_uptime(s); read_load(s); s->ok = (s->ncores > 0); } #endif /* linux */ /* ------------------------------------------------------------------ */ /* macOS sampling */ /* ------------------------------------------------------------------ */ #if defined(__APPLE__) static void sample_macos(sys_t *s) { size_t sz; char bbuf[256]; unsigned int ncpu = 0; uint64_t total_mem = 0; struct timeval boot; vm_statistics64_data_t vm; mach_msg_type_number_t vmcount = HOST_VM_INFO64_COUNT; integer_t *cpu0 = NULL, *cpu1 = NULL; natural_t ncpu0 = 0, ncpu1 = 0; unsigned long long page_kb; strcpy(s->platform, "macos"); sz = sizeof(bbuf); if (sysctlbyname("kern.hostname", bbuf, &sz, NULL, 0) == 0) snprintf(s->host, sizeof(s->host), "%s", bbuf); else s->host[0] = '\0'; s->cpu_model[0] = '\0'; sz = sizeof(bbuf); if (sysctlbyname("machdep.cpu.brand_string", bbuf, &sz, NULL, 0) == 0) snprintf(s->cpu_model, sizeof(s->cpu_model), "%s", bbuf); sz = sizeof(ncpu); if (sysctlbyname("hw.logicalcpu", &ncpu, &sz, NULL, 0) != 0 || sysctlbyname("hw.ncpu", &ncpu, &sz, NULL, 0) != 0) ncpu = 1; /* aggregate + per-core tick capture, twice */ { natural_t c0 = 0, c1 = 0; if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &ncpu0, &cpu0, &c0) != KERN_SUCCESS) cpu0 = NULL; sx_sleep_ms(SAMPLE_MS); if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &ncpu1, &cpu1, &c1) != KERN_SUCCESS) cpu1 = NULL; } if (cpu0 && cpu1) { natural_t i; natural_t n = ncpu1 < ncpu0 ? ncpu1 : ncpu0; unsigned long long t_idle = 0, t_total = 0; s->ncores = 0; for (i = 0; i < n && s->ncores < MAX_CORES; i++) { unsigned long long a_idle = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_IDLE]; unsigned long long a_usr = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_USER]; unsigned long long a_sys = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; unsigned long long a_nice = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_NICE]; unsigned long long b_idle = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_IDLE]; unsigned long long b_usr = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_USER]; unsigned long long b_sys = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; unsigned long long b_nice = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_NICE]; unsigned long long ta = a_idle + a_usr + a_sys + a_nice; unsigned long long tb = b_idle + b_usr + b_sys + b_nice; unsigned long long di = b_idle > a_idle ? b_idle - a_idle : 0; unsigned long long dt = tb > ta ? tb - ta : 0; s->cores[s->ncores].core = (int)i; s->cores[s->ncores].pct = dt ? clamp_pct(100.0 - 100.0 * (double)di / (double)dt) : 0.0; s->ncores++; t_idle += di; t_total += dt; } s->cpu_pct = t_total ? clamp_pct(100.0 - 100.0 * (double)t_idle / (double)t_total) : 0.0; } if (cpu0) (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu0, (vm_size_t)(ncpu0 * CPU_STATE_MAX * sizeof(integer_t))); if (cpu1) (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu1, (vm_size_t)(ncpu1 * CPU_STATE_MAX * sizeof(integer_t))); sz = sizeof(total_mem); if (sysctlbyname("hw.memsize", &total_mem, &sz, NULL, 0) != 0) total_mem = 0; if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vm, &vmcount) == KERN_SUCCESS) { vm_size_t pagesz = 0; host_page_size(mach_host_self(), &pagesz); page_kb = (unsigned long long)(pagesz / 1024ULL); s->mem_total_kb = (double)(total_mem / 1024ULL); s->mem_free_kb = (double)(((unsigned long long)vm.free_count + (unsigned long long)vm.inactive_count + (unsigned long long)vm.speculative_count) * page_kb); s->mem_cached_kb = (double)((unsigned long long)vm.purgeable_count * page_kb); s->mem_used_kb = (double)(((unsigned long long)(vm.active_count + vm.wire_count) * page_kb)); } { struct xsw_usage xs; sz = sizeof(xs); if (sysctlbyname("vm.swapusage", &xs, &sz, NULL, 0) == 0) { s->swap_total_kb = (double)(xs.xsu_total / 1024ULL); s->swap_used_kb = (double)(xs.xsu_used / 1024ULL); } } sz = sizeof(boot); if (sysctlbyname("kern.boottime", &boot, &sz, NULL, 0) == 0) { time_t now = time(NULL); s->uptime_sec = (double)now - (double)boot.tv_sec; if (s->uptime_sec < 0.0) s->uptime_sec = 0.0; } { double loads[3]; if (getloadavg(loads, 3) == 3) { s->load1 = loads[0]; s->load5 = loads[1]; s->load15 = loads[2]; s->load_available = 1; } } /* Process list: the kernel exposes it most simply through ps. */ { FILE *fp = popen("ps -Ao pid=,pcpu=,rss=,comm=", "r"); if (fp) { char line[600]; s->nprocs = 0; while (fgets(line, sizeof(line), fp) && s->nprocs < MAX_PROCS) { long pid = 0; double pcpu = 0.0; long rss = 0; char comm[256]; if (sscanf(line, "%ld %lf %ld %255[^\n]", &pid, &pcpu, &rss, comm) != 4) continue; s->procs[s->nprocs].pid = pid; s->procs[s->nprocs].cpu = clamp_pct(pcpu); s->procs[s->nprocs].rss_kb = rss; s->procs[s->nprocs].state = 'R'; { const char *base = strrchr(comm, '/'); base = base ? base + 1 : comm; snprintf(s->procs[s->nprocs].name, sizeof(s->procs[s->nprocs].name), "%s", base); } s->nprocs++; } pclose(fp); } } s->ok = (s->ncores > 0 && s->mem_total_kb > 0.0); } #endif /* __APPLE__ */ /* ------------------------------------------------------------------ */ /* Windows sampling */ /* ------------------------------------------------------------------ */ #if defined(_WIN32) static unsigned long long filetime_to_100ns(const FILETIME *ft) { ULARGE_INTEGER u; u.LowPart = ft->dwLowDateTime; u.HighPart = ft->dwHighDateTime; return (unsigned long long)u.QuadPart; } static void sample_windows(sys_t *s) { MEMORYSTATUSEX ms; FILETIME idle0, kern0, user0, idle1, kern1, user1; ULARGE_INTEGER li; double total0, total1, idle_d, kern_d, user_d, dt; DWORD ncpu = 0; HANDLE snap; PROCESSENTRY32W pe; strcpy(s->platform, "windows"); s->host[0] = '\0'; s->cpu_model[0] = '\0'; { char name[256]; DWORD n = (DWORD)sizeof(name); if (GetComputerNameA(name, &n)) snprintf(s->host, sizeof(s->host), "%s", name); } { SYSTEM_INFO si; GetSystemInfo(&si); ncpu = si.dwNumberOfProcessors; } if (!GetSystemTimes(&idle0, &kern0, &user0)) { s->ok = 0; return; } sx_sleep_ms(SAMPLE_MS); if (!GetSystemTimes(&idle1, &kern1, &user1)) { s->ok = 0; return; } total0 = (double)filetime_to_100ns(&kern0) + (double)filetime_to_100ns(&user0); total1 = (double)filetime_to_100ns(&kern1) + (double)filetime_to_100ns(&user1); idle_d = (double)filetime_to_100ns(&idle1) - (double)filetime_to_100ns(&idle0); kern_d = (double)filetime_to_100ns(&kern1) - (double)filetime_to_100ns(&kern0); user_d = (double)filetime_to_100ns(&user1) - (double)filetime_to_100ns(&user0); dt = total1 - total0; if (dt > 0.0) { /* kernel time already includes idle time */ double busy = (kern_d - idle_d) + user_d; s->cpu_pct = clamp_pct(100.0 * busy / dt); } s->ncores = 0; /* Windows has no cheap per-core delta, so the UI shows an aggregate bar. */ if (ncpu == 0) ncpu = 1; s->ncores = 0; memset(&ms, 0, sizeof(ms)); ms.dwLength = sizeof(ms); if (GlobalMemoryStatusEx(&ms)) { s->mem_total_kb = (double)(ms.ullTotalPhys / 1024ULL); s->mem_free_kb = (double)(ms.ullAvailPhys / 1024ULL); s->mem_used_kb = s->mem_total_kb - s->mem_free_kb; if (s->mem_used_kb < 0.0) s->mem_used_kb = 0.0; s->mem_cached_kb = 0.0; s->swap_total_kb = (double)(ms.ullTotalPageFile / 1024ULL); s->swap_used_kb = s->swap_total_kb > (double)(ms.ullAvailPageFile / 1024ULL) ? s->swap_total_kb - (double)(ms.ullAvailPageFile / 1024ULL) : 0.0; } (void)li; s->uptime_sec = (double)GetTickCount64() / 1000.0; s->load_available = 0; /* Process list via Toolhelp32, matching the POSIX fields. */ snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snap != INVALID_HANDLE_VALUE) { memset(&pe, 0, sizeof(pe)); pe.dwSize = sizeof(pe); s->nprocs = 0; if (Process32FirstW(snap, &pe)) { do { HANDLE ph; long rss_kb = 0; if (s->nprocs >= MAX_PROCS) break; ph = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ProcessID); if (ph) { PROCESS_MEMORY_COUNTERS pmc; memset(&pmc, 0, sizeof(pmc)); if (GetProcessMemoryInfo(ph, &pmc, sizeof(pmc))) rss_kb = (long)(pmc.WorkingSetSize / 1024); CloseHandle(ph); } s->procs[s->nprocs].pid = (long)pe.th32ProcessID; s->procs[s->nprocs].cpu = 0.0; s->procs[s->nprocs].rss_kb = rss_kb; s->procs[s->nprocs].state = 'R'; { int i = 0; while (pe.szExeFile[i] && i + 1 < (int)sizeof(s->procs[s->nprocs].name)) { s->procs[s->nprocs].name[i] = (char)pe.szExeFile[i]; i++; } s->procs[s->nprocs].name[i] = '\0'; } s->nprocs++; } while (Process32NextW(snap, &pe)); } CloseHandle(snap); } s->ok = (s->mem_total_kb > 0.0); } #endif /* _WIN32 */ /* ------------------------------------------------------------------ */ /* Sampling dispatch */ /* ------------------------------------------------------------------ */ static void sample(sys_t *s) { memset(s, 0, sizeof(*s)); #if defined(_WIN32) sample_windows(s); #elif defined(__APPLE__) sample_macos(s); #else sample_linux(s); #endif } static int proc_cmp_cpu(const void *a, const void *b) { const proc_t *pa = (const proc_t *)a; const proc_t *pb = (const proc_t *)b; if (pa->cpu < pb->cpu) return 1; if (pa->cpu > pb->cpu) return -1; if (pa->rss_kb < pb->rss_kb) return 1; if (pa->rss_kb > pb->rss_kb) return -1; return 0; } static int proc_cmp_mem(const void *a, const void *b) { const proc_t *pa = (const proc_t *)a; const proc_t *pb = (const proc_t *)b; if (pa->rss_kb < pb->rss_kb) return 1; if (pa->rss_kb > pb->rss_kb) return -1; return proc_cmp_cpu(a, b); } /* ------------------------------------------------------------------ */ /* Modes */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { puts("{\"name\":\"sysmon\",\"desc\":\"CPU & memory\"}"); return 0; } static void json_header(void) { /* Deliberately no Content-Length - the server owns framing. */ fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void emit_cores(const sys_t *s) { int i; fputs("[", stdout); for (i = 0; i < s->ncores && i < MAX_CORES; i++) { if (i) fputs(",", stdout); printf("{\"core\":%d,\"pct\":%.1f}", s->cores[i].core, s->cores[i].pct); } fputs("]", stdout); } static void emit_procs(const sys_t *s, int limit) { int i; fputs("[", stdout); for (i = 0; i < limit; i++) { if (i) fputs(",", stdout); printf("{\"pid\":%ld,\"name\":", s->procs[i].pid); json_str(s->procs[i].name); printf(",\"cpu\":%.1f,\"rss_kb\":%ld,\"state\":\"%c\"}", s->procs[i].cpu, s->procs[i].rss_kb, (s->procs[i].state ? s->procs[i].state : '?')); } fputs("]", stdout); } static int mode_json(const char *qs) { char action[64]; char sortby[16]; char topn[16]; char utc[40]; sys_t s; int limit = TOP_DEFAULT; int ntop; action[0] = sortby[0] = topn[0] = '\0'; get_query_val(qs, "action", action, sizeof(action)); get_query_val(qs, "sort", sortby, sizeof(sortby)); get_query_val(qs, "top", topn, sizeof(topn)); if (topn[0]) { int v = atoi(topn); if (v > 0 && v <= MAX_PROCS) limit = v; } if (action[0] && strcmp(action, "metrics") != 0 && strcmp(action, "info") != 0) { json_header(); printf("{\"ok\":false,\"error\":\"unknown_action\"," "\"supported\":[\"metrics\",\"info\"],\"requested\":"); json_str(action); fputs("}\n", stdout); return 0; } sample(&s); utc_now(utc, sizeof(utc)); if (strcmp(action, "info") == 0) { json_header(); fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); json_str(s.platform); fputs(",\"pid\":", stdout); printf("%ld", node_pid()); fputs(",\"utc\":", stdout); json_str(utc); fputs(",\"node_auth\":", stdout); { const char *np = getenv("BOT_PASSWORD"); fputs((np && *np) ? "true" : "false", stdout); } fputs(",\"supported\":[\"metrics\",\"info\"],\"zero_network\":true," "\"samples_cpu_delta_ms\":", stdout); printf("%d", SAMPLE_MS); fputs("}\n", stdout); return 0; } /* sort the process table before taking the top slice */ ntop = s.nprocs < MAX_PROCS ? s.nprocs : MAX_PROCS; if (ntop > 0) { qsort(s.procs, (size_t)ntop, sizeof(s.procs[0]), strcmp(sortby, "mem") == 0 ? proc_cmp_mem : proc_cmp_cpu); } if (ntop > limit) ntop = limit; json_header(); if (!s.ok) { fputs("{\"ok\":false,\"error\":\"sample_failed\"," "\"message\":\"could not read local system counters on this node\"}\n", stdout); return 0; } fputs("{\"ok\":true,\"action\":\"metrics\",\"plugin\":\"" PLUGIN_ID "\"," "\"version\":\"" PLUGIN_VER "\"", stdout); fputs(",\"platform\":", stdout); json_str(s.platform); fputs(",\"host\":", stdout); json_str(s.host); fputs(",\"cpu_model\":", stdout); json_str(s.cpu_model); fputs(",\"utc\":", stdout); json_str(utc); printf(",\"cpu_pct\":%.1f,\"ncores\":%d,\"cores\":", s.cpu_pct, s.ncores); emit_cores(&s); printf(",\"mem\":{\"total_kb\":%.0f,\"used_kb\":%.0f,\"free_kb\":%.0f," "\"cached_kb\":%.0f,\"pct\":%.1f}", s.mem_total_kb, s.mem_used_kb, s.mem_free_kb, s.mem_cached_kb, s.mem_total_kb > 0.0 ? clamp_pct(100.0 * s.mem_used_kb / s.mem_total_kb) : 0.0); printf(",\"swap\":{\"total_kb\":%.0f,\"used_kb\":%.0f,\"pct\":%.1f}", s.swap_total_kb, s.swap_used_kb, s.swap_total_kb > 0.0 ? clamp_pct(100.0 * s.swap_used_kb / s.swap_total_kb) : 0.0); printf(",\"uptime_sec\":%.0f,\"load\":{\"available\":%s," "\"load1\":%.2f,\"load5\":%.2f,\"load15\":%.2f}", s.uptime_sec, s.load_available ? "true" : "false", s.load1, s.load5, s.load15); printf(",\"proc_count\":%d,\"top\":%d,\"sort\":", s.nprocs, ntop); json_str(strcmp(sortby, "mem") == 0 ? "mem" : "cpu"); fputs(",\"processes\":", stdout); emit_procs(&s, ntop); fputs("}\n", stdout); return 0; } /* ------------------------------------------------------------------ */ /* HTML */ /* ------------------------------------------------------------------ */ static int mode_html(int embed) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); fputs("\n" "" "sysmon", stdout); fputs(SX_BOT_THEME_PREPAINT "" SX_BOT_THEME_HANDOFF "
", stdout); if (!embed) { fputs("", stdout); } fputs("
" "

sysmon

" "—" "—" "" "live 2s" "
" "" "" "" "
", stdout); /* KPI row */ fputs("

System

" "
cpu
—
" "
cores
—
" "
memory
—
" "
swap
—
" "
load 1m
—
" "
uptime
—
" "
processes
—
" "
" "
", stdout); /* history sparkline */ fputs("

CPU history

" "" "" "
", stdout); /* per-core */ fputs("

Per-core utilization

" "
" "
", stdout); /* memory + swap gauges */ fputs("

Memory & swap

" "
memory—
" "
" "
swap—
" "
" "
", stdout); /* processes */ fputs("

Top processes

" "
" "" "
" "" "" "
" "
" "" "" "" "
PIDNameCPU %RSSState
" "
No matching processes.
", stdout); fputs("

About this plugin

" "

Local node only. Reads the kernel's " "own counters (/proc on Linux, mach and sysctl on macOS, " "Win32 APIs on Windows) and makes zero outbound network requests.

" "

Two CPU samples " "80 ms apart give a live percentage; nothing is cached between requests " "and no shell command comes from user input.

", stdout); /* script */ fputs("
\n", stdout); return 0; } /* ------------------------------------------------------------------ */ /* Entry point */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; const char *method; int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--meta") == 0) return mode_meta(); if (strcmp(argv[i], "--version") == 0) { printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); return 0; } if (strcmp(argv[i], "--help") == 0) { printf("usage: %s [--meta] [--version] [--help]\n" " CGI mode reads QUERY_STRING:\n" " ?format=json | ?action=metrics JSON system snapshot\n" " ?action=info plugin info\n" " (no action) HTML dashboard\n", PLUGIN_ID); return 0; } } if (getenv("SX_PLUGIN_META")) return mode_meta(); require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; method = getenv("REQUEST_METHOD"); if (!method) method = "GET"; if (strstr(qs, "action=") || strstr(qs, "format=json")) return mode_json(qs); { char embedv[16]; embedv[0] = '\0'; if (get_query_val(qs, "embed", embedv, sizeof(embedv))) return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); } return mode_html(0); }