/* * plugin_logs - SCORPIOX BOT open-source local log viewer plugin * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery * 2. ?action=sources|tail|search|units -> JSON node API * 3. GET (default) -> responsive HTML log tail & search UI * * Local node only. Reads an explicit allowlist of local log files (a bounded * walk of /var/log, $HOME/.scorpiox, /workspace, ~/Library/Logs and * %LOCALAPPDATA%\scorpiox) and the local system journal through a fixed argv * with no user-controlled shell text. Makes ZERO outbound network requests, * opens no sockets, 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. */ /* MinGW defaults to a Server 2003 target; the Win7+ APIs used below would be * hidden by that gate. This must precede every include. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if defined(__APPLE__) /* sys/types.h pulls 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 #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include #else # include # include # include # include #endif #include "bot_theme_plugin.h" #define PLUGIN_SLUG "logs" #define PLUGIN_ID "plugin_logs" #define PLUGIN_VER "1.0.0" #define MAX_SRC 256 #define MAX_UNITS 512 #define ENTRY_TEXT 1024 #define ENTRY_UNIT 96 #define ENTRY_TS 40 #define TAIL_MAX 2000 #define SEARCH_HITS_MAX 500 #define SEARCH_SCAN 8000 #define FILE_TAIL_BYTES (4L * 1024L * 1024L) #define ROOT_BUDGET 40000 /* Severity buckets: 0 info, 1 warn, 2 err */ #define SEV_INFO 0 #define SEV_WARN 1 #define SEV_ERR 2 /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ 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'; } /* Copy one query parameter into out. Returns 1 when present. */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen = strlen(key); const char *p = qs; if (outsz) out[0] = '\0'; if (!qs || !klen) return 0; while (p && *p) { const char *amp = strchr(p, '&'); const char *end = amp ? amp : p + strlen(p); const char *eq = memchr(p, '=', (size_t)(end - p)); if (eq && (size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) { size_t vlen = (size_t)(end - eq - 1); if (vlen >= outsz) vlen = outsz ? outsz - 1 : 0; if (vlen) memcpy(out, eq + 1, vlen); out[vlen] = '\0'; url_decode(out); return 1; } p = amp ? amp + 1 : NULL; } return 0; } static void json_str(const char *s) { const unsigned char *p = (const unsigned char *)s; fputc('"', stdout); if (p) { for (; *p; p++) { switch (*p) { 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 (*p < 0x20) printf("\\u%04x", *p); else fputc((int)*p, stdout); } } } fputc('"', stdout); } static void utc_now(char *buf, size_t sz) { time_t t = time(NULL); struct tm tmv; #if defined(_WIN32) struct tm *lt = localtime(&t); if (lt) tmv = *lt; #else localtime_r(&t, &tmv); #endif #if defined(_WIN32) { struct tm *gp = gmtime(&t); if (gp) tmv = *gp; } #endif strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } /* Copy into out, trimming leading/trailing whitespace and CR/LF. */ static void trim_into(char *out, size_t osz, const char *src, size_t n) { size_t i = 0, k; if (!osz) return; while (i < n && (src[i] == ' ' || src[i] == '\t' || src[i] == '\r' || src[i] == '\n')) i++; while (n > i && (src[n - 1] == ' ' || src[n - 1] == '\t' || src[n - 1] == '\r' || src[n - 1] == '\n')) n--; k = n - i; if (k >= osz) k = osz - 1; /* callers trim a buffer in place, so the move may overlap */ if (k) memmove(out, src + i, k); out[k] = '\0'; } static int ci_contains(const char *hay, const char *needle) { size_t nl; if (!hay || !needle || !*needle) return 1; nl = strlen(needle); for (; *hay; hay++) { size_t i = 0; while (i < nl && hay[i] && tolower((unsigned char)hay[i]) == tolower((unsigned char)needle[i])) i++; if (i == nl) return 1; } return 0; } /* Case-insensitive substring test used for severity heuristics. */ static int has_word(const char *s, const char *w) { return ci_contains(s, w); } static int severity_of(const char *text, const char *level) { if (level && *level) { if (has_word(level, "err") || has_word(level, "crit") || has_word(level, "alert") || has_word(level, "emerg")) return SEV_ERR; if (has_word(level, "warn")) return SEV_WARN; } if (!text) return SEV_INFO; if (has_word(text, "panic") || has_word(text, "fatal") || has_word(text, "critical") || has_word(text, "segfault") || has_word(text, "traceback") || has_word(text, "error") || has_word(text, "err:") || has_word(text, "failed") || has_word(text, "failure") || has_word(text, "denied")) return SEV_ERR; if (has_word(text, "warn") || has_word(text, "deprecated") || has_word(text, "timeout") || has_word(text, "retry")) return SEV_WARN; return SEV_INFO; } static const char *sev_name(int sev) { return sev == SEV_ERR ? "err" : sev == SEV_WARN ? "warn" : "info"; } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ /* * The node API on the node's api port 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 the web front * 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); } /* ------------------------------------------------------------------ */ /* Source registry */ /* ------------------------------------------------------------------ */ typedef struct { char id[600]; /* journal | journal: | file: | event: */ char label[96]; char kind[10]; /* journal | file | event */ long long size; long mtime; } src_t; typedef struct { int journal_avail; src_t items[MAX_SRC]; int n; int truncated; } srcs_t; static void add_src(srcs_t *o, const char *id, const char *label, const char *kind, long long size, long mtime) { int i; if (o->n >= MAX_SRC) { o->truncated = 1; return; } for (i = 0; i < o->n; i++) if (strcmp(o->items[i].id, id) == 0) return; snprintf(o->items[o->n].id, sizeof(o->items[0].id), "%s", id); snprintf(o->items[o->n].label, sizeof(o->items[0].label), "%s", label); snprintf(o->items[o->n].kind, sizeof(o->items[0].kind), "%s", kind); o->items[o->n].size = size; o->items[o->n].mtime = mtime; o->n++; } static const char *base_name(const char *path) { const char *s = path; const char *b = path; for (; *s; s++) if (*s == '/' || *s == '\\') b = s + 1; return b; } #if !defined(_WIN32) static int has_log_suffix(const char *name) { size_t l = strlen(name); return l > 4 && strcmp(name + l - 4, ".log") == 0; } static void add_file_src(srcs_t *o, const char *path) { struct stat st; char id[600]; if (o->n >= MAX_SRC) { o->truncated = 1; return; } if (stat(path, &st) != 0) return; if (!S_ISREG(st.st_mode)) return; if (st.st_size <= 0) return; if (strlen(path) + 6 >= sizeof(id)) return; snprintf(id, sizeof(id), "file:%s", path); add_src(o, id, base_name(path), "file", (long long)st.st_size, (long)st.st_mtime); } /* * Bounded walk of one allowlisted root. Each root carries its own entry * budget so a large /workspace can never consume the allowance that * $HOME/.scorpiox needs. Symlinks are never followed. */ static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) { DIR *d; struct dirent *e; char p[1024]; if (depth < 0 || *budget <= 0 || !dir || !*dir) return; d = opendir(dir); if (!d) return; while ((e = readdir(d)) != NULL) { struct stat st; if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue; if (--(*budget) <= 0) { o->truncated = 1; break; } if (strlen(dir) + strlen(e->d_name) + 2 >= sizeof(p)) continue; snprintf(p, sizeof(p), "%s/%s", dir, e->d_name); if (lstat(p, &st) != 0) continue; if (S_ISLNK(st.st_mode)) continue; if (S_ISDIR(st.st_mode)) { if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); } else if (S_ISREG(st.st_mode)) { if (!log_only || has_log_suffix(e->d_name)) add_file_src(o, p); } } closedir(d); } /* * "journalctl exists" is not the same as "this node has a journal". Debian * slim containers ship the binary with no journald running underneath, so the * UI would offer a source that silently returns nothing. Require the binary * AND one of the two journal directories systemd actually writes. */ static int journal_available(void) { static const char *bins[] = { "/usr/bin/journalctl", "/bin/journalctl", "/usr/local/bin/journalctl", "/usr/sbin/journalctl", NULL }; static const char *dirs[] = { "/run/systemd/journal", "/run/log/journal", "/var/log/journal", NULL }; int i, have_bin = 0, have_dir = 0; for (i = 0; bins[i]; i++) if (access(bins[i], X_OK) == 0) { have_bin = 1; break; } if (!have_bin) return 0; for (i = 0; dirs[i]; i++) if (access(dirs[i], F_OK) == 0) { have_dir = 1; break; } return have_dir; } static void scan_sources(srcs_t *o) { int budget; char home[512]; char p[1024]; memset(o, 0, sizeof(*o)); #if defined(_WIN32) o->journal_avail = 0; /* Windows exposes the event log instead */ #else o->journal_avail = journal_available(); # if defined(__APPLE__) /* `log` is part of the base system and needs no daemon probe */ o->journal_avail = 1; # endif #endif if (o->journal_avail) add_src(o, "journal", # if defined(__APPLE__) "Unified log", # else "System journal", # endif "journal", 0LL, 0L); #if defined(__APPLE__) /* the per-file *.log scan plus the classic system.log */ budget = 8000; scan_root(o, "/var/log", 0, &budget, 1); add_file_src(o, "/var/log/system.log"); home[0] = '\0'; if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); if (home[0]) { snprintf(p, sizeof(p), "%s/Library/Logs", home); budget = 8000; scan_root(o, p, 3, &budget, 1); } #else /* the per-file *.log scan plus the distro-specific aggregate files */ budget = 12000; scan_root(o, "/var/log", 0, &budget, 1); add_file_src(o, "/var/log/syslog"); add_file_src(o, "/var/log/messages"); add_file_src(o, "/var/log/kern.log"); add_file_src(o, "/var/log/auth.log"); home[0] = '\0'; if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); if (home[0]) { snprintf(p, sizeof(p), "%s/.scorpiox", home); budget = ROOT_BUDGET; scan_root(o, p, 4, &budget, 1); } budget = ROOT_BUDGET; scan_root(o, "/workspace", 4, &budget, 1); #endif /* * Test-only knob: one extra allowlisted root so tests/run.sh can point the * plugin at fixture logs without inventing a path that production would * never serve. Only the operator who starts the process can set it. */ { const char *extra = getenv("SX_LOGS_EXTRA_ROOT"); if (extra && *extra) { budget = 4000; scan_root(o, extra, 2, &budget, 1); } } } #else /* _WIN32 */ static int has_log_suffix(const char *name) { size_t l = strlen(name); return l > 4 && strcmp(name + l - 4, ".log") == 0; } static void add_file_src(srcs_t *o, const char *path) { DWORD a = GetFileAttributesA(path); WIN32_FILE_ATTRIBUTE_DATA fad; char id[600]; if (o->n >= MAX_SRC) { o->truncated = 1; return; } if (a == INVALID_FILE_ATTRIBUTES) return; if (a & FILE_ATTRIBUTE_DIRECTORY) return; if (strlen(path) + 6 >= sizeof(id)) return; if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return; snprintf(id, sizeof(id), "file:%s", path); add_src(o, id, base_name(path), "file", (long long)fad.nFileSizeLow, 0L); } static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) { WIN32_FIND_DATAA fd; HANDLE h; char pat[1024]; char p[1024]; if (depth < 0 || *budget <= 0 || !dir || !*dir) return; if (strlen(dir) + 3 >= sizeof(pat)) return; snprintf(pat, sizeof(pat), "%s\\*", dir); h = FindFirstFileA(pat, &fd); if (h == INVALID_HANDLE_VALUE) return; do { if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue; if (--(*budget) <= 0) { o->truncated = 1; break; } if (strlen(dir) + strlen(fd.cFileName) + 2 >= sizeof(p)) continue; snprintf(p, sizeof(p), "%s\\%s", dir, fd.cFileName); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); } else if (!log_only || has_log_suffix(fd.cFileName)) { add_file_src(o, p); } } while (FindNextFileA(h, &fd)); FindClose(h); } static void scan_sources(srcs_t *o) { int budget = ROOT_BUDGET; char p[1024]; const char *lad = getenv("LOCALAPPDATA"); memset(o, 0, sizeof(*o)); o->journal_avail = 0; /* Windows uses the event log instead */ /* The two archives the plugin exposes on Windows. */ add_src(o, "event:System", "Windows System log", "event", 0LL, 0L); add_src(o, "event:Application", "Windows Application log", "event", 0LL, 0L); if (lad && *lad) { snprintf(p, sizeof(p), "%s\\scorpiox", lad); scan_root(o, p, 4, &budget, 1); } if (getenv("USERPROFILE")) { snprintf(p, sizeof(p), "%s\\AppData\\Local\\scorpiox", getenv("USERPROFILE")); scan_root(o, p, 4, &budget, 1); } } #endif /* Resolve a src id to an allowlisted entry. Returns NULL if not in the list. */ static const src_t *find_src(const srcs_t *o, const char *id) { int i; if (!id || !*id) return NULL; for (i = 0; i < o->n; i++) if (strcmp(o->items[i].id, id) == 0) return &o->items[i]; return NULL; } /* ------------------------------------------------------------------ */ /* Entry lists */ /* ------------------------------------------------------------------ */ typedef struct { char ts[ENTRY_TS]; char unit[ENTRY_UNIT]; int sev; char text[ENTRY_TEXT]; } entry_t; typedef struct { entry_t *v; int cap; int n; int start; } ring_t; static int ring_init(ring_t *r, int cap) { if (cap < 1) cap = 1; r->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); if (!r->v) return 0; r->cap = cap; r->n = 0; r->start = 0; return 1; } static void ring_add(ring_t *r, const entry_t *e) { if (r->n < r->cap) { r->v[(r->start + r->n) % r->cap] = *e; r->n++; } else { r->v[r->start] = *e; r->start = (r->start + 1) % r->cap; } } static entry_t *ring_at(ring_t *r, int i) { return &r->v[(r->start + i) % r->cap]; } static void ring_free(ring_t *r) { free(r->v); r->v = NULL; } typedef struct { entry_t *v; int cap; int n; } list_t; static int list_init(list_t *l, int cap) { if (cap < 1) cap = 1; l->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); if (!l->v) return 0; l->cap = cap; l->n = 0; return 1; } static void list_free(list_t *l) { free(l->v); l->v = NULL; } /* ------------------------------------------------------------------ */ /* Command execution (fixed argv only) */ /* ------------------------------------------------------------------ */ static FILE *run_cmd(const char *cmd) { #if defined(_WIN32) return _popen(cmd, "r"); #else return popen(cmd, "r"); #endif } static int close_cmd(FILE *f) { #if defined(_WIN32) return _pclose(f); #else return pclose(f); #endif } /* Validate a systemd unit name before it can reach the fixed argv. */ static int valid_unit(const char *u) { size_t i, l; if (!u || !*u) return 0; l = strlen(u); if (l > 128) return 0; for (i = 0; i < l; i++) { unsigned char c = (unsigned char)u[i]; if (!(isalnum(c) || c == '@' || c == '.' || c == '_' || c == '-')) return 0; } /* a leading '-' would read as an option to journalctl */ return u[0] != '-'; } /* ------------------------------------------------------------------ */ /* Journal parsing (journalctl -o json, one object per line) */ /* ------------------------------------------------------------------ */ /* * Extract one top-level key's value from a single journal JSON object line. * Handles string values with backslash escapes, numeric values, and String * arrays (journal stores binary or multi-line MESSAGE fields as arrays, which * this plugin renders as a placeholder rather than pretending to decode). */ static int jget(const char *line, const char *key, char *out, size_t osz) { char pat[128]; const char *p; if (osz) out[0] = '\0'; if (!line || !key || !*key) return 0; /* the search key is a fixed literal from this file, never user input */ snprintf(pat, sizeof(pat), "\"%s\"", key); for (p = line; (p = strstr(p, pat)) != NULL; p += strlen(pat)) { const char *q = p + strlen(pat); while (*q == ' ' || *q == '\t') q++; if (*q != ':') continue; /* a value that happens to match */ q++; while (*q == ' ' || *q == '\t') q++; if (*q == '"') { size_t o = 0; q++; while (*q && *q != '"') { char c = *q; if (c == '\\' && q[1]) { q++; switch (*q) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case '"': c = '"'; break; case '\\': c = '\\'; break; case '/': c = '/'; break; default: c = *q; break; } } if (o + 1 < osz) out[o++] = c; q++; } out[o] = '\0'; return 1; } if (*q == '[') { /* journal stores binary or multi-line fields as byte arrays */ snprintf(out, osz, "(binary)"); return 1; } { size_t o = 0; while (*q && *q != ',' && *q != '}') { if (o + 1 < osz) out[o++] = *q; q++; } out[o] = '\0'; return 1; } } return 0; } static void fmt_journal_ts(const char *us, char *out, size_t osz) { long long v; time_t secs; struct tm tmv; if (!us || !*us) { snprintf(out, osz, "-"); return; } v = atoll(us); if (v <= 0) { snprintf(out, osz, "-"); return; } secs = (time_t)(v / 1000000LL); if (!localtime_r(&secs, &tmv)) { snprintf(out, osz, "-"); return; } strftime(out, osz, "%m-%d %H:%M:%S", &tmv); } /* * Stream journalctl into `sink`. `filter` (optional) keeps only lines whose * text, unit or timestamp matches case-insensitively. Returns the number of * lines scanned, or -1 when journalctl could not be run. */ typedef void (*entry_sink)(void *ctx, const entry_t *e); static int stream_journal(const char *unit, int nlines, const char *filter, entry_sink sink, void *ctx) { #if defined(_WIN32) (void)unit; (void)nlines; (void)filter; (void)sink; (void)ctx; return -1; #else char cmd[512]; FILE *f; char line[8192]; int scanned = 0; int uok = unit && *unit && valid_unit(unit); const char *fixture = getenv("SX_LOGS_JOURNAL_FIXTURE"); if (unit && *unit && !uok) return -1; if (nlines < 1) nlines = 1; if (nlines > TAIL_MAX) nlines = TAIL_MAX; if (uok) snprintf(cmd, sizeof(cmd), "journalctl -o json --no-pager -n %d -u %s 2>/dev/null", nlines, unit); else snprintf(cmd, sizeof(cmd), "journalctl -o json --no-pager -n %d 2>/dev/null", nlines); /* test-only: replay a captured journalctl -o json stream */ if (fixture && *fixture) f = fopen(fixture, "r"); else f = run_cmd(cmd); if (!f) return -1; while (fgets(line, sizeof(line), f)) { entry_t e; char msg[ENTRY_TEXT] = ""; char pri[8] = ""; char tsus[32] = ""; char un[ENTRY_UNIT] = ""; int prio; if (line[0] != '{') continue; scanned++; jget(line, "MESSAGE", msg, sizeof(msg)); jget(line, "PRIORITY", pri, sizeof(pri)); jget(line, "__REALTIME_TIMESTAMP", tsus, sizeof(tsus)); if (!jget(line, "_SYSTEMD_UNIT", un, sizeof(un))) jget(line, "SYSLOG_IDENTIFIER", un, sizeof(un)); memset(&e, 0, sizeof(e)); fmt_journal_ts(tsus, e.ts, sizeof(e.ts)); snprintf(e.unit, sizeof(e.unit), "%s", un); prio = pri[0] ? atoi(pri) : 6; e.sev = prio <= 3 ? SEV_ERR : prio == 4 ? SEV_WARN : SEV_INFO; snprintf(e.text, sizeof(e.text), "%s", msg); if (e.sev == SEV_INFO) e.sev = severity_of(e.text, NULL); if (filter && *filter && !ci_contains(e.text, filter) && !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) continue; sink(ctx, &e); } if (fixture && *fixture) fclose(f); else close_cmd(f); return scanned; #endif } /* ------------------------------------------------------------------ */ /* Plain log-file reading */ /* ------------------------------------------------------------------ */ /* * Works out the byte offset to start reading from so only the last `maxbytes` * of a file are considered. Logs grow to gigabytes; a viewer must never read * one in full. */ static long tail_offset(long long size, long maxbytes) { if (size <= maxbytes) return 0; return (long)(size - maxbytes); } #if !defined(_WIN32) static int open_log(const char *path, FILE **out, long long *size_out) { struct stat st; if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) return -1; *out = fopen(path, "rb"); if (!*out) return -1; *size_out = (long long)st.st_size; return 0; } #else static int open_log(const char *path, FILE **out, long long *size_out) { WIN32_FILE_ATTRIBUTE_DATA fad; if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return -1; if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return -1; *out = fopen(path, "rb"); if (!*out) return -1; *size_out = (long long)fad.nFileSizeLow; return 0; } #endif /* Fill one entry from a raw log line. Detects the two timestamp layouts that * nearly every text log uses, and falls back to no timestamp. */ static void entry_from_line(entry_t *e, const char *line, size_t n) { char buf[ENTRY_TEXT * 2]; memset(e, 0, sizeof(*e)); if (n >= sizeof(buf)) n = sizeof(buf) - 1; memcpy(buf, line, n); buf[n] = '\0'; while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; /* syslog: "Nov 12 06:30:01 host unit[pid]: message" */ if (n > 16 && isalpha((unsigned char)buf[0]) && buf[3] == ' ' && isdigit((unsigned char)buf[4]) && buf[6] == ' ' && buf[9] == ':') { snprintf(e->ts, sizeof(e->ts), "%.15s", buf); /* everything after "host " is the text, unit if it looks like one */ { const char *p = buf + 16; const char *colon; while (*p && *p != ' ') p++; while (*p == ' ') p++; colon = strchr(p, ':'); if (colon && (size_t)(colon - p) < sizeof(e->unit) && (size_t)(colon - p) < 64) { snprintf(e->unit, sizeof(e->unit), "%.*s", (int)(colon - p), p); snprintf(e->text, sizeof(e->text), "%s", colon + 1); } else { snprintf(e->text, sizeof(e->text), "%.*s", (int)(sizeof(e->text) - 1), p); } trim_into(e->text, sizeof(e->text), e->text, strlen(e->text)); e->sev = severity_of(e->text, NULL); return; } } /* ISO-8601 prefix: "2026-11-12T06:30:01Z rest" or "2026-11-12 06:30:01 rest" */ if (n > 20 && isdigit((unsigned char)buf[0]) && buf[4] == '-' && buf[7] == '-' && (buf[10] == 'T' || buf[10] == ' ')) { size_t cut = 11; while (cut < n && cut < 32 && buf[cut] != ' ' && buf[cut] != '\t') cut++; snprintf(e->ts, sizeof(e->ts), "%.*s", (int)(cut < 24 ? cut : 24), buf); { const char *p = buf + cut; while (*p == ' ' || *p == '\t') p++; snprintf(e->text, sizeof(e->text), "%.*s", (int)(sizeof(e->text) - 1), p); } e->sev = severity_of(e->text, NULL); return; } snprintf(e->text, sizeof(e->text), "%.*s", (int)(sizeof(e->text) - 1), buf); e->sev = severity_of(e->text, NULL); } typedef struct { ring_t *ring; list_t *hits; const char *filter; int seen; int cap; } file_ctx_t; static void file_sink(void *vctx, const entry_t *e) { file_ctx_t *c = (file_ctx_t *)vctx; if (c->ring) ring_add(c->ring, e); if (c->hits) { if (c->hits->n < c->cap) c->hits->v[c->hits->n++] = *e; } c->seen++; } /* * Read the tail of a log file. `ring` keeps the last N entries (tail mode); * `hits` collects up to `cap` matching entries (search mode). Exactly one of * them is non-NULL. */ static int read_log_file(const char *path, int nlines, const char *filter, ring_t *ring, list_t *hits, int hitcap) { FILE *f = NULL; long long size = 0; long off; char line[ENTRY_TEXT * 2]; file_ctx_t ctx; (void)nlines; /* the ring/hit list owns the cap; this is only a hint */ if (open_log(path, &f, &size) != 0) return -1; memset(&ctx, 0, sizeof(ctx)); ctx.ring = ring; ctx.hits = hits; ctx.filter = filter; ctx.cap = hitcap; off = tail_offset(size, FILE_TAIL_BYTES); if (off > 0 && fseek(f, off, SEEK_SET) != 0) { fclose(f); return -1; } while (fgets(line, sizeof(line), f)) { entry_t e; size_t n = strlen(line); /* The first line after a tail seek is a partial line; drop it. */ if (off > 0 && ctx.seen == 0 && n > 0 && line[n - 1] != '\n') { ctx.seen = 0; /* still consume it so we do not emit a broken record */ continue; } if (hits && ctx.seen >= SEARCH_SCAN) break; entry_from_line(&e, line, n); if (filter && *filter && !ci_contains(e.text, filter) && !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) { ctx.seen++; continue; } file_sink(&ctx, &e); } fclose(f); return ctx.seen; } /* ------------------------------------------------------------------ */ /* macOS `log show` reading */ /* ------------------------------------------------------------------ */ #if defined(__APPLE__) static int stream_macos_log(int nlines, const char *filter, entry_sink sink, void *ctx) { char cmd[512]; FILE *f; char line[8192]; int scanned = 0; int mins; if (nlines < 1) nlines = 1; if (nlines > TAIL_MAX) nlines = TAIL_MAX; /* bound the time window: roughly one minute of syslog per 200 lines */ mins = nlines / 200; if (mins < 1) mins = 1; if (mins > 60) mins = 60; /* * Absolute path, and it matters: on macOS `log` is also a zsh shell * builtin, so a bare `log show` run through a user's shell prints * "zsh:log: too many arguments" and exits 0 with no output. popen uses * /bin/sh so it is only latent there, but the fixed path removes the * class of failure entirely. */ snprintf(cmd, sizeof(cmd), "/usr/bin/log show --style compact --last %dm 2>/dev/null | tail -n %d", mins, nlines); f = run_cmd(cmd); if (!f) return -1; while (fgets(line, sizeof(line), f)) { entry_t e; size_t n = strlen(line); if (filter && *filter && !ci_contains(line, filter)) { scanned++; continue; } scanned++; entry_from_line(&e, line, n); sink(ctx, &e); } close_cmd(f); return scanned; } #endif /* ------------------------------------------------------------------ */ /* Windows event log reading */ /* ------------------------------------------------------------------ */ #if defined(_WIN32) static int stream_event_log(const char *channel, int nlines, const char *filter, entry_sink sink, void *ctx) { char cmd[512]; FILE *f; char line[8192]; int scanned = 0; if (nlines < 1) nlines = 1; if (nlines > TAIL_MAX) nlines = TAIL_MAX; if (!channel || !*channel) return -1; /* channel is one of two constants chosen by the caller, never user text */ if (strcmp(channel, "System") != 0 && strcmp(channel, "Application") != 0) return -1; snprintf(cmd, sizeof(cmd), "wevtutil qe %s /c:%d /rd:true /f:text 2>NUL", channel, nlines); f = run_cmd(cmd); if (!f) return -1; { entry_t e; int have = 0; memset(&e, 0, sizeof(e)); while (fgets(line, sizeof(line), f)) { char t[ENTRY_TEXT]; trim_into(t, sizeof(t), line, strlen(line)); if (!*t) { if (have && e.text[0]) { e.sev = severity_of(e.text, NULL); if (!filter || !*filter || ci_contains(e.text, filter)) sink(ctx, &e); scanned++; } memset(&e, 0, sizeof(e)); have = 0; continue; } have = 1; if (strncmp(t, "Date:", 5) == 0) { snprintf(e.ts, sizeof(e.ts), "%s", t + 5); trim_into(e.ts, sizeof(e.ts), e.ts, strlen(e.ts)); } else if (strncmp(t, "Level:", 6) == 0) { const char *lv = t + 6; while (*lv == ' ') lv++; snprintf(e.unit, sizeof(e.unit), "%s", channel); if (ci_contains(lv, "Error") || ci_contains(lv, "Critical")) e.sev = SEV_ERR; else if (ci_contains(lv, "Warning")) e.sev = SEV_WARN; } else if (strncmp(t, "Description:", 12) == 0) { snprintf(e.text, sizeof(e.text), "%s", t + 12); trim_into(e.text, sizeof(e.text), e.text, strlen(e.text)); } } if (have && e.text[0]) { e.sev = severity_of(e.text, NULL); if (!filter || !*filter || ci_contains(e.text, filter)) sink(ctx, &e); scanned++; } } close_cmd(f); return scanned; } #endif /* ------------------------------------------------------------------ */ /* Units (service providers that have journal entries) */ /* ------------------------------------------------------------------ */ typedef struct { char name[ENTRY_UNIT]; int entries; } unit_t; static int list_units(unit_t *out, int max) { #if defined(_WIN32) || defined(__APPLE__) (void)out; (void)max; return 0; #else FILE *f; char line[1024]; int n = 0; f = run_cmd("journalctl --no-pager -F _SYSTEMD_UNIT 2>/dev/null | head -n 400"); if (!f) return 0; while (fgets(line, sizeof(line), f) && n < max) { char u[ENTRY_UNIT]; int i; trim_into(u, sizeof(u), line, strlen(line)); if (!*u) continue; if (!valid_unit(u)) continue; for (i = 0; i < n; i++) if (strcmp(out[i].name, u) == 0) break; if (i < n) continue; snprintf(out[n].name, sizeof(out[n].name), "%s", u); out[n].entries = 0; n++; } close_cmd(f); return n; #endif } /* ------------------------------------------------------------------ */ /* Collection helpers */ /* ------------------------------------------------------------------ */ typedef struct { ring_t *ring; } shell_ctx_t; static void shell_sink(void *vctx, const entry_t *e) { ring_t *r = ((shell_ctx_t *)vctx)->ring; ring_add(r, e); } /* Stream `nlines` entries for a source into `ring` (tail mode). */ static int collect_tail(const src_t *s, int nlines, ring_t *ring) { shell_ctx_t ctx; ctx.ring = ring; /* Platform first: on macOS the "journal" kind is `log show`, not * journalctl, and the generic branch below would swallow it. */ #if defined(__APPLE__) if (strcmp(s->kind, "journal") == 0) return stream_macos_log(nlines, NULL, shell_sink, &ctx); #elif defined(_WIN32) if (strncmp(s->id, "event:", 6) == 0) return stream_event_log(s->id + 6, nlines, NULL, shell_sink, &ctx); #else if (strcmp(s->kind, "journal") == 0) return stream_journal(NULL, nlines, NULL, shell_sink, &ctx); #endif if (strncmp(s->id, "file:", 5) == 0) return read_log_file(s->id + 5, nlines, NULL, ring, NULL, 0); if (strncmp(s->id, "journal:", 8) == 0) return stream_journal(s->id + 8, nlines, NULL, shell_sink, &ctx); return -1; } typedef struct { list_t *hits; } hits_ctx_t; static void hits_sink(void *vctx, const entry_t *e) { list_t *l = ((hits_ctx_t *)vctx)->hits; if (l->n < l->cap) l->v[l->n++] = *e; } /* Search a source for `filter`. Returns the number of lines scanned. */ static int collect_search(const src_t *s, const char *filter, list_t *hits) { hits_ctx_t ctx; ctx.hits = hits; /* same platform-first order as collect_tail */ #if defined(__APPLE__) if (strcmp(s->kind, "journal") == 0) return stream_macos_log(TAIL_MAX, filter, hits_sink, &ctx); #elif defined(_WIN32) if (strncmp(s->id, "event:", 6) == 0) return stream_event_log(s->id + 6, 600, filter, hits_sink, &ctx); #else if (strcmp(s->kind, "journal") == 0) return stream_journal(NULL, TAIL_MAX, filter, hits_sink, &ctx); #endif if (strncmp(s->id, "file:", 5) == 0) return read_log_file(s->id + 5, TAIL_MAX, filter, NULL, hits, SEARCH_HITS_MAX); if (strncmp(s->id, "journal:", 8) == 0) return stream_journal(s->id + 8, TAIL_MAX, filter, hits_sink, &ctx); return -1; } /* ------------------------------------------------------------------ */ /* Modes */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { puts("{\"name\":\"logs\",\"desc\":\"Log viewer\"}"); 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 int mode_json(const char *qs) { char action[32]; char srcid[600]; char linesv[16]; char q[256]; char utc[40]; srcs_t srcs; int nlines = 200; action[0] = srcid[0] = linesv[0] = q[0] = '\0'; get_query_val(qs, "action", action, sizeof(action)); get_query_val(qs, "src", srcid, sizeof(srcid)); get_query_val(qs, "lines", linesv, sizeof(linesv)); get_query_val(qs, "q", q, sizeof(q)); /* anything above the cap is clamped, never silently ignored */ if (linesv[0]) { int v = atoi(linesv); if (v > 0) nlines = v > TAIL_MAX ? TAIL_MAX : v; } if (!action[0] || (strcmp(action, "sources") != 0 && strcmp(action, "tail") != 0 && strcmp(action, "search") != 0 && strcmp(action, "units") != 0 && strcmp(action, "info") != 0)) { json_header(); printf("{\"ok\":false,\"error\":\"unknown_action\",\"supported\":" "[\"sources\",\"tail\",\"search\",\"units\",\"info\"],\"requested\":"); json_str(action); fputs("}\n", stdout); return 0; } utc_now(utc, sizeof(utc)); if (strcmp(action, "info") == 0) { json_header(); fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," "\"version\":\"" PLUGIN_VER "\",\"utc\":", stdout); json_str(utc); printf(",\"platform\":\"%s\"", #if defined(_WIN32) "windows" #elif defined(__APPLE__) "macos" #else "linux" #endif ); fputs(",\"limits\":{\"lines_max\":", stdout); printf("%d", TAIL_MAX); fputs(",\"search_hits_max\":", stdout); printf("%d", SEARCH_HITS_MAX); fputs(",\"search_scan_max\":", stdout); printf("%d", SEARCH_SCAN); fputs("},\"supported\":[\"sources\",\"tail\",\"search\",\"units\",\"info\"]," "\"zero_network\":true,\"read_only\":true,\"node_auth\":", stdout); { const char *np = getenv("BOT_PASSWORD"); fputs((np && *np) ? "true" : "false", stdout); } fputs("}\n", stdout); return 0; } scan_sources(&srcs); if (strcmp(action, "sources") == 0) { int i; json_header(); fputs("{\"ok\":true,\"action\":\"sources\",\"plugin\":\"" PLUGIN_ID "\"," "\"utc\":", stdout); json_str(utc); printf(",\"journal_available\":%s,\"count\":%d,\"truncated\":%s,\"sources\":[", srcs.journal_avail ? "true" : "false", srcs.n, srcs.truncated ? "true" : "false"); for (i = 0; i < srcs.n; i++) { if (i) fputc(',', stdout); fputs("{\"id\":", stdout); json_str(srcs.items[i].id); fputs(",\"label\":", stdout); json_str(srcs.items[i].label); fputs(",\"kind\":", stdout); json_str(srcs.items[i].kind); printf(",\"size\":%lld,\"mtime\":%ld}", srcs.items[i].size, srcs.items[i].mtime); } fputs("]}\n", stdout); return 0; } if (strcmp(action, "units") == 0) { static unit_t units[MAX_UNITS]; int n = 0, i; #if !defined(_WIN32) && !defined(__APPLE__) n = list_units(units, MAX_UNITS); #else (void)units; #endif json_header(); fputs("{\"ok\":true,\"action\":\"units\",\"available\":", stdout); #if !defined(_WIN32) && !defined(__APPLE__) fputs("true", stdout); #else fputs("false", stdout); #endif printf(",\"count\":%d,\"units\":[", n); for (i = 0; i < n; i++) { if (i) fputc(',', stdout); fputs("{\"name\":", stdout); json_str(units[i].name); printf(",\"src\":\"journal:%s\"}", units[i].name); } fputs("]}\n", stdout); return 0; } { const src_t *s = find_src(&srcs, srcid); char srcbuf[32]; snprintf(srcbuf, sizeof(srcbuf), "%s", srcid); if (!s) { json_header(); fputs("{\"ok\":false,\"error\":\"source_not_allowed\"," "\"message\":\"that path is not in this plugin's read allowlist; " "call action=sources for the current list\",\"requested\":", stdout); json_str(srcbuf); fputs("}\n", stdout); return 0; } if (!*s->kind) { json_header(); fputs("{\"ok\":false,\"error\":\"source_unavailable\"}\n", stdout); return 0; } if (strcmp(action, "tail") == 0) { ring_t ring; int got; int i; if (!ring_init(&ring, nlines)) { json_header(); fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); return 0; } got = collect_tail(s, nlines, &ring); json_header(); if (got < 0) { fputs("{\"ok\":false,\"error\":\"unreadable_source\"," "\"message\":\"the source could not be read on this node\"," "\"src\":", stdout); json_str(s->id); fputs("}\n", stdout); ring_free(&ring); return 0; } fputs("{\"ok\":true,\"action\":\"tail\",\"plugin\":\"" PLUGIN_ID "\"," "\"utc\":", stdout); json_str(utc); fputs(",\"src\":", stdout); json_str(s->id); fputs(",\"label\":", stdout); json_str(s->label); fputs(",\"kind\":", stdout); json_str(s->kind); printf(",\"requested\":%d,\"count\":%d,\"entries\":[", nlines, ring.n); for (i = 0; i < ring.n; i++) { entry_t *e = ring_at(&ring, i); if (i) fputc(',', stdout); fputs("{\"ts\":", stdout); json_str(e->ts); fputs(",\"unit\":", stdout); json_str(e->unit); fputs(",\"sev\":", stdout); json_str(sev_name(e->sev)); fputs(",\"text\":", stdout); json_str(e->text); fputc('}', stdout); } fputs("]}\n", stdout); ring_free(&ring); return 0; } /* search */ { list_t hits; int scanned; int i; if (!q[0]) { json_header(); fputs("{\"ok\":false,\"error\":\"missing_query\"," "\"message\":\"action=search needs q=\"}\n", stdout); return 0; } if (!list_init(&hits, SEARCH_HITS_MAX)) { json_header(); fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); return 0; } scanned = collect_search(s, q, &hits); json_header(); if (scanned < 0) { fputs("{\"ok\":false,\"error\":\"unreadable_source\"," "\"src\":", stdout); json_str(s->id); fputs("}\n", stdout); list_free(&hits); return 0; } fputs("{\"ok\":true,\"action\":\"search\",\"plugin\":\"" PLUGIN_ID "\"," "\"utc\":", stdout); json_str(utc); fputs(",\"src\":", stdout); json_str(s->id); fputs(",\"label\":", stdout); json_str(s->label); fputs(",\"q\":", stdout); json_str(q); printf(",\"scanned\":%d,\"count\":%d,\"max\":%d,\"truncated\":%s,\"hits\":[", scanned, hits.n, SEARCH_HITS_MAX, hits.n >= SEARCH_HITS_MAX ? "true" : "false"); for (i = 0; i < hits.n; i++) { if (i) fputc(',', stdout); fputs("{\"ts\":", stdout); json_str(hits.v[i].ts); fputs(",\"unit\":", stdout); json_str(hits.v[i].unit); fputs(",\"sev\":", stdout); json_str(sev_name(hits.v[i].sev)); fputs(",\"text\":", stdout); json_str(hits.v[i].text); fputc('}', stdout); } fputs("]}\n", stdout); list_free(&hits); return 0; } } } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ 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" "" "logs", stdout); fputs(SX_BOT_THEME_PREPAINT "" SX_BOT_THEME_HANDOFF "
", stdout); if (!embed) { fputs("", stdout); } fputs("
" "

logs

" "—" "" "paused" "" "
", stdout); /* source + controls */ fputs("
" "" "
" "" "" "" "" "
" "" "" "" "" "" "" "
", stdout); fputs("
Loading sources…
", stdout); fputs("
" "0 entries" "" "local read only · zero network" "
", stdout); fputs("
" "Reads an allowlist of local log files and the local system journal. " "Every source is read-only; nothing is written, and no request leaves this node." "
", stdout); /* ---------------- script ---------------- */ fputs("
\n", stdout); return 0; } /* ------------------------------------------------------------------ */ /* Entry point */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; 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" " ?action=sources readable log sources\n" " ?action=tail&src=&lines= last N entries of a source\n" " ?action=search&src=&q= case-insensitive substring search\n" " ?action=units systemd units with journal entries\n" " ?action=info plugin info\n" " (no action) HTML log viewer\n", PLUGIN_ID); return 0; } } if (getenv("SX_PLUGIN_META")) return mode_meta(); require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; 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); }