| 1 | /* |
| 2 | * plugin_logs - SCORPIOX BOT open-source local log viewer 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=sources|tail|search|units -> JSON node API |
| 7 | * 3. GET (default) -> responsive HTML log tail & search UI |
| 8 | * |
| 9 | * Local node only. Reads an explicit allowlist of local log files (a bounded |
| 10 | * walk of /var/log, $HOME/.scorpiox, /workspace, ~/Library/Logs and |
| 11 | * %LOCALAPPDATA%\scorpiox) and the local system journal through a fixed argv |
| 12 | * with no user-controlled shell text. Makes ZERO outbound network requests, |
| 13 | * opens no sockets, reads no credentials. |
| 14 | * |
| 15 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 16 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 17 | * scorpiox-server on the node. |
| 18 | * |
| 19 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 20 | */ |
| 21 | |
| 22 | /* MinGW defaults to a Server 2003 target; the Win7+ APIs used below would be |
| 23 | * hidden by that gate. This must precede every include. */ |
| 24 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 25 | # define _WIN32_WINNT 0x0601 |
| 26 | #endif |
| 27 | |
| 28 | #if defined(__APPLE__) |
| 29 | /* sys/types.h pulls BSD types (u_int) that strict c99 would hide */ |
| 30 | # define _DARWIN_C_SOURCE 1 |
| 31 | #elif !defined(_WIN32) |
| 32 | # define _POSIX_C_SOURCE 200809L |
| 33 | # define _DEFAULT_SOURCE 1 |
| 34 | #endif |
| 35 | |
| 36 | #include <stdio.h> |
| 37 | #include <stdlib.h> |
| 38 | #include <string.h> |
| 39 | #include <time.h> |
| 40 | #include <ctype.h> |
| 41 | #include <errno.h> |
| 42 | |
| 43 | #if defined(_WIN32) |
| 44 | |
| 45 | # define WIN32_LEAN_AND_MEAN |
| 46 | # include <windows.h> |
| 47 | # include <io.h> |
| 48 | |
| 49 | #else |
| 50 | |
| 51 | # include <unistd.h> |
| 52 | # include <dirent.h> |
| 53 | # include <sys/types.h> |
| 54 | # include <sys/stat.h> |
| 55 | |
| 56 | #endif |
| 57 | |
| 58 | #include "bot_theme_plugin.h" |
| 59 | |
| 60 | #define PLUGIN_SLUG "logs" |
| 61 | #define PLUGIN_ID "plugin_logs" |
| 62 | #define PLUGIN_VER "1.0.0" |
| 63 | |
| 64 | #define MAX_SRC 256 |
| 65 | #define MAX_UNITS 512 |
| 66 | #define ENTRY_TEXT 1024 |
| 67 | #define ENTRY_UNIT 96 |
| 68 | #define ENTRY_TS 40 |
| 69 | #define TAIL_MAX 2000 |
| 70 | #define SEARCH_HITS_MAX 500 |
| 71 | #define SEARCH_SCAN 8000 |
| 72 | #define FILE_TAIL_BYTES (4L * 1024L * 1024L) |
| 73 | #define ROOT_BUDGET 40000 |
| 74 | |
| 75 | /* Severity buckets: 0 info, 1 warn, 2 err */ |
| 76 | #define SEV_INFO 0 |
| 77 | #define SEV_WARN 1 |
| 78 | #define SEV_ERR 2 |
| 79 | |
| 80 | /* ------------------------------------------------------------------ */ |
| 81 | /* Small utilities */ |
| 82 | /* ------------------------------------------------------------------ */ |
| 83 | |
| 84 | static void url_decode(char *s) |
| 85 | { |
| 86 | char *o = s; |
| 87 | if (!s) return; |
| 88 | while (*s) { |
| 89 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 90 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 91 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 92 | *o++ = (char)((hi << 4) | lo); |
| 93 | s += 3; |
| 94 | } else if (*s == '+') { |
| 95 | *o++ = ' '; |
| 96 | s++; |
| 97 | } else { |
| 98 | *o++ = *s++; |
| 99 | } |
| 100 | } |
| 101 | *o = '\0'; |
| 102 | } |
| 103 | |
| 104 | /* Copy one query parameter into out. Returns 1 when present. */ |
| 105 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 106 | { |
| 107 | size_t klen = strlen(key); |
| 108 | const char *p = qs; |
| 109 | |
| 110 | if (outsz) out[0] = '\0'; |
| 111 | if (!qs || !klen) return 0; |
| 112 | |
| 113 | while (p && *p) { |
| 114 | const char *amp = strchr(p, '&'); |
| 115 | const char *end = amp ? amp : p + strlen(p); |
| 116 | const char *eq = memchr(p, '=', (size_t)(end - p)); |
| 117 | |
| 118 | if (eq && (size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) { |
| 119 | size_t vlen = (size_t)(end - eq - 1); |
| 120 | if (vlen >= outsz) vlen = outsz ? outsz - 1 : 0; |
| 121 | if (vlen) memcpy(out, eq + 1, vlen); |
| 122 | out[vlen] = '\0'; |
| 123 | url_decode(out); |
| 124 | return 1; |
| 125 | } |
| 126 | p = amp ? amp + 1 : NULL; |
| 127 | } |
| 128 | return 0; |
| 129 | } |
| 130 | |
| 131 | static void json_str(const char *s) |
| 132 | { |
| 133 | const unsigned char *p = (const unsigned char *)s; |
| 134 | fputc('"', stdout); |
| 135 | if (p) { |
| 136 | for (; *p; p++) { |
| 137 | switch (*p) { |
| 138 | case '"': fputs("\\\"", stdout); break; |
| 139 | case '\\': fputs("\\\\", stdout); break; |
| 140 | case '\n': fputs("\\n", stdout); break; |
| 141 | case '\r': fputs("\\r", stdout); break; |
| 142 | case '\t': fputs("\\t", stdout); break; |
| 143 | default: |
| 144 | if (*p < 0x20) printf("\\u%04x", *p); |
| 145 | else fputc((int)*p, stdout); |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | fputc('"', stdout); |
| 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 | struct tm *lt = localtime(&t); |
| 158 | if (lt) tmv = *lt; |
| 159 | #else |
| 160 | localtime_r(&t, &tmv); |
| 161 | #endif |
| 162 | #if defined(_WIN32) |
| 163 | { |
| 164 | struct tm *gp = gmtime(&t); |
| 165 | if (gp) tmv = *gp; |
| 166 | } |
| 167 | #endif |
| 168 | strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); |
| 169 | } |
| 170 | |
| 171 | /* Copy into out, trimming leading/trailing whitespace and CR/LF. */ |
| 172 | static void trim_into(char *out, size_t osz, const char *src, size_t n) |
| 173 | { |
| 174 | size_t i = 0, k; |
| 175 | if (!osz) return; |
| 176 | while (i < n && (src[i] == ' ' || src[i] == '\t' || src[i] == '\r' || src[i] == '\n')) i++; |
| 177 | while (n > i && (src[n - 1] == ' ' || src[n - 1] == '\t' || |
| 178 | src[n - 1] == '\r' || src[n - 1] == '\n')) n--; |
| 179 | k = n - i; |
| 180 | if (k >= osz) k = osz - 1; |
| 181 | /* callers trim a buffer in place, so the move may overlap */ |
| 182 | if (k) memmove(out, src + i, k); |
| 183 | out[k] = '\0'; |
| 184 | } |
| 185 | |
| 186 | static int ci_contains(const char *hay, const char *needle) |
| 187 | { |
| 188 | size_t nl; |
| 189 | if (!hay || !needle || !*needle) return 1; |
| 190 | nl = strlen(needle); |
| 191 | for (; *hay; hay++) { |
| 192 | size_t i = 0; |
| 193 | while (i < nl && hay[i] && |
| 194 | tolower((unsigned char)hay[i]) == tolower((unsigned char)needle[i])) i++; |
| 195 | if (i == nl) return 1; |
| 196 | } |
| 197 | return 0; |
| 198 | } |
| 199 | |
| 200 | /* Case-insensitive substring test used for severity heuristics. */ |
| 201 | static int has_word(const char *s, const char *w) |
| 202 | { |
| 203 | return ci_contains(s, w); |
| 204 | } |
| 205 | |
| 206 | static int severity_of(const char *text, const char *level) |
| 207 | { |
| 208 | if (level && *level) { |
| 209 | if (has_word(level, "err") || has_word(level, "crit") || |
| 210 | has_word(level, "alert") || has_word(level, "emerg")) |
| 211 | return SEV_ERR; |
| 212 | if (has_word(level, "warn")) return SEV_WARN; |
| 213 | } |
| 214 | if (!text) return SEV_INFO; |
| 215 | if (has_word(text, "panic") || has_word(text, "fatal") || |
| 216 | has_word(text, "critical") || has_word(text, "segfault") || |
| 217 | has_word(text, "traceback") || has_word(text, "error") || |
| 218 | has_word(text, "err:") || has_word(text, "failed") || |
| 219 | has_word(text, "failure") || has_word(text, "denied")) |
| 220 | return SEV_ERR; |
| 221 | if (has_word(text, "warn") || has_word(text, "deprecated") || |
| 222 | has_word(text, "timeout") || has_word(text, "retry")) |
| 223 | return SEV_WARN; |
| 224 | return SEV_INFO; |
| 225 | } |
| 226 | |
| 227 | static const char *sev_name(int sev) |
| 228 | { |
| 229 | return sev == SEV_ERR ? "err" : sev == SEV_WARN ? "warn" : "info"; |
| 230 | } |
| 231 | |
| 232 | /* ------------------------------------------------------------------ */ |
| 233 | /* Node authentication */ |
| 234 | /* ------------------------------------------------------------------ */ |
| 235 | |
| 236 | /* |
| 237 | * The node API on the node's api port is reachable from the LAN. Every request |
| 238 | * except --meta discovery must prove it knows the node password. Accepted |
| 239 | * forms match the rest of the node API: X-Bot-Password (what the web front |
| 240 | * proxies with), Authorization: Bearer, and ?pwd= (what the plugin iframe |
| 241 | * appends). When BOT_PASSWORD is unset the plugin is a deliberate no-op, which |
| 242 | * is how a developer runs it locally from a shell. |
| 243 | */ |
| 244 | static void require_node_auth(void) |
| 245 | { |
| 246 | const char *np = getenv("BOT_PASSWORD"); |
| 247 | const char *xp; |
| 248 | const char *auth; |
| 249 | char qpwd[256]; |
| 250 | const char *qs; |
| 251 | |
| 252 | if (!np || !*np) return; |
| 253 | |
| 254 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 255 | if (xp && strcmp(xp, np) == 0) return; |
| 256 | |
| 257 | auth = getenv("HTTP_AUTHORIZATION"); |
| 258 | if (auth) { |
| 259 | while (*auth == ' ') auth++; |
| 260 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 261 | auth += 7; |
| 262 | while (*auth == ' ') auth++; |
| 263 | if (strcmp(auth, np) == 0) return; |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | qs = getenv("QUERY_STRING"); |
| 268 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 269 | return; |
| 270 | |
| 271 | fputs("Status: 401 Unauthorized\r\n" |
| 272 | "Content-Type: application/json; charset=utf-8\r\n" |
| 273 | "Cache-Control: no-store\r\n" |
| 274 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 275 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 276 | exit(0); |
| 277 | } |
| 278 | |
| 279 | /* ------------------------------------------------------------------ */ |
| 280 | /* Source registry */ |
| 281 | /* ------------------------------------------------------------------ */ |
| 282 | |
| 283 | typedef struct { |
| 284 | char id[600]; /* journal | journal:<unit> | file:<path> | event:<log> */ |
| 285 | char label[96]; |
| 286 | char kind[10]; /* journal | file | event */ |
| 287 | long long size; |
| 288 | long mtime; |
| 289 | } src_t; |
| 290 | |
| 291 | typedef struct { |
| 292 | int journal_avail; |
| 293 | src_t items[MAX_SRC]; |
| 294 | int n; |
| 295 | int truncated; |
| 296 | } srcs_t; |
| 297 | |
| 298 | static void add_src(srcs_t *o, const char *id, const char *label, |
| 299 | const char *kind, long long size, long mtime) |
| 300 | { |
| 301 | int i; |
| 302 | if (o->n >= MAX_SRC) { o->truncated = 1; return; } |
| 303 | for (i = 0; i < o->n; i++) |
| 304 | if (strcmp(o->items[i].id, id) == 0) return; |
| 305 | snprintf(o->items[o->n].id, sizeof(o->items[0].id), "%s", id); |
| 306 | snprintf(o->items[o->n].label, sizeof(o->items[0].label), "%s", label); |
| 307 | snprintf(o->items[o->n].kind, sizeof(o->items[0].kind), "%s", kind); |
| 308 | o->items[o->n].size = size; |
| 309 | o->items[o->n].mtime = mtime; |
| 310 | o->n++; |
| 311 | } |
| 312 | |
| 313 | static const char *base_name(const char *path) |
| 314 | { |
| 315 | const char *s = path; |
| 316 | const char *b = path; |
| 317 | for (; *s; s++) |
| 318 | if (*s == '/' || *s == '\\') b = s + 1; |
| 319 | return b; |
| 320 | } |
| 321 | |
| 322 | #if !defined(_WIN32) |
| 323 | |
| 324 | static int has_log_suffix(const char *name) |
| 325 | { |
| 326 | size_t l = strlen(name); |
| 327 | return l > 4 && strcmp(name + l - 4, ".log") == 0; |
| 328 | } |
| 329 | |
| 330 | static void add_file_src(srcs_t *o, const char *path) |
| 331 | { |
| 332 | struct stat st; |
| 333 | char id[600]; |
| 334 | if (o->n >= MAX_SRC) { o->truncated = 1; return; } |
| 335 | if (stat(path, &st) != 0) return; |
| 336 | if (!S_ISREG(st.st_mode)) return; |
| 337 | if (st.st_size <= 0) return; |
| 338 | if (strlen(path) + 6 >= sizeof(id)) return; |
| 339 | snprintf(id, sizeof(id), "file:%s", path); |
| 340 | add_src(o, id, base_name(path), "file", (long long)st.st_size, (long)st.st_mtime); |
| 341 | } |
| 342 | |
| 343 | /* |
| 344 | * Bounded walk of one allowlisted root. Each root carries its own entry |
| 345 | * budget so a large /workspace can never consume the allowance that |
| 346 | * $HOME/.scorpiox needs. Symlinks are never followed. |
| 347 | */ |
| 348 | static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) |
| 349 | { |
| 350 | DIR *d; |
| 351 | struct dirent *e; |
| 352 | char p[1024]; |
| 353 | |
| 354 | if (depth < 0 || *budget <= 0 || !dir || !*dir) return; |
| 355 | d = opendir(dir); |
| 356 | if (!d) return; |
| 357 | |
| 358 | while ((e = readdir(d)) != NULL) { |
| 359 | struct stat st; |
| 360 | if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue; |
| 361 | if (--(*budget) <= 0) { o->truncated = 1; break; } |
| 362 | if (strlen(dir) + strlen(e->d_name) + 2 >= sizeof(p)) continue; |
| 363 | snprintf(p, sizeof(p), "%s/%s", dir, e->d_name); |
| 364 | if (lstat(p, &st) != 0) continue; |
| 365 | if (S_ISLNK(st.st_mode)) continue; |
| 366 | if (S_ISDIR(st.st_mode)) { |
| 367 | if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); |
| 368 | } else if (S_ISREG(st.st_mode)) { |
| 369 | if (!log_only || has_log_suffix(e->d_name)) add_file_src(o, p); |
| 370 | } |
| 371 | } |
| 372 | closedir(d); |
| 373 | } |
| 374 | |
| 375 | /* |
| 376 | * "journalctl exists" is not the same as "this node has a journal". Debian |
| 377 | * slim containers ship the binary with no journald running underneath, so the |
| 378 | * UI would offer a source that silently returns nothing. Require the binary |
| 379 | * AND one of the two journal directories systemd actually writes. |
| 380 | */ |
| 381 | static int journal_available(void) |
| 382 | { |
| 383 | static const char *bins[] = { |
| 384 | "/usr/bin/journalctl", "/bin/journalctl", |
| 385 | "/usr/local/bin/journalctl", "/usr/sbin/journalctl", NULL |
| 386 | }; |
| 387 | static const char *dirs[] = { |
| 388 | "/run/systemd/journal", "/run/log/journal", "/var/log/journal", NULL |
| 389 | }; |
| 390 | int i, have_bin = 0, have_dir = 0; |
| 391 | |
| 392 | for (i = 0; bins[i]; i++) |
| 393 | if (access(bins[i], X_OK) == 0) { have_bin = 1; break; } |
| 394 | if (!have_bin) return 0; |
| 395 | for (i = 0; dirs[i]; i++) |
| 396 | if (access(dirs[i], F_OK) == 0) { have_dir = 1; break; } |
| 397 | return have_dir; |
| 398 | } |
| 399 | |
| 400 | static void scan_sources(srcs_t *o) |
| 401 | { |
| 402 | int budget; |
| 403 | char home[512]; |
| 404 | char p[1024]; |
| 405 | |
| 406 | memset(o, 0, sizeof(*o)); |
| 407 | |
| 408 | #if defined(_WIN32) |
| 409 | o->journal_avail = 0; /* Windows exposes the event log instead */ |
| 410 | #else |
| 411 | o->journal_avail = journal_available(); |
| 412 | # if defined(__APPLE__) |
| 413 | /* `log` is part of the base system and needs no daemon probe */ |
| 414 | o->journal_avail = 1; |
| 415 | # endif |
| 416 | #endif |
| 417 | |
| 418 | if (o->journal_avail) |
| 419 | add_src(o, "journal", |
| 420 | # if defined(__APPLE__) |
| 421 | "Unified log", |
| 422 | # else |
| 423 | "System journal", |
| 424 | # endif |
| 425 | "journal", 0LL, 0L); |
| 426 | |
| 427 | #if defined(__APPLE__) |
| 428 | /* the per-file *.log scan plus the classic system.log */ |
| 429 | budget = 8000; |
| 430 | scan_root(o, "/var/log", 0, &budget, 1); |
| 431 | add_file_src(o, "/var/log/system.log"); |
| 432 | |
| 433 | home[0] = '\0'; |
| 434 | if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); |
| 435 | if (home[0]) { |
| 436 | snprintf(p, sizeof(p), "%s/Library/Logs", home); |
| 437 | budget = 8000; |
| 438 | scan_root(o, p, 3, &budget, 1); |
| 439 | } |
| 440 | #else |
| 441 | /* the per-file *.log scan plus the distro-specific aggregate files */ |
| 442 | budget = 12000; |
| 443 | scan_root(o, "/var/log", 0, &budget, 1); |
| 444 | add_file_src(o, "/var/log/syslog"); |
| 445 | add_file_src(o, "/var/log/messages"); |
| 446 | add_file_src(o, "/var/log/kern.log"); |
| 447 | add_file_src(o, "/var/log/auth.log"); |
| 448 | |
| 449 | home[0] = '\0'; |
| 450 | if (getenv("HOME")) snprintf(home, sizeof(home), "%s", getenv("HOME")); |
| 451 | if (home[0]) { |
| 452 | snprintf(p, sizeof(p), "%s/.scorpiox", home); |
| 453 | budget = ROOT_BUDGET; |
| 454 | scan_root(o, p, 4, &budget, 1); |
| 455 | } |
| 456 | budget = ROOT_BUDGET; |
| 457 | scan_root(o, "/workspace", 4, &budget, 1); |
| 458 | #endif |
| 459 | |
| 460 | /* |
| 461 | * Test-only knob: one extra allowlisted root so tests/run.sh can point the |
| 462 | * plugin at fixture logs without inventing a path that production would |
| 463 | * never serve. Only the operator who starts the process can set it. |
| 464 | */ |
| 465 | { |
| 466 | const char *extra = getenv("SX_LOGS_EXTRA_ROOT"); |
| 467 | if (extra && *extra) { |
| 468 | budget = 4000; |
| 469 | scan_root(o, extra, 2, &budget, 1); |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | #else /* _WIN32 */ |
| 475 | |
| 476 | static int has_log_suffix(const char *name) |
| 477 | { |
| 478 | size_t l = strlen(name); |
| 479 | return l > 4 && strcmp(name + l - 4, ".log") == 0; |
| 480 | } |
| 481 | |
| 482 | static void add_file_src(srcs_t *o, const char *path) |
| 483 | { |
| 484 | DWORD a = GetFileAttributesA(path); |
| 485 | WIN32_FILE_ATTRIBUTE_DATA fad; |
| 486 | char id[600]; |
| 487 | if (o->n >= MAX_SRC) { o->truncated = 1; return; } |
| 488 | if (a == INVALID_FILE_ATTRIBUTES) return; |
| 489 | if (a & FILE_ATTRIBUTE_DIRECTORY) return; |
| 490 | if (strlen(path) + 6 >= sizeof(id)) return; |
| 491 | if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return; |
| 492 | snprintf(id, sizeof(id), "file:%s", path); |
| 493 | add_src(o, id, base_name(path), "file", |
| 494 | (long long)fad.nFileSizeLow, 0L); |
| 495 | } |
| 496 | |
| 497 | static void scan_root(srcs_t *o, const char *dir, int depth, int *budget, int log_only) |
| 498 | { |
| 499 | WIN32_FIND_DATAA fd; |
| 500 | HANDLE h; |
| 501 | char pat[1024]; |
| 502 | char p[1024]; |
| 503 | |
| 504 | if (depth < 0 || *budget <= 0 || !dir || !*dir) return; |
| 505 | if (strlen(dir) + 3 >= sizeof(pat)) return; |
| 506 | snprintf(pat, sizeof(pat), "%s\\*", dir); |
| 507 | h = FindFirstFileA(pat, &fd); |
| 508 | if (h == INVALID_HANDLE_VALUE) return; |
| 509 | |
| 510 | do { |
| 511 | if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue; |
| 512 | if (--(*budget) <= 0) { o->truncated = 1; break; } |
| 513 | if (strlen(dir) + strlen(fd.cFileName) + 2 >= sizeof(p)) continue; |
| 514 | snprintf(p, sizeof(p), "%s\\%s", dir, fd.cFileName); |
| 515 | if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { |
| 516 | if (depth > 0) scan_root(o, p, depth - 1, budget, log_only); |
| 517 | } else if (!log_only || has_log_suffix(fd.cFileName)) { |
| 518 | add_file_src(o, p); |
| 519 | } |
| 520 | } while (FindNextFileA(h, &fd)); |
| 521 | FindClose(h); |
| 522 | } |
| 523 | |
| 524 | static void scan_sources(srcs_t *o) |
| 525 | { |
| 526 | int budget = ROOT_BUDGET; |
| 527 | char p[1024]; |
| 528 | const char *lad = getenv("LOCALAPPDATA"); |
| 529 | |
| 530 | memset(o, 0, sizeof(*o)); |
| 531 | o->journal_avail = 0; /* Windows uses the event log instead */ |
| 532 | |
| 533 | /* The two archives the plugin exposes on Windows. */ |
| 534 | add_src(o, "event:System", "Windows System log", "event", 0LL, 0L); |
| 535 | add_src(o, "event:Application", "Windows Application log", "event", 0LL, 0L); |
| 536 | |
| 537 | if (lad && *lad) { |
| 538 | snprintf(p, sizeof(p), "%s\\scorpiox", lad); |
| 539 | scan_root(o, p, 4, &budget, 1); |
| 540 | } |
| 541 | if (getenv("USERPROFILE")) { |
| 542 | snprintf(p, sizeof(p), "%s\\AppData\\Local\\scorpiox", getenv("USERPROFILE")); |
| 543 | scan_root(o, p, 4, &budget, 1); |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | #endif |
| 548 | |
| 549 | /* Resolve a src id to an allowlisted entry. Returns NULL if not in the list. */ |
| 550 | static const src_t *find_src(const srcs_t *o, const char *id) |
| 551 | { |
| 552 | int i; |
| 553 | if (!id || !*id) return NULL; |
| 554 | for (i = 0; i < o->n; i++) |
| 555 | if (strcmp(o->items[i].id, id) == 0) return &o->items[i]; |
| 556 | return NULL; |
| 557 | } |
| 558 | |
| 559 | /* ------------------------------------------------------------------ */ |
| 560 | /* Entry lists */ |
| 561 | /* ------------------------------------------------------------------ */ |
| 562 | |
| 563 | typedef struct { |
| 564 | char ts[ENTRY_TS]; |
| 565 | char unit[ENTRY_UNIT]; |
| 566 | int sev; |
| 567 | char text[ENTRY_TEXT]; |
| 568 | } entry_t; |
| 569 | |
| 570 | typedef struct { |
| 571 | entry_t *v; |
| 572 | int cap; |
| 573 | int n; |
| 574 | int start; |
| 575 | } ring_t; |
| 576 | |
| 577 | static int ring_init(ring_t *r, int cap) |
| 578 | { |
| 579 | if (cap < 1) cap = 1; |
| 580 | r->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); |
| 581 | if (!r->v) return 0; |
| 582 | r->cap = cap; |
| 583 | r->n = 0; |
| 584 | r->start = 0; |
| 585 | return 1; |
| 586 | } |
| 587 | |
| 588 | static void ring_add(ring_t *r, const entry_t *e) |
| 589 | { |
| 590 | if (r->n < r->cap) { |
| 591 | r->v[(r->start + r->n) % r->cap] = *e; |
| 592 | r->n++; |
| 593 | } else { |
| 594 | r->v[r->start] = *e; |
| 595 | r->start = (r->start + 1) % r->cap; |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | static entry_t *ring_at(ring_t *r, int i) |
| 600 | { |
| 601 | return &r->v[(r->start + i) % r->cap]; |
| 602 | } |
| 603 | |
| 604 | static void ring_free(ring_t *r) |
| 605 | { |
| 606 | free(r->v); |
| 607 | r->v = NULL; |
| 608 | } |
| 609 | |
| 610 | typedef struct { |
| 611 | entry_t *v; |
| 612 | int cap; |
| 613 | int n; |
| 614 | } list_t; |
| 615 | |
| 616 | static int list_init(list_t *l, int cap) |
| 617 | { |
| 618 | if (cap < 1) cap = 1; |
| 619 | l->v = (entry_t *)calloc((size_t)cap, sizeof(entry_t)); |
| 620 | if (!l->v) return 0; |
| 621 | l->cap = cap; |
| 622 | l->n = 0; |
| 623 | return 1; |
| 624 | } |
| 625 | |
| 626 | static void list_free(list_t *l) |
| 627 | { |
| 628 | free(l->v); |
| 629 | l->v = NULL; |
| 630 | } |
| 631 | |
| 632 | /* ------------------------------------------------------------------ */ |
| 633 | /* Command execution (fixed argv only) */ |
| 634 | /* ------------------------------------------------------------------ */ |
| 635 | |
| 636 | static FILE *run_cmd(const char *cmd) |
| 637 | { |
| 638 | #if defined(_WIN32) |
| 639 | return _popen(cmd, "r"); |
| 640 | #else |
| 641 | return popen(cmd, "r"); |
| 642 | #endif |
| 643 | } |
| 644 | |
| 645 | static int close_cmd(FILE *f) |
| 646 | { |
| 647 | #if defined(_WIN32) |
| 648 | return _pclose(f); |
| 649 | #else |
| 650 | return pclose(f); |
| 651 | #endif |
| 652 | } |
| 653 | |
| 654 | /* Validate a systemd unit name before it can reach the fixed argv. */ |
| 655 | static int valid_unit(const char *u) |
| 656 | { |
| 657 | size_t i, l; |
| 658 | if (!u || !*u) return 0; |
| 659 | l = strlen(u); |
| 660 | if (l > 128) return 0; |
| 661 | for (i = 0; i < l; i++) { |
| 662 | unsigned char c = (unsigned char)u[i]; |
| 663 | if (!(isalnum(c) || c == '@' || c == '.' || c == '_' || c == '-')) |
| 664 | return 0; |
| 665 | } |
| 666 | /* a leading '-' would read as an option to journalctl */ |
| 667 | return u[0] != '-'; |
| 668 | } |
| 669 | |
| 670 | /* ------------------------------------------------------------------ */ |
| 671 | /* Journal parsing (journalctl -o json, one object per line) */ |
| 672 | /* ------------------------------------------------------------------ */ |
| 673 | |
| 674 | /* |
| 675 | * Extract one top-level key's value from a single journal JSON object line. |
| 676 | * Handles string values with backslash escapes, numeric values, and String |
| 677 | * arrays (journal stores binary or multi-line MESSAGE fields as arrays, which |
| 678 | * this plugin renders as a placeholder rather than pretending to decode). |
| 679 | */ |
| 680 | static int jget(const char *line, const char *key, char *out, size_t osz) |
| 681 | { |
| 682 | char pat[128]; |
| 683 | const char *p; |
| 684 | |
| 685 | if (osz) out[0] = '\0'; |
| 686 | if (!line || !key || !*key) return 0; |
| 687 | /* the search key is a fixed literal from this file, never user input */ |
| 688 | snprintf(pat, sizeof(pat), "\"%s\"", key); |
| 689 | |
| 690 | for (p = line; (p = strstr(p, pat)) != NULL; p += strlen(pat)) { |
| 691 | const char *q = p + strlen(pat); |
| 692 | while (*q == ' ' || *q == '\t') q++; |
| 693 | if (*q != ':') continue; /* a value that happens to match */ |
| 694 | q++; |
| 695 | while (*q == ' ' || *q == '\t') q++; |
| 696 | |
| 697 | if (*q == '"') { |
| 698 | size_t o = 0; |
| 699 | q++; |
| 700 | while (*q && *q != '"') { |
| 701 | char c = *q; |
| 702 | if (c == '\\' && q[1]) { |
| 703 | q++; |
| 704 | switch (*q) { |
| 705 | case 'n': c = '\n'; break; |
| 706 | case 'r': c = '\r'; break; |
| 707 | case 't': c = '\t'; break; |
| 708 | case '"': c = '"'; break; |
| 709 | case '\\': c = '\\'; break; |
| 710 | case '/': c = '/'; break; |
| 711 | default: c = *q; break; |
| 712 | } |
| 713 | } |
| 714 | if (o + 1 < osz) out[o++] = c; |
| 715 | q++; |
| 716 | } |
| 717 | out[o] = '\0'; |
| 718 | return 1; |
| 719 | } |
| 720 | if (*q == '[') { |
| 721 | /* journal stores binary or multi-line fields as byte arrays */ |
| 722 | snprintf(out, osz, "(binary)"); |
| 723 | return 1; |
| 724 | } |
| 725 | { |
| 726 | size_t o = 0; |
| 727 | while (*q && *q != ',' && *q != '}') { |
| 728 | if (o + 1 < osz) out[o++] = *q; |
| 729 | q++; |
| 730 | } |
| 731 | out[o] = '\0'; |
| 732 | return 1; |
| 733 | } |
| 734 | } |
| 735 | return 0; |
| 736 | } |
| 737 | |
| 738 | static void fmt_journal_ts(const char *us, char *out, size_t osz) |
| 739 | { |
| 740 | long long v; |
| 741 | time_t secs; |
| 742 | struct tm tmv; |
| 743 | if (!us || !*us) { snprintf(out, osz, "-"); return; } |
| 744 | v = atoll(us); |
| 745 | if (v <= 0) { snprintf(out, osz, "-"); return; } |
| 746 | secs = (time_t)(v / 1000000LL); |
| 747 | if (!localtime_r(&secs, &tmv)) { snprintf(out, osz, "-"); return; } |
| 748 | strftime(out, osz, "%m-%d %H:%M:%S", &tmv); |
| 749 | } |
| 750 | |
| 751 | /* |
| 752 | * Stream journalctl into `sink`. `filter` (optional) keeps only lines whose |
| 753 | * text, unit or timestamp matches case-insensitively. Returns the number of |
| 754 | * lines scanned, or -1 when journalctl could not be run. |
| 755 | */ |
| 756 | typedef void (*entry_sink)(void *ctx, const entry_t *e); |
| 757 | |
| 758 | static int stream_journal(const char *unit, int nlines, const char *filter, |
| 759 | entry_sink sink, void *ctx) |
| 760 | { |
| 761 | #if defined(_WIN32) |
| 762 | (void)unit; (void)nlines; (void)filter; (void)sink; (void)ctx; |
| 763 | return -1; |
| 764 | #else |
| 765 | char cmd[512]; |
| 766 | FILE *f; |
| 767 | char line[8192]; |
| 768 | int scanned = 0; |
| 769 | int uok = unit && *unit && valid_unit(unit); |
| 770 | const char *fixture = getenv("SX_LOGS_JOURNAL_FIXTURE"); |
| 771 | |
| 772 | if (unit && *unit && !uok) return -1; |
| 773 | if (nlines < 1) nlines = 1; |
| 774 | if (nlines > TAIL_MAX) nlines = TAIL_MAX; |
| 775 | |
| 776 | if (uok) |
| 777 | snprintf(cmd, sizeof(cmd), |
| 778 | "journalctl -o json --no-pager -n %d -u %s 2>/dev/null", nlines, unit); |
| 779 | else |
| 780 | snprintf(cmd, sizeof(cmd), |
| 781 | "journalctl -o json --no-pager -n %d 2>/dev/null", nlines); |
| 782 | |
| 783 | /* test-only: replay a captured journalctl -o json stream */ |
| 784 | if (fixture && *fixture) f = fopen(fixture, "r"); |
| 785 | else f = run_cmd(cmd); |
| 786 | if (!f) return -1; |
| 787 | |
| 788 | while (fgets(line, sizeof(line), f)) { |
| 789 | entry_t e; |
| 790 | char msg[ENTRY_TEXT] = ""; |
| 791 | char pri[8] = ""; |
| 792 | char tsus[32] = ""; |
| 793 | char un[ENTRY_UNIT] = ""; |
| 794 | int prio; |
| 795 | |
| 796 | if (line[0] != '{') continue; |
| 797 | scanned++; |
| 798 | jget(line, "MESSAGE", msg, sizeof(msg)); |
| 799 | jget(line, "PRIORITY", pri, sizeof(pri)); |
| 800 | jget(line, "__REALTIME_TIMESTAMP", tsus, sizeof(tsus)); |
| 801 | if (!jget(line, "_SYSTEMD_UNIT", un, sizeof(un))) |
| 802 | jget(line, "SYSLOG_IDENTIFIER", un, sizeof(un)); |
| 803 | |
| 804 | memset(&e, 0, sizeof(e)); |
| 805 | fmt_journal_ts(tsus, e.ts, sizeof(e.ts)); |
| 806 | snprintf(e.unit, sizeof(e.unit), "%s", un); |
| 807 | prio = pri[0] ? atoi(pri) : 6; |
| 808 | e.sev = prio <= 3 ? SEV_ERR : prio == 4 ? SEV_WARN : SEV_INFO; |
| 809 | snprintf(e.text, sizeof(e.text), "%s", msg); |
| 810 | if (e.sev == SEV_INFO) e.sev = severity_of(e.text, NULL); |
| 811 | |
| 812 | if (filter && *filter && !ci_contains(e.text, filter) && |
| 813 | !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) |
| 814 | continue; |
| 815 | sink(ctx, &e); |
| 816 | } |
| 817 | if (fixture && *fixture) fclose(f); |
| 818 | else close_cmd(f); |
| 819 | return scanned; |
| 820 | #endif |
| 821 | } |
| 822 | |
| 823 | /* ------------------------------------------------------------------ */ |
| 824 | /* Plain log-file reading */ |
| 825 | /* ------------------------------------------------------------------ */ |
| 826 | |
| 827 | /* |
| 828 | * Works out the byte offset to start reading from so only the last `maxbytes` |
| 829 | * of a file are considered. Logs grow to gigabytes; a viewer must never read |
| 830 | * one in full. |
| 831 | */ |
| 832 | static long tail_offset(long long size, long maxbytes) |
| 833 | { |
| 834 | if (size <= maxbytes) return 0; |
| 835 | return (long)(size - maxbytes); |
| 836 | } |
| 837 | |
| 838 | #if !defined(_WIN32) |
| 839 | static int open_log(const char *path, FILE **out, long long *size_out) |
| 840 | { |
| 841 | struct stat st; |
| 842 | if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) return -1; |
| 843 | *out = fopen(path, "rb"); |
| 844 | if (!*out) return -1; |
| 845 | *size_out = (long long)st.st_size; |
| 846 | return 0; |
| 847 | } |
| 848 | #else |
| 849 | static int open_log(const char *path, FILE **out, long long *size_out) |
| 850 | { |
| 851 | WIN32_FILE_ATTRIBUTE_DATA fad; |
| 852 | if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) return -1; |
| 853 | if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return -1; |
| 854 | *out = fopen(path, "rb"); |
| 855 | if (!*out) return -1; |
| 856 | *size_out = (long long)fad.nFileSizeLow; |
| 857 | return 0; |
| 858 | } |
| 859 | #endif |
| 860 | |
| 861 | /* Fill one entry from a raw log line. Detects the two timestamp layouts that |
| 862 | * nearly every text log uses, and falls back to no timestamp. */ |
| 863 | static void entry_from_line(entry_t *e, const char *line, size_t n) |
| 864 | { |
| 865 | char buf[ENTRY_TEXT * 2]; |
| 866 | |
| 867 | memset(e, 0, sizeof(*e)); |
| 868 | if (n >= sizeof(buf)) n = sizeof(buf) - 1; |
| 869 | memcpy(buf, line, n); |
| 870 | buf[n] = '\0'; |
| 871 | while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; |
| 872 | |
| 873 | /* syslog: "Nov 12 06:30:01 host unit[pid]: message" */ |
| 874 | if (n > 16 && isalpha((unsigned char)buf[0]) && buf[3] == ' ' && |
| 875 | isdigit((unsigned char)buf[4]) && buf[6] == ' ' && buf[9] == ':') { |
| 876 | snprintf(e->ts, sizeof(e->ts), "%.15s", buf); |
| 877 | /* everything after "host " is the text, unit if it looks like one */ |
| 878 | { |
| 879 | const char *p = buf + 16; |
| 880 | const char *colon; |
| 881 | while (*p && *p != ' ') p++; |
| 882 | while (*p == ' ') p++; |
| 883 | colon = strchr(p, ':'); |
| 884 | if (colon && (size_t)(colon - p) < sizeof(e->unit) && |
| 885 | (size_t)(colon - p) < 64) { |
| 886 | snprintf(e->unit, sizeof(e->unit), "%.*s", (int)(colon - p), p); |
| 887 | snprintf(e->text, sizeof(e->text), "%s", colon + 1); |
| 888 | } else { |
| 889 | snprintf(e->text, sizeof(e->text), "%.*s", |
| 890 | (int)(sizeof(e->text) - 1), p); |
| 891 | } |
| 892 | trim_into(e->text, sizeof(e->text), e->text, strlen(e->text)); |
| 893 | e->sev = severity_of(e->text, NULL); |
| 894 | return; |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | /* ISO-8601 prefix: "2026-11-12T06:30:01Z rest" or "2026-11-12 06:30:01 rest" */ |
| 899 | if (n > 20 && isdigit((unsigned char)buf[0]) && buf[4] == '-' && buf[7] == '-' && |
| 900 | (buf[10] == 'T' || buf[10] == ' ')) { |
| 901 | size_t cut = 11; |
| 902 | while (cut < n && cut < 32 && buf[cut] != ' ' && buf[cut] != '\t') cut++; |
| 903 | snprintf(e->ts, sizeof(e->ts), "%.*s", (int)(cut < 24 ? cut : 24), buf); |
| 904 | { |
| 905 | const char *p = buf + cut; |
| 906 | while (*p == ' ' || *p == '\t') p++; |
| 907 | snprintf(e->text, sizeof(e->text), "%.*s", |
| 908 | (int)(sizeof(e->text) - 1), p); |
| 909 | } |
| 910 | e->sev = severity_of(e->text, NULL); |
| 911 | return; |
| 912 | } |
| 913 | |
| 914 | snprintf(e->text, sizeof(e->text), "%.*s", |
| 915 | (int)(sizeof(e->text) - 1), buf); |
| 916 | e->sev = severity_of(e->text, NULL); |
| 917 | } |
| 918 | |
| 919 | typedef struct { |
| 920 | ring_t *ring; |
| 921 | list_t *hits; |
| 922 | const char *filter; |
| 923 | int seen; |
| 924 | int cap; |
| 925 | } file_ctx_t; |
| 926 | |
| 927 | static void file_sink(void *vctx, const entry_t *e) |
| 928 | { |
| 929 | file_ctx_t *c = (file_ctx_t *)vctx; |
| 930 | if (c->ring) ring_add(c->ring, e); |
| 931 | if (c->hits) { |
| 932 | if (c->hits->n < c->cap) c->hits->v[c->hits->n++] = *e; |
| 933 | } |
| 934 | c->seen++; |
| 935 | } |
| 936 | |
| 937 | /* |
| 938 | * Read the tail of a log file. `ring` keeps the last N entries (tail mode); |
| 939 | * `hits` collects up to `cap` matching entries (search mode). Exactly one of |
| 940 | * them is non-NULL. |
| 941 | */ |
| 942 | static int read_log_file(const char *path, int nlines, const char *filter, |
| 943 | ring_t *ring, list_t *hits, int hitcap) |
| 944 | { |
| 945 | FILE *f = NULL; |
| 946 | long long size = 0; |
| 947 | long off; |
| 948 | char line[ENTRY_TEXT * 2]; |
| 949 | file_ctx_t ctx; |
| 950 | |
| 951 | (void)nlines; /* the ring/hit list owns the cap; this is only a hint */ |
| 952 | if (open_log(path, &f, &size) != 0) return -1; |
| 953 | |
| 954 | memset(&ctx, 0, sizeof(ctx)); |
| 955 | ctx.ring = ring; |
| 956 | ctx.hits = hits; |
| 957 | ctx.filter = filter; |
| 958 | ctx.cap = hitcap; |
| 959 | |
| 960 | off = tail_offset(size, FILE_TAIL_BYTES); |
| 961 | if (off > 0 && fseek(f, off, SEEK_SET) != 0) { |
| 962 | fclose(f); |
| 963 | return -1; |
| 964 | } |
| 965 | |
| 966 | while (fgets(line, sizeof(line), f)) { |
| 967 | entry_t e; |
| 968 | size_t n = strlen(line); |
| 969 | /* The first line after a tail seek is a partial line; drop it. */ |
| 970 | if (off > 0 && ctx.seen == 0 && n > 0 && line[n - 1] != '\n') { |
| 971 | ctx.seen = 0; |
| 972 | /* still consume it so we do not emit a broken record */ |
| 973 | continue; |
| 974 | } |
| 975 | if (hits && ctx.seen >= SEARCH_SCAN) break; |
| 976 | entry_from_line(&e, line, n); |
| 977 | if (filter && *filter && !ci_contains(e.text, filter) && |
| 978 | !ci_contains(e.unit, filter) && !ci_contains(e.ts, filter)) |
| 979 | { ctx.seen++; continue; } |
| 980 | file_sink(&ctx, &e); |
| 981 | } |
| 982 | fclose(f); |
| 983 | return ctx.seen; |
| 984 | } |
| 985 | |
| 986 | /* ------------------------------------------------------------------ */ |
| 987 | /* macOS `log show` reading */ |
| 988 | /* ------------------------------------------------------------------ */ |
| 989 | |
| 990 | #if defined(__APPLE__) |
| 991 | |
| 992 | static int stream_macos_log(int nlines, const char *filter, |
| 993 | entry_sink sink, void *ctx) |
| 994 | { |
| 995 | char cmd[512]; |
| 996 | FILE *f; |
| 997 | char line[8192]; |
| 998 | int scanned = 0; |
| 999 | int mins; |
| 1000 | |
| 1001 | if (nlines < 1) nlines = 1; |
| 1002 | if (nlines > TAIL_MAX) nlines = TAIL_MAX; |
| 1003 | /* bound the time window: roughly one minute of syslog per 200 lines */ |
| 1004 | mins = nlines / 200; |
| 1005 | if (mins < 1) mins = 1; |
| 1006 | if (mins > 60) mins = 60; |
| 1007 | |
| 1008 | /* |
| 1009 | * Absolute path, and it matters: on macOS `log` is also a zsh shell |
| 1010 | * builtin, so a bare `log show` run through a user's shell prints |
| 1011 | * "zsh:log: too many arguments" and exits 0 with no output. popen uses |
| 1012 | * /bin/sh so it is only latent there, but the fixed path removes the |
| 1013 | * class of failure entirely. |
| 1014 | */ |
| 1015 | snprintf(cmd, sizeof(cmd), |
| 1016 | "/usr/bin/log show --style compact --last %dm 2>/dev/null | tail -n %d", |
| 1017 | mins, nlines); |
| 1018 | f = run_cmd(cmd); |
| 1019 | if (!f) return -1; |
| 1020 | while (fgets(line, sizeof(line), f)) { |
| 1021 | entry_t e; |
| 1022 | size_t n = strlen(line); |
| 1023 | if (filter && *filter && !ci_contains(line, filter)) { scanned++; continue; } |
| 1024 | scanned++; |
| 1025 | entry_from_line(&e, line, n); |
| 1026 | sink(ctx, &e); |
| 1027 | } |
| 1028 | close_cmd(f); |
| 1029 | return scanned; |
| 1030 | } |
| 1031 | |
| 1032 | #endif |
| 1033 | |
| 1034 | /* ------------------------------------------------------------------ */ |
| 1035 | /* Windows event log reading */ |
| 1036 | /* ------------------------------------------------------------------ */ |
| 1037 | |
| 1038 | #if defined(_WIN32) |
| 1039 | |
| 1040 | static int stream_event_log(const char *channel, int nlines, const char *filter, |
| 1041 | entry_sink sink, void *ctx) |
| 1042 | { |
| 1043 | char cmd[512]; |
| 1044 | FILE *f; |
| 1045 | char line[8192]; |
| 1046 | int scanned = 0; |
| 1047 | |
| 1048 | if (nlines < 1) nlines = 1; |
| 1049 | if (nlines > TAIL_MAX) nlines = TAIL_MAX; |
| 1050 | if (!channel || !*channel) return -1; |
| 1051 | /* channel is one of two constants chosen by the caller, never user text */ |
| 1052 | if (strcmp(channel, "System") != 0 && strcmp(channel, "Application") != 0) |
| 1053 | return -1; |
| 1054 | |
| 1055 | snprintf(cmd, sizeof(cmd), |
| 1056 | "wevtutil qe %s /c:%d /rd:true /f:text 2>NUL", channel, nlines); |
| 1057 | f = run_cmd(cmd); |
| 1058 | if (!f) return -1; |
| 1059 | |
| 1060 | { |
| 1061 | entry_t e; |
| 1062 | int have = 0; |
| 1063 | memset(&e, 0, sizeof(e)); |
| 1064 | while (fgets(line, sizeof(line), f)) { |
| 1065 | char t[ENTRY_TEXT]; |
| 1066 | trim_into(t, sizeof(t), line, strlen(line)); |
| 1067 | if (!*t) { |
| 1068 | if (have && e.text[0]) { |
| 1069 | e.sev = severity_of(e.text, NULL); |
| 1070 | if (!filter || !*filter || ci_contains(e.text, filter)) |
| 1071 | sink(ctx, &e); |
| 1072 | scanned++; |
| 1073 | } |
| 1074 | memset(&e, 0, sizeof(e)); |
| 1075 | have = 0; |
| 1076 | continue; |
| 1077 | } |
| 1078 | have = 1; |
| 1079 | if (strncmp(t, "Date:", 5) == 0) { |
| 1080 | snprintf(e.ts, sizeof(e.ts), "%s", t + 5); |
| 1081 | trim_into(e.ts, sizeof(e.ts), e.ts, strlen(e.ts)); |
| 1082 | } else if (strncmp(t, "Level:", 6) == 0) { |
| 1083 | const char *lv = t + 6; |
| 1084 | while (*lv == ' ') lv++; |
| 1085 | snprintf(e.unit, sizeof(e.unit), "%s", channel); |
| 1086 | if (ci_contains(lv, "Error") || ci_contains(lv, "Critical")) |
| 1087 | e.sev = SEV_ERR; |
| 1088 | else if (ci_contains(lv, "Warning")) |
| 1089 | e.sev = SEV_WARN; |
| 1090 | } else if (strncmp(t, "Description:", 12) == 0) { |
| 1091 | snprintf(e.text, sizeof(e.text), "%s", t + 12); |
| 1092 | trim_into(e.text, sizeof(e.text), e.text, strlen(e.text)); |
| 1093 | } |
| 1094 | } |
| 1095 | if (have && e.text[0]) { |
| 1096 | e.sev = severity_of(e.text, NULL); |
| 1097 | if (!filter || !*filter || ci_contains(e.text, filter)) |
| 1098 | sink(ctx, &e); |
| 1099 | scanned++; |
| 1100 | } |
| 1101 | } |
| 1102 | close_cmd(f); |
| 1103 | return scanned; |
| 1104 | } |
| 1105 | |
| 1106 | #endif |
| 1107 | |
| 1108 | /* ------------------------------------------------------------------ */ |
| 1109 | /* Units (service providers that have journal entries) */ |
| 1110 | /* ------------------------------------------------------------------ */ |
| 1111 | |
| 1112 | typedef struct { |
| 1113 | char name[ENTRY_UNIT]; |
| 1114 | int entries; |
| 1115 | } unit_t; |
| 1116 | |
| 1117 | static int list_units(unit_t *out, int max) |
| 1118 | { |
| 1119 | #if defined(_WIN32) || defined(__APPLE__) |
| 1120 | (void)out; (void)max; |
| 1121 | return 0; |
| 1122 | #else |
| 1123 | FILE *f; |
| 1124 | char line[1024]; |
| 1125 | int n = 0; |
| 1126 | |
| 1127 | f = run_cmd("journalctl --no-pager -F _SYSTEMD_UNIT 2>/dev/null | head -n 400"); |
| 1128 | if (!f) return 0; |
| 1129 | while (fgets(line, sizeof(line), f) && n < max) { |
| 1130 | char u[ENTRY_UNIT]; |
| 1131 | int i; |
| 1132 | trim_into(u, sizeof(u), line, strlen(line)); |
| 1133 | if (!*u) continue; |
| 1134 | if (!valid_unit(u)) continue; |
| 1135 | for (i = 0; i < n; i++) |
| 1136 | if (strcmp(out[i].name, u) == 0) break; |
| 1137 | if (i < n) continue; |
| 1138 | snprintf(out[n].name, sizeof(out[n].name), "%s", u); |
| 1139 | out[n].entries = 0; |
| 1140 | n++; |
| 1141 | } |
| 1142 | close_cmd(f); |
| 1143 | return n; |
| 1144 | #endif |
| 1145 | } |
| 1146 | |
| 1147 | /* ------------------------------------------------------------------ */ |
| 1148 | /* Collection helpers */ |
| 1149 | /* ------------------------------------------------------------------ */ |
| 1150 | |
| 1151 | typedef struct { |
| 1152 | ring_t *ring; |
| 1153 | } shell_ctx_t; |
| 1154 | |
| 1155 | static void shell_sink(void *vctx, const entry_t *e) |
| 1156 | { |
| 1157 | ring_t *r = ((shell_ctx_t *)vctx)->ring; |
| 1158 | ring_add(r, e); |
| 1159 | } |
| 1160 | |
| 1161 | /* Stream `nlines` entries for a source into `ring` (tail mode). */ |
| 1162 | static int collect_tail(const src_t *s, int nlines, ring_t *ring) |
| 1163 | { |
| 1164 | shell_ctx_t ctx; |
| 1165 | |
| 1166 | ctx.ring = ring; |
| 1167 | /* Platform first: on macOS the "journal" kind is `log show`, not |
| 1168 | * journalctl, and the generic branch below would swallow it. */ |
| 1169 | #if defined(__APPLE__) |
| 1170 | if (strcmp(s->kind, "journal") == 0) |
| 1171 | return stream_macos_log(nlines, NULL, shell_sink, &ctx); |
| 1172 | #elif defined(_WIN32) |
| 1173 | if (strncmp(s->id, "event:", 6) == 0) |
| 1174 | return stream_event_log(s->id + 6, nlines, NULL, shell_sink, &ctx); |
| 1175 | #else |
| 1176 | if (strcmp(s->kind, "journal") == 0) |
| 1177 | return stream_journal(NULL, nlines, NULL, shell_sink, &ctx); |
| 1178 | #endif |
| 1179 | if (strncmp(s->id, "file:", 5) == 0) |
| 1180 | return read_log_file(s->id + 5, nlines, NULL, ring, NULL, 0); |
| 1181 | if (strncmp(s->id, "journal:", 8) == 0) |
| 1182 | return stream_journal(s->id + 8, nlines, NULL, shell_sink, &ctx); |
| 1183 | return -1; |
| 1184 | } |
| 1185 | |
| 1186 | typedef struct { |
| 1187 | list_t *hits; |
| 1188 | } hits_ctx_t; |
| 1189 | |
| 1190 | static void hits_sink(void *vctx, const entry_t *e) |
| 1191 | { |
| 1192 | list_t *l = ((hits_ctx_t *)vctx)->hits; |
| 1193 | if (l->n < l->cap) l->v[l->n++] = *e; |
| 1194 | } |
| 1195 | |
| 1196 | /* Search a source for `filter`. Returns the number of lines scanned. */ |
| 1197 | static int collect_search(const src_t *s, const char *filter, list_t *hits) |
| 1198 | { |
| 1199 | hits_ctx_t ctx; |
| 1200 | |
| 1201 | ctx.hits = hits; |
| 1202 | /* same platform-first order as collect_tail */ |
| 1203 | #if defined(__APPLE__) |
| 1204 | if (strcmp(s->kind, "journal") == 0) |
| 1205 | return stream_macos_log(TAIL_MAX, filter, hits_sink, &ctx); |
| 1206 | #elif defined(_WIN32) |
| 1207 | if (strncmp(s->id, "event:", 6) == 0) |
| 1208 | return stream_event_log(s->id + 6, 600, filter, hits_sink, &ctx); |
| 1209 | #else |
| 1210 | if (strcmp(s->kind, "journal") == 0) |
| 1211 | return stream_journal(NULL, TAIL_MAX, filter, hits_sink, &ctx); |
| 1212 | #endif |
| 1213 | if (strncmp(s->id, "file:", 5) == 0) |
| 1214 | return read_log_file(s->id + 5, TAIL_MAX, filter, NULL, hits, SEARCH_HITS_MAX); |
| 1215 | if (strncmp(s->id, "journal:", 8) == 0) |
| 1216 | return stream_journal(s->id + 8, TAIL_MAX, filter, hits_sink, &ctx); |
| 1217 | return -1; |
| 1218 | } |
| 1219 | |
| 1220 | /* ------------------------------------------------------------------ */ |
| 1221 | /* Modes */ |
| 1222 | /* ------------------------------------------------------------------ */ |
| 1223 | |
| 1224 | static int mode_meta(void) |
| 1225 | { |
| 1226 | puts("{\"name\":\"logs\",\"desc\":\"Log viewer\"}"); |
| 1227 | return 0; |
| 1228 | } |
| 1229 | |
| 1230 | static void json_header(void) |
| 1231 | { |
| 1232 | /* Deliberately no Content-Length - the server owns framing. */ |
| 1233 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 1234 | "Cache-Control: no-store\r\n" |
| 1235 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1236 | } |
| 1237 | |
| 1238 | static int mode_json(const char *qs) |
| 1239 | { |
| 1240 | char action[32]; |
| 1241 | char srcid[600]; |
| 1242 | char linesv[16]; |
| 1243 | char q[256]; |
| 1244 | char utc[40]; |
| 1245 | srcs_t srcs; |
| 1246 | int nlines = 200; |
| 1247 | |
| 1248 | action[0] = srcid[0] = linesv[0] = q[0] = '\0'; |
| 1249 | get_query_val(qs, "action", action, sizeof(action)); |
| 1250 | get_query_val(qs, "src", srcid, sizeof(srcid)); |
| 1251 | get_query_val(qs, "lines", linesv, sizeof(linesv)); |
| 1252 | get_query_val(qs, "q", q, sizeof(q)); |
| 1253 | |
| 1254 | /* anything above the cap is clamped, never silently ignored */ |
| 1255 | if (linesv[0]) { |
| 1256 | int v = atoi(linesv); |
| 1257 | if (v > 0) nlines = v > TAIL_MAX ? TAIL_MAX : v; |
| 1258 | } |
| 1259 | |
| 1260 | if (!action[0] || (strcmp(action, "sources") != 0 && strcmp(action, "tail") != 0 && |
| 1261 | strcmp(action, "search") != 0 && strcmp(action, "units") != 0 && |
| 1262 | strcmp(action, "info") != 0)) { |
| 1263 | json_header(); |
| 1264 | printf("{\"ok\":false,\"error\":\"unknown_action\",\"supported\":" |
| 1265 | "[\"sources\",\"tail\",\"search\",\"units\",\"info\"],\"requested\":"); |
| 1266 | json_str(action); |
| 1267 | fputs("}\n", stdout); |
| 1268 | return 0; |
| 1269 | } |
| 1270 | |
| 1271 | utc_now(utc, sizeof(utc)); |
| 1272 | |
| 1273 | if (strcmp(action, "info") == 0) { |
| 1274 | json_header(); |
| 1275 | fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," |
| 1276 | "\"version\":\"" PLUGIN_VER "\",\"utc\":", stdout); |
| 1277 | json_str(utc); |
| 1278 | printf(",\"platform\":\"%s\"", |
| 1279 | #if defined(_WIN32) |
| 1280 | "windows" |
| 1281 | #elif defined(__APPLE__) |
| 1282 | "macos" |
| 1283 | #else |
| 1284 | "linux" |
| 1285 | #endif |
| 1286 | ); |
| 1287 | fputs(",\"limits\":{\"lines_max\":", stdout); |
| 1288 | printf("%d", TAIL_MAX); |
| 1289 | fputs(",\"search_hits_max\":", stdout); |
| 1290 | printf("%d", SEARCH_HITS_MAX); |
| 1291 | fputs(",\"search_scan_max\":", stdout); |
| 1292 | printf("%d", SEARCH_SCAN); |
| 1293 | fputs("},\"supported\":[\"sources\",\"tail\",\"search\",\"units\",\"info\"]," |
| 1294 | "\"zero_network\":true,\"read_only\":true,\"node_auth\":", stdout); |
| 1295 | { |
| 1296 | const char *np = getenv("BOT_PASSWORD"); |
| 1297 | fputs((np && *np) ? "true" : "false", stdout); |
| 1298 | } |
| 1299 | fputs("}\n", stdout); |
| 1300 | return 0; |
| 1301 | } |
| 1302 | |
| 1303 | scan_sources(&srcs); |
| 1304 | |
| 1305 | if (strcmp(action, "sources") == 0) { |
| 1306 | int i; |
| 1307 | json_header(); |
| 1308 | fputs("{\"ok\":true,\"action\":\"sources\",\"plugin\":\"" PLUGIN_ID "\"," |
| 1309 | "\"utc\":", stdout); |
| 1310 | json_str(utc); |
| 1311 | printf(",\"journal_available\":%s,\"count\":%d,\"truncated\":%s,\"sources\":[", |
| 1312 | srcs.journal_avail ? "true" : "false", srcs.n, |
| 1313 | srcs.truncated ? "true" : "false"); |
| 1314 | for (i = 0; i < srcs.n; i++) { |
| 1315 | if (i) fputc(',', stdout); |
| 1316 | fputs("{\"id\":", stdout); json_str(srcs.items[i].id); |
| 1317 | fputs(",\"label\":", stdout); json_str(srcs.items[i].label); |
| 1318 | fputs(",\"kind\":", stdout); json_str(srcs.items[i].kind); |
| 1319 | printf(",\"size\":%lld,\"mtime\":%ld}", srcs.items[i].size, srcs.items[i].mtime); |
| 1320 | } |
| 1321 | fputs("]}\n", stdout); |
| 1322 | return 0; |
| 1323 | } |
| 1324 | |
| 1325 | if (strcmp(action, "units") == 0) { |
| 1326 | static unit_t units[MAX_UNITS]; |
| 1327 | int n = 0, i; |
| 1328 | #if !defined(_WIN32) && !defined(__APPLE__) |
| 1329 | n = list_units(units, MAX_UNITS); |
| 1330 | #else |
| 1331 | (void)units; |
| 1332 | #endif |
| 1333 | json_header(); |
| 1334 | fputs("{\"ok\":true,\"action\":\"units\",\"available\":", stdout); |
| 1335 | #if !defined(_WIN32) && !defined(__APPLE__) |
| 1336 | fputs("true", stdout); |
| 1337 | #else |
| 1338 | fputs("false", stdout); |
| 1339 | #endif |
| 1340 | printf(",\"count\":%d,\"units\":[", n); |
| 1341 | for (i = 0; i < n; i++) { |
| 1342 | if (i) fputc(',', stdout); |
| 1343 | fputs("{\"name\":", stdout); json_str(units[i].name); |
| 1344 | printf(",\"src\":\"journal:%s\"}", units[i].name); |
| 1345 | } |
| 1346 | fputs("]}\n", stdout); |
| 1347 | return 0; |
| 1348 | } |
| 1349 | |
| 1350 | { |
| 1351 | const src_t *s = find_src(&srcs, srcid); |
| 1352 | char srcbuf[32]; |
| 1353 | |
| 1354 | snprintf(srcbuf, sizeof(srcbuf), "%s", srcid); |
| 1355 | if (!s) { |
| 1356 | json_header(); |
| 1357 | fputs("{\"ok\":false,\"error\":\"source_not_allowed\"," |
| 1358 | "\"message\":\"that path is not in this plugin's read allowlist; " |
| 1359 | "call action=sources for the current list\",\"requested\":", stdout); |
| 1360 | json_str(srcbuf); |
| 1361 | fputs("}\n", stdout); |
| 1362 | return 0; |
| 1363 | } |
| 1364 | if (!*s->kind) { |
| 1365 | json_header(); |
| 1366 | fputs("{\"ok\":false,\"error\":\"source_unavailable\"}\n", stdout); |
| 1367 | return 0; |
| 1368 | } |
| 1369 | |
| 1370 | if (strcmp(action, "tail") == 0) { |
| 1371 | ring_t ring; |
| 1372 | int got; |
| 1373 | int i; |
| 1374 | |
| 1375 | if (!ring_init(&ring, nlines)) { |
| 1376 | json_header(); |
| 1377 | fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); |
| 1378 | return 0; |
| 1379 | } |
| 1380 | got = collect_tail(s, nlines, &ring); |
| 1381 | json_header(); |
| 1382 | if (got < 0) { |
| 1383 | fputs("{\"ok\":false,\"error\":\"unreadable_source\"," |
| 1384 | "\"message\":\"the source could not be read on this node\"," |
| 1385 | "\"src\":", stdout); |
| 1386 | json_str(s->id); |
| 1387 | fputs("}\n", stdout); |
| 1388 | ring_free(&ring); |
| 1389 | return 0; |
| 1390 | } |
| 1391 | fputs("{\"ok\":true,\"action\":\"tail\",\"plugin\":\"" PLUGIN_ID "\"," |
| 1392 | "\"utc\":", stdout); |
| 1393 | json_str(utc); |
| 1394 | fputs(",\"src\":", stdout); json_str(s->id); |
| 1395 | fputs(",\"label\":", stdout); json_str(s->label); |
| 1396 | fputs(",\"kind\":", stdout); json_str(s->kind); |
| 1397 | printf(",\"requested\":%d,\"count\":%d,\"entries\":[", nlines, ring.n); |
| 1398 | for (i = 0; i < ring.n; i++) { |
| 1399 | entry_t *e = ring_at(&ring, i); |
| 1400 | if (i) fputc(',', stdout); |
| 1401 | fputs("{\"ts\":", stdout); json_str(e->ts); |
| 1402 | fputs(",\"unit\":", stdout); json_str(e->unit); |
| 1403 | fputs(",\"sev\":", stdout); json_str(sev_name(e->sev)); |
| 1404 | fputs(",\"text\":", stdout); json_str(e->text); |
| 1405 | fputc('}', stdout); |
| 1406 | } |
| 1407 | fputs("]}\n", stdout); |
| 1408 | ring_free(&ring); |
| 1409 | return 0; |
| 1410 | } |
| 1411 | |
| 1412 | /* search */ |
| 1413 | { |
| 1414 | list_t hits; |
| 1415 | int scanned; |
| 1416 | int i; |
| 1417 | |
| 1418 | if (!q[0]) { |
| 1419 | json_header(); |
| 1420 | fputs("{\"ok\":false,\"error\":\"missing_query\"," |
| 1421 | "\"message\":\"action=search needs q=<text>\"}\n", stdout); |
| 1422 | return 0; |
| 1423 | } |
| 1424 | if (!list_init(&hits, SEARCH_HITS_MAX)) { |
| 1425 | json_header(); |
| 1426 | fputs("{\"ok\":false,\"error\":\"out_of_memory\"}\n", stdout); |
| 1427 | return 0; |
| 1428 | } |
| 1429 | scanned = collect_search(s, q, &hits); |
| 1430 | json_header(); |
| 1431 | if (scanned < 0) { |
| 1432 | fputs("{\"ok\":false,\"error\":\"unreadable_source\"," |
| 1433 | "\"src\":", stdout); |
| 1434 | json_str(s->id); |
| 1435 | fputs("}\n", stdout); |
| 1436 | list_free(&hits); |
| 1437 | return 0; |
| 1438 | } |
| 1439 | fputs("{\"ok\":true,\"action\":\"search\",\"plugin\":\"" PLUGIN_ID "\"," |
| 1440 | "\"utc\":", stdout); |
| 1441 | json_str(utc); |
| 1442 | fputs(",\"src\":", stdout); json_str(s->id); |
| 1443 | fputs(",\"label\":", stdout); json_str(s->label); |
| 1444 | fputs(",\"q\":", stdout); json_str(q); |
| 1445 | printf(",\"scanned\":%d,\"count\":%d,\"max\":%d,\"truncated\":%s,\"hits\":[", |
| 1446 | scanned, hits.n, SEARCH_HITS_MAX, |
| 1447 | hits.n >= SEARCH_HITS_MAX ? "true" : "false"); |
| 1448 | for (i = 0; i < hits.n; i++) { |
| 1449 | if (i) fputc(',', stdout); |
| 1450 | fputs("{\"ts\":", stdout); json_str(hits.v[i].ts); |
| 1451 | fputs(",\"unit\":", stdout); json_str(hits.v[i].unit); |
| 1452 | fputs(",\"sev\":", stdout); json_str(sev_name(hits.v[i].sev)); |
| 1453 | fputs(",\"text\":", stdout); json_str(hits.v[i].text); |
| 1454 | fputc('}', stdout); |
| 1455 | } |
| 1456 | fputs("]}\n", stdout); |
| 1457 | list_free(&hits); |
| 1458 | return 0; |
| 1459 | } |
| 1460 | } |
| 1461 | } |
| 1462 | |
| 1463 | /* ------------------------------------------------------------------ */ |
| 1464 | /* HTML UI */ |
| 1465 | /* ------------------------------------------------------------------ */ |
| 1466 | |
| 1467 | static int mode_html(int embed) |
| 1468 | { |
| 1469 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1470 | "Cache-Control: no-store\r\n" |
| 1471 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1472 | |
| 1473 | fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" |
| 1474 | "<meta name='viewport' content='width=device-width,initial-scale=1'>" |
| 1475 | "<title>logs</title>", stdout); |
| 1476 | |
| 1477 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout); |
| 1478 | fputs( |
| 1479 | "*{box-sizing:border-box}" |
| 1480 | "html,body{height:100%}" |
| 1481 | "body{margin:0;padding:14px;background:var(--bg);color:var(--text);" |
| 1482 | "font-family:var(--font);font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased}" |
| 1483 | ".wrap{max-width:1280px;margin:0 auto;display:flex;flex-direction:column;" |
| 1484 | "gap:12px;min-height:100%}" |
| 1485 | ".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap}" |
| 1486 | ".title{font-size:19px;font-weight:700;margin:0;letter-spacing:-.01em}" |
| 1487 | ".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow:hidden;" |
| 1488 | "text-overflow:ellipsis;white-space:nowrap;max-width:46ch}" |
| 1489 | ".spacer{flex:1}" |
| 1490 | ".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" |
| 1491 | "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" |
| 1492 | ".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" |
| 1493 | ".pill.paused{color:var(--warn);border-color:rgba(255,214,10,.4)}" |
| 1494 | "select,input,button{font-family:inherit;font-size:13px;color:var(--text)}" |
| 1495 | "select,input{background:var(--input-bg);border:1px solid var(--line);" |
| 1496 | "border-radius:9px;padding:7px 11px;min-width:0}" |
| 1497 | "select{max-width:100%}" |
| 1498 | "input[type=text]{flex:1;min-width:120px;font-family:var(--mono);font-size:12px}" |
| 1499 | "input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}" |
| 1500 | "button{background:var(--accent);color:#fff;border:0;border-radius:999px;" |
| 1501 | "padding:7px 14px;font-weight:600;cursor:pointer;white-space:nowrap}" |
| 1502 | "button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" |
| 1503 | "button.on{background:var(--accent);color:#fff;border-color:transparent}" |
| 1504 | "button.sm{padding:5px 11px;font-size:12px}" |
| 1505 | "button:active{transform:scale(.98)}" |
| 1506 | ".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" |
| 1507 | ".seg{display:inline-flex;gap:3px;background:var(--surface2);border:1px solid var(--line);" |
| 1508 | "border-radius:999px;padding:3px;flex-wrap:nowrap}" |
| 1509 | ".seg button{background:transparent;color:var(--muted);border:0;padding:4px 10px;font-size:12px}" |
| 1510 | ".seg button.on{background:var(--accent);color:#fff}" |
| 1511 | ".panel{background:var(--surface);border:1px solid var(--line);border-radius:14px;" |
| 1512 | "display:flex;flex-direction:column;min-height:0;flex:1;overflow:hidden}" |
| 1513 | ".loghead{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 12px;" |
| 1514 | "border-bottom:1px solid var(--line)}" |
| 1515 | ".log{flex:1;overflow:auto;padding:6px 0;min-height:260px;max-height:calc(100vh - 260px);" |
| 1516 | "font-family:var(--mono);font-size:12px;line-height:1.55}" |
| 1517 | ".log.wrap .tx{white-space:pre-wrap;word-break:break-word}" |
| 1518 | ".ln{display:grid;grid-template-columns:112px minmax(0,1fr) 132px;gap:10px;" |
| 1519 | "padding:3px 12px;border-left:3px solid transparent;align-items:baseline}" |
| 1520 | ".ln:hover{background:var(--surface-hover)}" |
| 1521 | ".ln .ts{color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;" |
| 1522 | "text-overflow:ellipsis}" |
| 1523 | ".ln .un{color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;" |
| 1524 | "text-overflow:ellipsis;text-align:right}" |
| 1525 | ".ln .tx{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}" |
| 1526 | ".ln.err{border-left-color:var(--red)}" |
| 1527 | ".ln.err .tx{color:var(--red)}" |
| 1528 | ".ln.warn{border-left-color:var(--warn)}" |
| 1529 | ".ln.warn .tx{color:var(--warn)}" |
| 1530 | ".ln.info{border-left-color:transparent}" |
| 1531 | ".ln mark{background:rgba(255,214,10,.28);color:inherit;border-radius:3px;padding:0 1px}" |
| 1532 | ".empty{color:var(--muted);padding:24px 14px;text-align:center;font-size:13px;" |
| 1533 | "font-family:var(--font)}" |
| 1534 | ".foot{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:8px 12px;" |
| 1535 | "border-top:1px solid var(--line);color:var(--muted);font-size:11px;font-family:var(--mono)}" |
| 1536 | ".hide{display:none!important}" |
| 1537 | ".muted{color:var(--muted)}" |
| 1538 | "@media(max-width:760px){" |
| 1539 | ".ln{grid-template-columns:96px minmax(0,1fr);gap:8px}" |
| 1540 | ".ln .un{display:none}" |
| 1541 | ".log{max-height:calc(100vh - 330px)}" |
| 1542 | "#q{flex:1 1 100%}" |
| 1543 | "}" |
| 1544 | "@media(max-width:480px){" |
| 1545 | "body{padding:10px}" |
| 1546 | ".title{font-size:17px}" |
| 1547 | ".sub{max-width:26ch}" |
| 1548 | ".seg button{padding:4px 8px}" |
| 1549 | "}", stdout); |
| 1550 | |
| 1551 | fputs("</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); |
| 1552 | |
| 1553 | if (!embed) { |
| 1554 | fputs("<div class='top'><a href='/' style='color:var(--accent);" |
| 1555 | "text-decoration:none;font-weight:600'>← Back to Bot</a></div>", stdout); |
| 1556 | } |
| 1557 | |
| 1558 | fputs("<div class='top'>" |
| 1559 | "<h1 class='title'>logs</h1>" |
| 1560 | "<span class='sub' id='pSrc'>—</span>" |
| 1561 | "<span class='spacer'></span>" |
| 1562 | "<span class='pill paused' id='pState'>paused</span>" |
| 1563 | "<button class='ghost sm embed-hide' id='btnTheme' type='button'>Theme</button>" |
| 1564 | "</div>", stdout); |
| 1565 | |
| 1566 | /* source + controls */ |
| 1567 | fputs("<div class='panel'><div class='loghead'>" |
| 1568 | "<select id='srcSel' title='Log source'><option value=''>—</option></select>" |
| 1569 | "<div class='seg' id='segLines'>" |
| 1570 | "<button type='button' data-n='100'>100</button>" |
| 1571 | "<button type='button' data-n='200' class='on'>200</button>" |
| 1572 | "<button type='button' data-n='500'>500</button>" |
| 1573 | "<button type='button' data-n='2000'>2000</button>" |
| 1574 | "</div>" |
| 1575 | "<button type='button' id='btnFollow' class='on'>Follow</button>" |
| 1576 | "<input type='text' id='q' placeholder='Search in this source'>" |
| 1577 | "<button type='button' id='btnSearch' class='sm'>Search</button>" |
| 1578 | "<button type='button' id='btnWrap' class='ghost sm'>Wrap</button>" |
| 1579 | "<button type='button' id='btnCopy' class='ghost sm'>Copy</button>" |
| 1580 | "<button type='button' id='btnReload' class='ghost sm'>Reload</button>" |
| 1581 | "</div>", stdout); |
| 1582 | |
| 1583 | fputs("<div class='log' id='log'><div class='empty' id='empty'>Loading sources…</div></div>", stdout); |
| 1584 | fputs("<div class='foot'>" |
| 1585 | "<span id='fCount'>0 entries</span>" |
| 1586 | "<span class='spacer'></span>" |
| 1587 | "<span id='fNote'>local read only · zero network</span>" |
| 1588 | "</div></div>", stdout); |
| 1589 | |
| 1590 | fputs("<div class='foot' style='border:0;padding:0'><span class='muted'>" |
| 1591 | "Reads an allowlist of local log files and the local system journal. " |
| 1592 | "Every source is read-only; nothing is written, and no request leaves this node." |
| 1593 | "</span></div>", stdout); |
| 1594 | |
| 1595 | /* ---------------- script ---------------- */ |
| 1596 | fputs("<script>\n" |
| 1597 | "(function(){\n" |
| 1598 | " var qs = new URLSearchParams(location.search);\n" |
| 1599 | " var HUB = qs.get('plugin') || '';\n" |
| 1600 | " var node = qs.get('node') || '';\n" |
| 1601 | " var sid = qs.get('id') || '';\n" |
| 1602 | " var pwd = qs.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" |
| 1603 | " localStorage.getItem('bot_active_pwd') || '';\n" |
| 1604 | " var SRC = '', LINES = 200, FOLLOW = true, TIMER = null, BUSY = false;\n" |
| 1605 | " var LAST = [], QUERY = '', MODE = 'tail';\n" |
| 1606 | "\n" |
| 1607 | " /* Two routes: opened through the hub -> call the hub proxy back;\n" |
| 1608 | " opened directly on the node -> the plugin IS the route. */\n" |
| 1609 | " function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_logs'; }\n" |
| 1610 | " function withCtx(u){\n" |
| 1611 | " if (node) u += '&node=' + encodeURIComponent(node);\n" |
| 1612 | " if (sid) u += '&id=' + encodeURIComponent(sid);\n" |
| 1613 | " if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" |
| 1614 | " return u;\n" |
| 1615 | " }\n" |
| 1616 | " function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" |
| 1617 | " function $(i){ return document.getElementById(i); }\n" |
| 1618 | " function el(t,c,x){ var e=document.createElement(t); if(c) e.className=c;\n" |
| 1619 | " if (x!==undefined && x!==null) e.textContent=String(x); return e; }\n" |
| 1620 | " function api(extra){\n" |
| 1621 | " return fetch(withCtx(base() + '?' + extra), {headers:hdr(), cache:'no-store'})\n" |
| 1622 | " .then(function(r){ return r.json(); });\n" |
| 1623 | " }\n" |
| 1624 | "\n" |
| 1625 | " function state(txt, cls){\n" |
| 1626 | " var p = $('pState'); p.textContent = txt; p.className = 'pill ' + (cls||'paused');\n" |
| 1627 | " }\n" |
| 1628 | "\n" |
| 1629 | " function humanSize(n){\n" |
| 1630 | " if (!n) return '';\n" |
| 1631 | " var u=['B','KB','MB','GB'], i=0, v=n;\n" |
| 1632 | " while (v >= 1024 && i < u.length-1){ v/=1024; i++; }\n" |
| 1633 | " return (i===0 ? v : v.toFixed(1)) + ' ' + u[i];\n" |
| 1634 | " }\n" |
| 1635 | "\n" |
| 1636 | " function loadSources(){\n" |
| 1637 | " return api('action=sources').then(function(d){\n" |
| 1638 | " var sel = $('srcSel');\n" |
| 1639 | " sel.innerHTML = '';\n" |
| 1640 | " if (!d || d.ok === false){ $('empty').textContent = 'Could not list sources.'; return; }\n" |
| 1641 | " var groups = [['journal','Journal'],['file','Log files'],['event','Event logs']];\n" |
| 1642 | " var seen = {};\n" |
| 1643 | " for (var g=0; g<groups.length; g++){\n" |
| 1644 | " var kind = groups[g][0], any = false, og = null;\n" |
| 1645 | " for (var i=0;i<d.sources.length;i++){\n" |
| 1646 | " var s = d.sources[i];\n" |
| 1647 | " if (s.kind !== kind) continue;\n" |
| 1648 | " if (!og){ og = document.createElement('optgroup'); og.label = groups[g][1]; }\n" |
| 1649 | " var o = document.createElement('option');\n" |
| 1650 | " o.value = s.id;\n" |
| 1651 | " o.textContent = s.label + (s.size ? ' (' + humanSize(s.size) + ')' : '');\n" |
| 1652 | " og.appendChild(o); any = true;\n" |
| 1653 | " }\n" |
| 1654 | " if (any) sel.appendChild(og);\n" |
| 1655 | " }\n" |
| 1656 | " if (d.truncated) $('fNote').textContent = 'source list truncated · local read only';\n" |
| 1657 | " /* keep the previous selection when it still exists */\n" |
| 1658 | " var want = SRC;\n" |
| 1659 | " if (!want){\n" |
| 1660 | " for (var k=0;k<d.sources.length;k++){ want = d.sources[k].id; break; }\n" |
| 1661 | " }\n" |
| 1662 | " if (want){ sel.value = want; SRC = want; }\n" |
| 1663 | " if (!d.sources.length){\n" |
| 1664 | " $('empty').textContent = 'No readable log sources on this node.';\n" |
| 1665 | " }\n" |
| 1666 | " return d;\n" |
| 1667 | " }).catch(function(e){ $('empty').textContent = 'Request failed: ' + e; });\n" |
| 1668 | " }\n" |
| 1669 | "\n" |
| 1670 | " function highlight(text, q){\n" |
| 1671 | " var frag = document.createDocumentFragment();\n" |
| 1672 | " if (!q) { frag.appendChild(document.createTextNode(text)); return frag; }\n" |
| 1673 | " var hay = text.toLowerCase(), need = q.toLowerCase(), at = 0;\n" |
| 1674 | " while (true){\n" |
| 1675 | " var i = hay.indexOf(need, at);\n" |
| 1676 | " if (i < 0){ frag.appendChild(document.createTextNode(text.slice(at))); break; }\n" |
| 1677 | " if (i > at) frag.appendChild(document.createTextNode(text.slice(at, i)));\n" |
| 1678 | " var m = document.createElement('mark');\n" |
| 1679 | " m.textContent = text.slice(i, i + q.length);\n" |
| 1680 | " frag.appendChild(m);\n" |
| 1681 | " at = i + q.length;\n" |
| 1682 | " }\n" |
| 1683 | " return frag;\n" |
| 1684 | " }\n" |
| 1685 | "\n" |
| 1686 | " function renderRows(rows, q){\n" |
| 1687 | " var box = $('log');\n" |
| 1688 | " box.innerHTML = '';\n" |
| 1689 | " if (!rows || !rows.length){\n" |
| 1690 | " var e = el('div','empty', MODE === 'search'\n" |
| 1691 | " ? 'No matches in the scanned window.'\n" |
| 1692 | " : 'This source produced no entries.');\n" |
| 1693 | " box.appendChild(e);\n" |
| 1694 | " $('fCount').textContent = '0 entries';\n" |
| 1695 | " return;\n" |
| 1696 | " }\n" |
| 1697 | " var frag = document.createDocumentFragment();\n" |
| 1698 | " for (var i=0;i<rows.length;i++){\n" |
| 1699 | " var r = rows[i];\n" |
| 1700 | " var ln = el('div', 'ln ' + (r.sev || 'info'));\n" |
| 1701 | " ln.appendChild(el('span','ts', r.ts || ''));\n" |
| 1702 | " var tx = el('span','tx');\n" |
| 1703 | " tx.appendChild(highlight(r.text === undefined ? '' : r.text, q));\n" |
| 1704 | " ln.appendChild(tx);\n" |
| 1705 | " ln.appendChild(el('span','un', r.unit || ''));\n" |
| 1706 | " frag.appendChild(ln);\n" |
| 1707 | " }\n" |
| 1708 | " box.appendChild(frag);\n" |
| 1709 | " $('fCount').textContent = rows.length + ' entries';\n" |
| 1710 | " }\n" |
| 1711 | "\n" |
| 1712 | " function scrollBottom(){ var b = $('log'); b.scrollTop = b.scrollHeight; }\n" |
| 1713 | "\n" |
| 1714 | " function tail(keepScroll){\n" |
| 1715 | " if (!SRC) return Promise.resolve();\n" |
| 1716 | " var atBottom = true, b = $('log');\n" |
| 1717 | " atBottom = (b.scrollTop + b.clientHeight) >= (b.scrollHeight - 24);\n" |
| 1718 | " return api('action=tail&lines=' + LINES + '&src=' + encodeURIComponent(SRC))\n" |
| 1719 | " .then(function(d){\n" |
| 1720 | " if (!d || d.ok === false){\n" |
| 1721 | " state('error','paused');\n" |
| 1722 | " $('empty').textContent = (d && d.message) || (d && d.error) || 'unreadable source';\n" |
| 1723 | " $('log').innerHTML = '';\n" |
| 1724 | " $('log').appendChild(el('div','empty',(d && d.message) || 'unreadable source'));\n" |
| 1725 | " $('fCount').textContent = '0 entries';\n" |
| 1726 | " return;\n" |
| 1727 | " }\n" |
| 1728 | " MODE = 'tail';\n" |
| 1729 | " LAST = d.entries || [];\n" |
| 1730 | " $('pSrc').textContent = d.label || d.src || '';\n" |
| 1731 | " renderRows(LAST, '');\n" |
| 1732 | " if (!keepScroll && atBottom) scrollBottom();\n" |
| 1733 | " state(FOLLOW ? 'live 3s' : 'paused', FOLLOW ? 'live' : 'paused');\n" |
| 1734 | " })\n" |
| 1735 | " .catch(function(e){ state('offline','paused'); $('fNote').textContent = 'request failed'; });\n" |
| 1736 | " }\n" |
| 1737 | "\n" |
| 1738 | " function search(){\n" |
| 1739 | " if (!SRC || !QUERY){ tail(); return Promise.resolve(); }\n" |
| 1740 | " return api('action=search&src=' + encodeURIComponent(SRC) +\n" |
| 1741 | " '&q=' + encodeURIComponent(QUERY))\n" |
| 1742 | " .then(function(d){\n" |
| 1743 | " if (!d || d.ok === false){\n" |
| 1744 | " $('log').innerHTML = '';\n" |
| 1745 | " $('log').appendChild(el('div','empty',(d && (d.message||d.error)) || 'search failed'));\n" |
| 1746 | " return;\n" |
| 1747 | " }\n" |
| 1748 | " MODE = 'search';\n" |
| 1749 | " LAST = d.hits || [];\n" |
| 1750 | " renderRows(LAST, QUERY);\n" |
| 1751 | " $('fCount').textContent = LAST.length + ' hits of ' + d.scanned + ' scanned' +\n" |
| 1752 | " (d.truncated ? ' (capped)' : '');\n" |
| 1753 | " state('search','paused');\n" |
| 1754 | " })\n" |
| 1755 | " .catch(function(e){ $('fNote').textContent = 'search failed'; });\n" |
| 1756 | " }\n" |
| 1757 | "\n" |
| 1758 | " function schedule(){\n" |
| 1759 | " if (TIMER){ clearInterval(TIMER); TIMER = null; }\n" |
| 1760 | " if (FOLLOW && MODE === 'tail' && document.visibilityState === 'visible'){\n" |
| 1761 | " TIMER = setInterval(function(){ if (!BUSY){ BUSY = true; tail().then(function(){ BUSY = false; }); } }, 3000);\n" |
| 1762 | " state('live 3s','live');\n" |
| 1763 | " } else {\n" |
| 1764 | " state(MODE === 'search' ? 'search' : 'paused', 'paused');\n" |
| 1765 | " }\n" |
| 1766 | " }\n" |
| 1767 | "\n" |
| 1768 | " function refresh(){\n" |
| 1769 | " if (MODE === 'search' && QUERY) search(); else tail();\n" |
| 1770 | " schedule();\n" |
| 1771 | " }\n" |
| 1772 | "\n" |
| 1773 | " /* ---- wiring ---- */\n" |
| 1774 | " $('srcSel').addEventListener('change', function(){\n" |
| 1775 | " SRC = this.value; MODE = 'tail'; QUERY = $('q').value = ''; refresh();\n" |
| 1776 | " });\n" |
| 1777 | " Array.prototype.forEach.call(document.querySelectorAll('#segLines button'), function(b){\n" |
| 1778 | " b.addEventListener('click', function(){\n" |
| 1779 | " Array.prototype.forEach.call(document.querySelectorAll('#segLines button'),\n" |
| 1780 | " function(x){ x.classList.remove('on'); });\n" |
| 1781 | " b.classList.add('on');\n" |
| 1782 | " LINES = parseInt(b.getAttribute('data-n'), 10) || 200;\n" |
| 1783 | " refresh();\n" |
| 1784 | " });\n" |
| 1785 | " });\n" |
| 1786 | " $('btnFollow').addEventListener('click', function(){\n" |
| 1787 | " FOLLOW = !FOLLOW;\n" |
| 1788 | " this.classList.toggle('on', FOLLOW);\n" |
| 1789 | " this.textContent = FOLLOW ? 'Follow' : 'Paused';\n" |
| 1790 | " if (MODE === 'search' && FOLLOW) MODE = 'tail';\n" |
| 1791 | " refresh();\n" |
| 1792 | " });\n" |
| 1793 | " $('btnSearch').addEventListener('click', function(){\n" |
| 1794 | " QUERY = $('q').value.trim();\n" |
| 1795 | " if (!QUERY){ MODE = 'tail'; tail(); schedule(); return; }\n" |
| 1796 | " MODE = 'search'; search(); schedule();\n" |
| 1797 | " });\n" |
| 1798 | " $('q').addEventListener('keydown', function(e){ if (e.key === 'Enter') $('btnSearch').click(); });\n" |
| 1799 | " $('btnWrap').addEventListener('click', function(){\n" |
| 1800 | " var w = $('log').classList.toggle('wrap');\n" |
| 1801 | " this.classList.toggle('on', w);\n" |
| 1802 | " });\n" |
| 1803 | " $('btnCopy').addEventListener('click', function(){\n" |
| 1804 | " var out = [];\n" |
| 1805 | " for (var i=0;i<LAST.length;i++){\n" |
| 1806 | " var r = LAST[i];\n" |
| 1807 | " out.push((r.ts ? r.ts + ' ' : '') + (r.unit ? r.unit + ': ' : '') + (r.text || ''));\n" |
| 1808 | " }\n" |
| 1809 | " var txt = out.join('\\n');\n" |
| 1810 | " var btn = this;\n" |
| 1811 | " function done(ok){ btn.textContent = ok ? 'Copied' : 'Copy failed';\n" |
| 1812 | " setTimeout(function(){ btn.textContent = 'Copy'; }, 1400); }\n" |
| 1813 | " if (navigator.clipboard && navigator.clipboard.writeText){\n" |
| 1814 | " navigator.clipboard.writeText(txt).then(function(){ done(true); },\n" |
| 1815 | " function(){ done(false); });\n" |
| 1816 | " } else {\n" |
| 1817 | " var ta = document.createElement('textarea');\n" |
| 1818 | " ta.value = txt; document.body.appendChild(ta); ta.select();\n" |
| 1819 | " try { done(document.execCommand('copy')); } catch(e){ done(false); }\n" |
| 1820 | " document.body.removeChild(ta);\n" |
| 1821 | " }\n" |
| 1822 | " });\n" |
| 1823 | " $('btnReload').addEventListener('click', function(){ loadSources().then(refresh); });\n" |
| 1824 | " $('btnTheme').addEventListener('click', function(){\n" |
| 1825 | " if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme && window.sxTheme() === 'dark' ? 'light' : 'dark');\n" |
| 1826 | " });\n" |
| 1827 | "\n" |
| 1828 | " document.addEventListener('visibilitychange', function(){\n" |
| 1829 | " if (document.visibilityState === 'visible'){ refresh(); }\n" |
| 1830 | " else { schedule(); }\n" |
| 1831 | " });\n" |
| 1832 | " window.addEventListener('bot-theme', function(){});\n" |
| 1833 | "\n" |
| 1834 | " loadSources().then(refresh);\n" |
| 1835 | "})();\n" |
| 1836 | "</script></div></body></html>\n", stdout); |
| 1837 | |
| 1838 | return 0; |
| 1839 | } |
| 1840 | |
| 1841 | /* ------------------------------------------------------------------ */ |
| 1842 | /* Entry point */ |
| 1843 | /* ------------------------------------------------------------------ */ |
| 1844 | |
| 1845 | int main(int argc, char **argv) |
| 1846 | { |
| 1847 | const char *qs; |
| 1848 | int i; |
| 1849 | |
| 1850 | for (i = 1; i < argc; i++) { |
| 1851 | if (strcmp(argv[i], "--meta") == 0) |
| 1852 | return mode_meta(); |
| 1853 | if (strcmp(argv[i], "--version") == 0) { |
| 1854 | printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); |
| 1855 | return 0; |
| 1856 | } |
| 1857 | if (strcmp(argv[i], "--help") == 0) { |
| 1858 | printf("usage: %s [--meta] [--version] [--help]\n" |
| 1859 | " CGI mode reads QUERY_STRING:\n" |
| 1860 | " ?action=sources readable log sources\n" |
| 1861 | " ?action=tail&src=<id>&lines=<N> last N entries of a source\n" |
| 1862 | " ?action=search&src=<id>&q=<text> case-insensitive substring search\n" |
| 1863 | " ?action=units systemd units with journal entries\n" |
| 1864 | " ?action=info plugin info\n" |
| 1865 | " (no action) HTML log viewer\n", PLUGIN_ID); |
| 1866 | return 0; |
| 1867 | } |
| 1868 | } |
| 1869 | |
| 1870 | if (getenv("SX_PLUGIN_META")) |
| 1871 | return mode_meta(); |
| 1872 | |
| 1873 | require_node_auth(); |
| 1874 | |
| 1875 | qs = getenv("QUERY_STRING"); |
| 1876 | if (!qs) qs = ""; |
| 1877 | |
| 1878 | if (strstr(qs, "action=") || strstr(qs, "format=json")) |
| 1879 | return mode_json(qs); |
| 1880 | |
| 1881 | { |
| 1882 | char embedv[16]; |
| 1883 | embedv[0] = '\0'; |
| 1884 | if (get_query_val(qs, "embed", embedv, sizeof(embedv))) |
| 1885 | return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); |
| 1886 | } |
| 1887 | return mode_html(0); |
| 1888 | } |