scorpiox-bot-plugin-crontab
←plugin_crontab.cc
1676 lines · 57 KBHEADBlameDownload
1/*
2 * plugin_crontab — SCORPIOX BOT open-source cron schedule inspector
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=jobs | ?action=explain&expr=... | ?format=json -> JSON node API
7 * 3. GET (default) -> responsive HTML schedule inspector
8 *
9 * Strictly READ-ONLY. It never writes a crontab, never installs a task and
10 * never executes a scheduled command. On POSIX it reads the user's
11 * `crontab -l` output plus /etc/crontab and the files in /etc/cron.d; on Windows it reads
12 * `schtasks /Query /FO CSV`. Setting CRONTAB_FILE to a fixture path bypasses
13 * all of that, which is what the offline tests use.
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#if !defined(_WIN32)
23# define _POSIX_C_SOURCE 200809L
24# define _DEFAULT_SOURCE 1
25#endif
26
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <time.h>
31#include <ctype.h>
32
33#if defined(_WIN32)
34# define WIN32_LEAN_AND_MEAN
35# include <windows.h>
36# define sx_popen _popen
37# define sx_pclose _pclose
38#else
39# include <unistd.h>
40# include <dirent.h>
41# define sx_popen popen
42# define sx_pclose pclose
43#endif
44
45#include "bot_theme_plugin.h"
46
47#define PLUGIN_SLUG "crontab"
48#define PLUGIN_ID "plugin_crontab"
49#define PLUGIN_VER "1.0.1"
50
51#define MAX_JOBS 512
52#define MAX_EXPR 128
53#define MAX_DESC 224
54#define MAX_CMD 512
55#define MAX_SRC 64
56#define MAX_RUNS 5
57#define HORIZON_DAYS 7305 /* twenty years: five runs even for 29 February */
58#define READ_LINE 2048
59
60/* ------------------------------------------------------------------ */
61/* Small utilities */
62/* ------------------------------------------------------------------ */
63
64static void url_decode(char *s)
65{
66 char *o = s;
67 if (!s) return;
68 while (*s) {
69 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
70 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
71 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
72 *o++ = (char)((hi << 4) | lo);
73 s += 3;
74 } else if (*s == '+') {
75 *o++ = ' ';
76 s++;
77 } else {
78 *o++ = *s++;
79 }
80 }
81 *o = '\0';
82}
83
84static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
85{
86 size_t klen;
87 const char *p;
88
89 if (!out || outsz == 0) return 0;
90 out[0] = '\0';
91 if (!qs || !key) return 0;
92 klen = strlen(key);
93
94 for (p = qs; *p; ) {
95 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
96 const char *v = p + klen + 1;
97 size_t i = 0;
98 while (*v && *v != '&' && i + 1 < outsz)
99 out[i++] = *v++;
100 out[i] = '\0';
101 url_decode(out);
102 return 1;
103 }
104 p = strchr(p, '&');
105 if (!p) break;
106 p++;
107 }
108 return 0;
109}
110
111static void json_str(const char *s)
112{
113 putchar('"');
114 for (; s && *s; s++) {
115 unsigned char c = (unsigned char)*s;
116 switch (c) {
117 case '"': fputs("\\\"", stdout); break;
118 case '\\': fputs("\\\\", stdout); break;
119 case '\n': fputs("\\n", stdout); break;
120 case '\r': fputs("\\r", stdout); break;
121 case '\t': fputs("\\t", stdout); break;
122 default:
123 if (c < 0x20) printf("\\u%04x", c);
124 else putchar(c);
125 }
126 }
127 putchar('"');
128}
129
130static void str_copy(char *dst, size_t sz, const char *src)
131{
132 size_t n;
133 if (!dst || sz == 0) return;
134 if (!src) { dst[0] = '\0'; return; }
135 n = strlen(src);
136 if (n >= sz) n = sz - 1;
137 memcpy(dst, src, n);
138 dst[n] = '\0';
139}
140
141static void str_trim(char *s)
142{
143 size_t n;
144 char *p;
145
146 if (!s) return;
147 p = s;
148 while (*p && isspace((unsigned char)*p)) p++;
149 if (p != s) memmove(s, p, strlen(p) + 1);
150 n = strlen(s);
151 while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0';
152}
153
154static void utc_stamp(time_t t, char *buf, size_t sz)
155{
156 struct tm tmv;
157#if defined(_WIN32)
158 gmtime_s(&tmv, &t);
159#else
160 gmtime_r(&t, &tmv);
161#endif
162 if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0)
163 str_copy(buf, sz, "1970-01-01T00:00:00Z");
164}
165
166static void local_stamp(time_t t, char *buf, size_t sz)
167{
168 struct tm tmv;
169#if defined(_WIN32)
170 localtime_s(&tmv, &t);
171#else
172 localtime_r(&t, &tmv);
173#endif
174 if (strftime(buf, sz, "%Y-%m-%d %H:%M", &tmv) == 0)
175 str_copy(buf, sz, "1970-01-01 00:00");
176}
177
178/* ------------------------------------------------------------------ */
179/* Cron model */
180/* ------------------------------------------------------------------ */
181
182typedef struct {
183 int valid;
184 char error[96];
185 char raw[MAX_EXPR];
186 char keyword[16]; /* "@daily" etc; empty for 5-field syntax */
187 char f[5][40]; /* original field texts */
188 unsigned char min[60];
189 unsigned char hour[24];
190 unsigned char dom[32]; /* index 1..31 used */
191 unsigned char mon[13]; /* index 1..12 used */
192 unsigned char dow[7]; /* index 0 == Sunday */
193 int dom_restricted;
194 int dow_restricted;
195 int boot_only; /* @reboot — no computable fire times */
196 char desc[MAX_DESC];
197} cron_t;
198
199static const char *const k_mon_names[12] = {
200 "jan", "feb", "mar", "apr", "may", "jun",
201 "jul", "aug", "sep", "oct", "nov", "dec"
202};
203static const char *const k_dow_names[7] = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };
204static const char *const k_mon_long[12] = {
205 "January", "February", "March", "April", "May", "June",
206 "July", "August", "September", "October", "November", "December"
207};
208static const char *const k_dow_long[7] = {
209 "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
210};
211
212static void cron_clear(cron_t *c)
213{
214 memset(c, 0, sizeof(*c));
215}
216
217static int name_index(const char *tok, int len, const char *const *names, int count)
218{
219 int i;
220 char buf[16];
221 if (len <= 0 || len >= (int)sizeof(buf)) return -1;
222 for (i = 0; i < len; i++) buf[i] = (char)tolower((unsigned char)tok[i]);
223 buf[len] = '\0';
224 for (i = 0; i < count; i++)
225 if (strcmp(buf, names[i]) == 0) return i;
226 return -1;
227}
228
229/* Plain number or 3-letter name -> value. Returns 1 on success. */
230static int parse_value(const char *tok, int len, const char *const *names,
231 int namecount, int name_offset, int *out)
232{
233 int i;
234 int v = 0;
235 int named;
236
237 if (len <= 0) return 0;
238 named = name_index(tok, len, names, namecount);
239 if (named >= 0) { *out = named + name_offset; return 1; }
240 for (i = 0; i < len; i++) {
241 if (!isdigit((unsigned char)tok[i])) return 0;
242 v = v * 10 + (tok[i] - '0');
243 if (v > 100000) return 0;
244 }
245 *out = v;
246 return 1;
247}
248
249/*
250 * Parse one cron field into a flag array (indices lo..hi).
251 * Accepts "*", "N", "a-b", "*&#47;step", "a-b&#47;step" and comma lists.
252 * Returns 1 on success, 0 on syntax error, -1 on out-of-range value.
253 */
254static int parse_field(const char *text, int lo, int hi,
255 const char *const *names, int namecount, int name_offset,
256 unsigned char *flags)
257{
258 char work[256];
259 char *item;
260
261 memset(flags, 0, (size_t)(hi + 1));
262 if (!text || !*text) return 0;
263 if (strlen(text) >= sizeof(work)) return 0;
264 str_copy(work, sizeof(work), text);
265
266 item = work;
267 while (item && *item) {
268 char *comma = strchr(item, ',');
269 char rng[128];
270 const char *slash;
271 int step = 1;
272 int start = lo;
273 int end = hi;
274 int v;
275
276 if (comma) *comma = '\0';
277 str_trim(item);
278 if (!*item) return 0;
279
280 slash = strchr(item, '/');
281 if (slash) {
282 size_t off = (size_t)(slash - item);
283 if (off >= sizeof(rng)) return 0;
284 memcpy(rng, item, off);
285 rng[off] = '\0';
286 if (!parse_value(slash + 1, (int)strlen(slash + 1), NULL, 0, 0, &step)) return 0;
287 if (step <= 0) return 0;
288 if (step > hi - lo + 1) step = hi - lo + 1;
289 } else {
290 str_copy(rng, sizeof(rng), item);
291 }
292
293 if (strcmp(rng, "*") == 0) {
294 start = lo;
295 end = hi;
296 } else {
297 const char *dash = strchr(rng, '-');
298 if (dash) {
299 if (!parse_value(rng, (int)(dash - rng), names, namecount, name_offset, &start)) return 0;
300 if (!parse_value(dash + 1, (int)strlen(dash + 1), names, namecount, name_offset, &end)) return 0;
301 } else {
302 if (!parse_value(rng, (int)strlen(rng), names, namecount, name_offset, &start)) return 0;
303 end = slash ? hi : start;
304 }
305 }
306
307 if (start < lo || start > hi || end < lo || end > hi) return -1;
308 if (end < start) return -1;
309 for (v = start; v <= end; v += step) flags[v] = 1;
310
311 if (!comma) break;
312 item = comma + 1;
313 }
314 return 1;
315}
316
317/* True when every value in lo..hi is selected. */
318static int field_is_full(const unsigned char *flags, int lo, int hi)
319{
320 int i;
321 for (i = lo; i <= hi; i++)
322 if (!flags[i]) return 0;
323 return 1;
324}
325
326static int count_set(const unsigned char *flags, int lo, int hi)
327{
328 int i, n = 0;
329 for (i = lo; i <= hi; i++) if (flags[i]) n++;
330 return n;
331}
332
333/* ---------------------------------------------------------------- */
334/* Portable UTC mktime */
335/* ---------------------------------------------------------------- */
336
337/* Days since the Unix epoch for a civil date (Howard Hinnant's algorithm). */
338static long days_from_civil(int y, int m, int d)
339{
340 long era, yoe, doy, doe;
341
342 y -= (m <= 2);
343 era = (y >= 0 ? y : y - 399) / 400;
344 yoe = (long)(y - era * 400);
345 doy = (153L * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
346 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
347 return era * 146097L + doe - 719468L;
348}
349
350/*
351 * Portable UTC mktime. Implemented directly rather than calling timegm(),
352 * which is not declared by default on macOS and is missing on Windows.
353 */
354static time_t timegm_portable(struct tm *tmv)
355{
356 long days = days_from_civil(tmv->tm_year + 1900, tmv->tm_mon + 1, tmv->tm_mday);
357 return (time_t)(days * 86400L + (long)tmv->tm_hour * 3600L
358 + (long)tmv->tm_min * 60L + (long)tmv->tm_sec);
359}
360/* ---------------------------------------------------------------- */
361/* Human readable description of a parsed schedule */
362/* ---------------------------------------------------------------- */
363
364/* Append with bounds. */
365static void sapp(char *dst, size_t sz, const char *src)
366{
367 size_t have;
368 if (!dst || sz == 0 || !src) return;
369 have = strlen(dst);
370 if (have + 1 >= sz) return;
371 strncat(dst, src, sz - have - 1);
372}
373
374/* First selected index in [lo,hi], or lo when none. */
375static int first_set(const unsigned char *flags, int lo, int hi)
376{
377 int i;
378 for (i = lo; i <= hi; i++) if (flags[i]) return i;
379 return lo;
380}
381
382static void cron_describe_time(const cron_t *c, char *out, size_t sz)
383{
384 int nm, nh;
385
386 out[0] = '\0';
387
388 if (field_is_full(c->min, 0, 59) && field_is_full(c->hour, 0, 23)) {
389 str_copy(out, sz, "Every minute");
390 return;
391 }
392 if (c->f[0][0] == '*' && c->f[0][1] == '/' && field_is_full(c->hour, 0, 23)
393 && !strchr(c->f[0], ',')) {
394 int step = atoi(c->f[0] + 2);
395 if (step == 1) str_copy(out, sz, "Every minute");
396 else snprintf(out, sz, "Every %d minutes", step);
397 return;
398 }
399 if (field_is_full(c->hour, 0, 23) && c->f[1][0] == '*') {
400 int n = count_set(c->min, 0, 59);
401 if (c->f[0][0] == '*' && c->f[0][1] == '\0') {
402 str_copy(out, sz, "Every minute");
403 } else if (n <= 6) {
404 int m, first = 1;
405 sapp(out, sz, "Every hour at minute ");
406 for (m = 0; m < 60; m++) {
407 char t[8];
408 if (!c->min[m]) continue;
409 snprintf(t, sizeof(t), "%s%d", first ? "" : " and ", m);
410 sapp(out, sz, t);
411 first = 0;
412 }
413 } else {
414 snprintf(out, sz, "Every hour at %d selected minutes", n);
415 }
416 return;
417 }
418 if (c->f[1][0] == '*' && c->f[1][1] == '/' && c->min[0] == 0
419 && count_set(c->min, 0, 59) == 1 && !c->dom_restricted && !c->dow_restricted) {
420 int step = atoi(c->f[1] + 2);
421 snprintf(out, sz, "Every %d hours at minute %d", step, first_set(c->min, 0, 59));
422 return;
423 }
424
425 nm = count_set(c->min, 0, 59);
426 nh = count_set(c->hour, 0, 23);
427
428 /* uniform minute step inside a restricted hour window */
429 if (c->f[0][0] == '*' && c->f[0][1] == '/' && !strchr(c->f[0], ',')) {
430 int step = atoi(c->f[0] + 2);
431 int hlo = first_set(c->hour, 0, 23);
432 int hhi = hlo;
433 int h;
434 for (h = 23; h >= 0; h--) if (c->hour[h]) { hhi = h; break; }
435 if (step > 0 && nh > 1) {
436 snprintf(out, sz, "Every %d minutes, between %02d:00 and %02d:59",
437 step, hlo, hhi);
438 return;
439 }
440 }
441
442 if (nm == 1 && nh == 1) {
443 snprintf(out, sz, "At %02d:%02d", first_set(c->hour, 0, 23), first_set(c->min, 0, 59));
444 return;
445 }
446 if (nm * nh <= 6) {
447 int h, m, first = 1;
448 sapp(out, sz, "At ");
449 for (h = 0; h < 24; h++) {
450 if (!c->hour[h]) continue;
451 for (m = 0; m < 60; m++) {
452 char t[8];
453 if (!c->min[m]) continue;
454 snprintf(t, sizeof(t), "%s%02d:%02d", first ? "" : ", ", h, m);
455 sapp(out, sz, t);
456 first = 0;
457 }
458 }
459 return;
460 }
461 if (nm == 1 && nh < 24) {
462 int h, first = 1;
463 char buf[256];
464 snprintf(buf, sizeof(buf), "At minute %d past hour%s ",
465 first_set(c->min, 0, 59), nh == 1 ? "" : "s");
466 for (h = 0; h < 24; h++) {
467 char t[8];
468 if (!c->hour[h]) continue;
469 snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", h);
470 sapp(buf, sizeof(buf), t);
471 first = 0;
472 }
473 str_copy(out, sz, buf);
474 return;
475 }
476 snprintf(out, sz, "At %d times a day", nm * nh);
477}
478
479static void cron_describe(const cron_t *cc, char *out, size_t sz)
480{
481 cron_t c = *cc;
482 char day[128];
483
484 out[0] = '\0';
485 day[0] = '\0';
486
487 if (c.keyword[0]) {
488 if (strcmp(c.keyword, "@reboot") == 0)
489 str_copy(out, sz, "When the system starts");
490 else if (strcmp(c.keyword, "@hourly") == 0)
491 str_copy(out, sz, "Every hour, on the hour");
492 else if (strcmp(c.keyword, "@daily") == 0 || strcmp(c.keyword, "@midnight") == 0)
493 str_copy(out, sz, "Every day at midnight");
494 else if (strcmp(c.keyword, "@weekly") == 0)
495 str_copy(out, sz, "Every Sunday at midnight");
496 else if (strcmp(c.keyword, "@monthly") == 0)
497 str_copy(out, sz, "The 1st of every month at midnight");
498 else if (strcmp(c.keyword, "@yearly") == 0 || strcmp(c.keyword, "@annually") == 0)
499 str_copy(out, sz, "1 January at midnight");
500 else
501 str_copy(out, sz, "Custom schedule");
502 return;
503 }
504
505 cron_describe_time(&c, out, sz);
506
507 /* month restriction */
508 if (!field_is_full(c.mon, 1, 12)) {
509 int n = count_set(c.mon, 1, 12);
510 int i;
511 if (n == 1) {
512 snprintf(day, sizeof(day), "in %s", k_mon_long[first_set(c.mon, 1, 12) - 1]);
513 } else {
514 int first = 1;
515 sapp(day, sizeof(day), "in ");
516 for (i = 1; i <= 12; i++) {
517 if (!c.mon[i]) continue;
518 sapp(day, sizeof(day), first ? "" : ", ");
519 sapp(day, sizeof(day), k_mon_long[i - 1]);
520 first = 0;
521 }
522 }
523 }
524
525 /* day-of-month / day-of-week (classic OR semantics when both restricted) */
526 if (c.dom_restricted && c.dow_restricted) {
527 int ndow = count_set(c.dow, 0, 6);
528 int ndom = count_set(c.dom, 1, 31);
529 char part[96];
530 part[0] = '\0';
531 if (ndow == 1) {
532 sapp(part, sizeof(part), k_dow_long[first_set(c.dow, 0, 6)]);
533 } else {
534 int i, first = 1;
535 for (i = 0; i < 7; i++) {
536 if (!c.dow[i]) continue;
537 sapp(part, sizeof(part), first ? "" : ", ");
538 sapp(part, sizeof(part), k_dow_long[i]);
539 first = 0;
540 }
541 }
542 sapp(day, sizeof(day), day[0] ? " " : "");
543 sapp(day, sizeof(day), "on ");
544 sapp(day, sizeof(day), part);
545 if (ndom == 1) {
546 char t[32];
547 snprintf(t, sizeof(t), " or day %d of the month", first_set(c.dom, 1, 31));
548 sapp(day, sizeof(day), t);
549 } else {
550 sapp(day, sizeof(day), " or on selected days of the month");
551 }
552 } else if (c.dow_restricted) {
553 int ndow = count_set(c.dow, 0, 6);
554 sapp(day, sizeof(day), day[0] ? " " : "");
555 sapp(day, sizeof(day), "on ");
556 if (ndow == 1) {
557 sapp(day, sizeof(day), k_dow_long[first_set(c.dow, 0, 6)]);
558 } else {
559 int i, first = 1;
560 for (i = 0; i < 7; i++) {
561 if (!c.dow[i]) continue;
562 sapp(day, sizeof(day), first ? "" : ", ");
563 sapp(day, sizeof(day), k_dow_long[i]);
564 first = 0;
565 }
566 }
567 } else if (c.dom_restricted) {
568 int ndom = count_set(c.dom, 1, 31);
569 sapp(day, sizeof(day), day[0] ? " " : "");
570 if (ndom == 1) {
571 char t[32];
572 snprintf(t, sizeof(t), "on day %d of the month", first_set(c.dom, 1, 31));
573 sapp(day, sizeof(day), t);
574 } else if (c.f[2][0] == '*' && c.f[2][1] == '/') {
575 char t[48];
576 snprintf(t, sizeof(t), "every %d days of the month", atoi(c.f[2] + 2));
577 sapp(day, sizeof(day), t);
578 } else {
579 int i, first = 1;
580 sapp(day, sizeof(day), "on days ");
581 for (i = 1; i <= 31; i++) {
582 char t[8];
583 if (!c.dom[i]) continue;
584 snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", i);
585 sapp(day, sizeof(day), t);
586 first = 0;
587 }
588 sapp(day, sizeof(day), " of the month");
589 }
590 }
591
592 if (day[0]) {
593 char full[MAX_DESC];
594 snprintf(full, sizeof(full), "%s, %s", out, day);
595 str_copy(out, sz, full);
596 } else if (strncmp(out, "At ", 3) == 0) {
597 sapp(out, sz, ", every day");
598 }
599}
600/* ---------------------------------------------------------------- */
601/* Expression parsing */
602/* ---------------------------------------------------------------- */
603
604static void apply_keyword(cron_t *c, const char *kw)
605{
606 int i;
607 for (i = 0; i < 60; i++) c->min[i] = 1;
608 for (i = 0; i < 24; i++) c->hour[i] = 1;
609 for (i = 0; i <= 31; i++) c->dom[i] = 1;
610 for (i = 0; i <= 12; i++) c->mon[i] = 1;
611 for (i = 0; i < 7; i++) c->dow[i] = 1;
612
613 if (strcmp(kw, "@reboot") == 0) {
614 c->boot_only = 1;
615 return;
616 }
617 memset(c->min, 0, sizeof(c->min));
618 c->min[0] = 1;
619 if (strcmp(kw, "@hourly") == 0) {
620 memset(c->hour, 0, sizeof(c->hour));
621 for (i = 0; i < 24; i++) c->hour[i] = 1;
622 return;
623 }
624 memset(c->hour, 0, sizeof(c->hour));
625 c->hour[0] = 1;
626 if (strcmp(kw, "@daily") == 0 || strcmp(kw, "@midnight") == 0) return;
627 if (strcmp(kw, "@weekly") == 0) {
628 memset(c->dow, 0, sizeof(c->dow));
629 c->dow[0] = 1;
630 c->dow_restricted = 1;
631 return;
632 }
633 if (strcmp(kw, "@monthly") == 0) {
634 memset(c->dom, 0, sizeof(c->dom));
635 c->dom[1] = 1;
636 c->dom_restricted = 1;
637 return;
638 }
639 if (strcmp(kw, "@yearly") == 0 || strcmp(kw, "@annually") == 0) {
640 memset(c->dom, 0, sizeof(c->dom));
641 memset(c->mon, 0, sizeof(c->mon));
642 c->dom[1] = 1;
643 c->mon[1] = 1;
644 c->dom_restricted = 1;
645 return;
646 }
647 /* continue for @hourly handled above */
648}
649
650/*
651 * Parse a full cron expression: either "@keyword" or five whitespace-separated
652 * fields. Fills c->valid / c->error. Returns c->valid.
653 * The expression is trimmed in place into c->raw.
654 */
655static int cron_parse(cron_t *c, const char *expr)
656{
657 char work[MAX_EXPR * 2];
658 char *tok[8];
659 int ntok = 0;
660 int rc;
661 char *p;
662
663 cron_clear(c);
664 str_copy(c->raw, sizeof(c->raw), expr ? expr : "");
665 str_copy(work, sizeof(work), c->raw);
666 str_trim(work);
667
668 if (!work[0]) {
669 str_copy(c->error, sizeof(c->error), "empty expression");
670 return 0;
671 }
672
673 if (work[0] == '@') {
674 char kw[24];
675 str_copy(kw, sizeof(kw), work);
676 str_trim(kw);
677 if (strcmp(kw, "@reboot") != 0 && strcmp(kw, "@hourly") != 0
678 && strcmp(kw, "@daily") != 0 && strcmp(kw, "@midnight") != 0
679 && strcmp(kw, "@weekly") != 0 && strcmp(kw, "@monthly") != 0
680 && strcmp(kw, "@yearly") != 0 && strcmp(kw, "@annually") != 0) {
681 str_copy(c->error, sizeof(c->error), "unknown @keyword");
682 return 0;
683 }
684 str_copy(c->keyword, sizeof(c->keyword), kw);
685 apply_keyword(c, kw);
686 c->dom_restricted = c->dom_restricted || 0;
687 c->valid = 1;
688 cron_describe(c, c->desc, sizeof(c->desc));
689 return 1;
690 }
691
692 for (p = work; *p && ntok < 8; ) {
693 while (*p && isspace((unsigned char)*p)) *p++ = '\0';
694 if (!*p) break;
695 tok[ntok++] = p;
696 while (*p && !isspace((unsigned char)*p)) p++;
697 }
698 if (ntok != 5) {
699 str_copy(c->error, sizeof(c->error),
700 ntok < 5 ? "expected 5 fields" : "too many fields");
701 return 0;
702 }
703
704 {
705 int i;
706 for (i = 0; i < 5; i++) str_copy(c->f[i], sizeof(c->f[i]), tok[i]);
707 }
708
709 rc = parse_field(c->f[0], 0, 59, NULL, 0, 0, c->min);
710 if (rc <= 0) {
711 str_copy(c->error, sizeof(c->error), rc < 0 ? "minute out of range 0-59" : "bad minute field");
712 return 0;
713 }
714 rc = parse_field(c->f[1], 0, 23, NULL, 0, 0, c->hour);
715 if (rc <= 0) {
716 str_copy(c->error, sizeof(c->error), rc < 0 ? "hour out of range 0-23" : "bad hour field");
717 return 0;
718 }
719 rc = parse_field(c->f[2], 1, 31, NULL, 0, 0, c->dom);
720 if (rc <= 0) {
721 str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-month out of range 1-31" : "bad day-of-month field");
722 return 0;
723 }
724 rc = parse_field(c->f[3], 1, 12, k_mon_names, 12, 1, c->mon);
725 if (rc <= 0) {
726 str_copy(c->error, sizeof(c->error), rc < 0 ? "month out of range 1-12" : "bad month field");
727 return 0;
728 }
729 {
730 unsigned char tmpdow[8];
731 int i;
732 rc = parse_field(c->f[4], 0, 7, k_dow_names, 7, 0, tmpdow);
733 if (rc <= 0) {
734 str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-week out of range 0-7" : "bad day-of-week field");
735 return 0;
736 }
737 memset(c->dow, 0, sizeof(c->dow));
738 for (i = 0; i <= 7; i++)
739 if (tmpdow[i]) c->dow[i % 7] = 1;
740 }
741
742 c->dom_restricted = !field_is_full(c->dom, 1, 31);
743 c->dow_restricted = !field_is_full(c->dow, 0, 6);
744
745 c->valid = 1;
746 cron_describe(c, c->desc, sizeof(c->desc));
747 return 1;
748}
749
750/* Day-of-week for a broken-down UTC time; 0 == Sunday. */
751static int tm_dow(const struct tm *t)
752{
753 return t->tm_wday;
754}
755
756static int day_matches(const cron_t *c, const struct tm *day)
757{
758 int dom_ok = c->dom[day->tm_mday] ? 1 : 0;
759 int dow_ok = c->dow[tm_dow(day)] ? 1 : 0;
760
761 if (!c->mon[day->tm_mon + 1]) return 0;
762 if (c->dom_restricted && c->dow_restricted) return dom_ok || dow_ok;
763 if (c->dom_restricted) return dom_ok;
764 if (c->dow_restricted) return dow_ok;
765 return 1;
766}
767
768/*
769 * Compute the next `want` firing times strictly after `from` (UTC).
770 * Iterates day by day, then within matching days iterates hours and minutes
771 * using the parsed bitmaps. Returns the number of timestamps written.
772 */
773static int cron_next_runs(const cron_t *c, time_t from, time_t *out, int want)
774{
775 struct tm base;
776 int got = 0;
777 int d;
778
779 if (!c->valid || c->boot_only) return 0;
780
781 {
782 time_t t = from;
783#if defined(_WIN32)
784 gmtime_s(&base, &t);
785#else
786 gmtime_r(&t, &base);
787#endif
788 }
789
790 for (d = 0; d < HORIZON_DAYS && got < want; d++) {
791 struct tm day;
792 time_t day_start;
793 int h, m;
794
795 day = base;
796 day.tm_mday += d;
797 day.tm_hour = 0;
798 day.tm_min = 0;
799 day.tm_sec = 0;
800 day.tm_isdst = 0;
801 day_start = timegm_portable(&day);
802 if (day_start == (time_t)-1) continue;
803#if defined(_WIN32)
804 gmtime_s(&day, &day_start);
805#else
806 gmtime_r(&day_start, &day);
807#endif
808 if (!day_matches(c, &day)) continue;
809
810 for (h = 0; h < 24 && got < want; h++) {
811 if (!c->hour[h]) continue;
812 for (m = 0; m < 60 && got < want; m++) {
813 time_t cand;
814 if (!c->min[m]) continue;
815 cand = day_start + (time_t)h * 3600 + (time_t)m * 60;
816 if (cand <= from) continue;
817 out[got++] = cand;
818 }
819 }
820 }
821 return got;
822}
823/* ---------------------------------------------------------------- */
824/* Job collection */
825/* ---------------------------------------------------------------- */
826
827typedef struct {
828 char source[MAX_SRC];
829 char expr[MAX_EXPR];
830 char command[MAX_CMD];
831 char user[64];
832 char kind[12]; /* "cron" or "task" */
833 int valid;
834 char error[96];
835 char desc[MAX_DESC];
836 int next_count;
837 time_t next[MAX_RUNS];
838} job_t;
839
840static job_t g_jobs[MAX_JOBS];
841static int g_job_count;
842static char g_sources[16][MAX_SRC];
843static int g_source_count;
844static int g_truncated;
845
846static void note_source(const char *name)
847{
848 int i;
849 if (!name || !*name) return;
850 for (i = 0; i < g_source_count; i++)
851 if (strcmp(g_sources[i], name) == 0) return;
852 if (g_source_count < (int)(sizeof(g_sources) / sizeof(g_sources[0])))
853 str_copy(g_sources[g_source_count++], MAX_SRC, name);
854}
855
856static job_t *job_new(void)
857{
858 job_t *j;
859 if (g_job_count >= MAX_JOBS) { g_truncated = 1; return NULL; }
860 j = &g_jobs[g_job_count++];
861 memset(j, 0, sizeof(*j));
862 return j;
863}
864
865/* Skip blank lines, comments and environment assignments. */
866static int cron_line_skippable(const char *s)
867{
868 const char *p;
869
870 if (!s) return 1;
871 while (*s && isspace((unsigned char)*s)) s++;
872 if (!*s) return 1;
873 if (*s == '#') return 1;
874 /* NAME = value (no whitespace inside the name) */
875 for (p = s; *p && (isalnum((unsigned char)*p) || *p == '_'); p++) ;
876 if (p > s && *p == '=') return 1;
877 return 0;
878}
879
880/*
881 * Split one crontab line into an expression and a command.
882 * system format: 5 fields, user, command (/etc/crontab, /etc/cron.d entries)
883 * user format: 5 fields, command (crontab -l)
884 * Returns 1 on success.
885 */
886static int split_cron_line(const char *line, int system_format,
887 char *expr, size_t expr_sz,
888 char *user, size_t user_sz,
889 char *cmd, size_t cmd_sz)
890{
891 char work[READ_LINE];
892 char *p;
893 int fields_needed = system_format ? 6 : 5;
894 int got = 0;
895
896 expr[0] = user[0] = cmd[0] = '\0';
897 str_copy(work, sizeof(work), line);
898 str_trim(work);
899 if (!work[0]) return 0;
900
901 /* @keyword form */
902 if (work[0] == '@') {
903 p = work;
904 while (*p && !isspace((unsigned char)*p)) p++;
905 str_copy(expr, expr_sz, work);
906 expr[strlen(work) - strlen(p) >= expr_sz ? expr_sz - 1 : strlen(work) - strlen(p)] = '\0';
907 if (*p) {
908 char *rest = p;
909 while (*rest && isspace((unsigned char)*rest)) rest++;
910 if (system_format) {
911 char *u = rest;
912 while (*u && !isspace((unsigned char)*u)) u++;
913 str_copy(user, user_sz, rest);
914 user[strlen(rest) - strlen(u) >= user_sz ? user_sz - 1 : strlen(rest) - strlen(u)] = '\0';
915 while (*u && isspace((unsigned char)*u)) u++;
916 str_copy(cmd, cmd_sz, u);
917 } else {
918 str_copy(cmd, cmd_sz, rest);
919 }
920 }
921 return 1;
922 }
923
924 p = work;
925 while (*p && got < fields_needed) {
926 char *start;
927 while (*p && isspace((unsigned char)*p)) p++;
928 if (!*p) break;
929 start = p;
930 while (*p && !isspace((unsigned char)*p)) p++;
931 if (got < 5) {
932 size_t len = (size_t)(p - start);
933 size_t have = strlen(expr);
934 if (have + len + 2 < expr_sz) {
935 if (have) expr[have++] = ' ';
936 memcpy(expr + have, start, len);
937 expr[have + len] = '\0';
938 }
939 } else {
940 size_t len = (size_t)(p - start);
941 if (len >= user_sz) len = user_sz - 1;
942 memcpy(user, start, len);
943 user[len] = '\0';
944 }
945 got++;
946 }
947 if (got < fields_needed) return 0;
948 while (*p && isspace((unsigned char)*p)) p++;
949 str_copy(cmd, cmd_sz, p);
950 return 1;
951}
952
953static void add_cron_job(const char *source, const char *line, int system_format, time_t now)
954{
955 char expr[MAX_EXPR], user[64], cmd[MAX_CMD];
956 job_t *j;
957
958 if (!split_cron_line(line, system_format, expr, sizeof(expr),
959 user, sizeof(user), cmd, sizeof(cmd)))
960 return;
961 if (!expr[0]) return;
962
963 j = job_new();
964 if (!j) return;
965
966 str_copy(j->source, sizeof(j->source), source);
967 str_copy(j->expr, sizeof(j->expr), expr);
968 str_copy(j->command, sizeof(j->command), cmd);
969 str_copy(j->user, sizeof(j->user), user);
970 str_copy(j->kind, sizeof(j->kind), "cron");
971
972 {
973 cron_t c;
974 if (cron_parse(&c, expr)) {
975 j->valid = 1;
976 str_copy(j->desc, sizeof(j->desc), c.desc);
977 if (c.boot_only)
978 str_copy(j->desc, sizeof(j->desc), "When the system starts (no scheduled times)");
979 else
980 j->next_count = cron_next_runs(&c, now, j->next, MAX_RUNS);
981 } else {
982 j->valid = 0;
983 str_copy(j->error, sizeof(j->error), c.error);
984 str_copy(j->desc, sizeof(j->desc), "Unrecognised schedule expression");
985 }
986 }
987 note_source(source);
988}
989
990#if defined(_WIN32)
991static void add_task_job(const char *name, const char *nextrun, const char *status, time_t now)
992{
993 job_t *j = job_new();
994 (void)now;
995 if (!j) return;
996
997 str_copy(j->source, sizeof(j->source), "schtasks");
998 str_copy(j->kind, sizeof(j->kind), "task");
999 str_copy(j->expr, sizeof(j->expr), "task");
1000 str_copy(j->command, sizeof(j->command), name);
1001 str_copy(j->user, sizeof(j->user), "");
1002 j->valid = 1;
1003 {
1004 char d[MAX_DESC];
1005 snprintf(d, sizeof(d), "%s%s%s",
1006 status && *status ? status : "Scheduled Windows task",
1007 nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? " - next " : "",
1008 nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? nextrun : "");
1009 str_copy(j->desc, sizeof(j->desc), d);
1010 }
1011 note_source("schtasks");
1012}
1013
1014#endif
1015
1016/* Feed a whole file (or popen stream) of crontab lines. */
1017static void ingest_lines(FILE *fp, const char *source, int system_format, time_t now)
1018{
1019 char line[READ_LINE];
1020 int forced = system_format;
1021
1022 while (fp && fgets(line, sizeof(line), fp)) {
1023 char probe[READ_LINE];
1024 size_t n = strlen(line);
1025 while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0';
1026 str_copy(probe, sizeof(probe), line);
1027 str_trim(probe);
1028
1029 /* fixture directives: "# sx:system" / "# sx:user" / "# sx:source NAME" */
1030 if (strncmp(probe, "# sx:", 5) == 0) {
1031 const char *d = probe + 5;
1032 if (strncmp(d, "system", 6) == 0) { forced = 1; continue; }
1033 if (strncmp(d, "user", 4) == 0) { forced = 0; continue; }
1034 continue;
1035 }
1036 if (cron_line_skippable(line)) continue;
1037 add_cron_job(source, line, forced, now);
1038 }
1039}
1040
1041static void ingest_file(const char *path, const char *source, int system_format, time_t now)
1042{
1043 FILE *fp = fopen(path, "r");
1044 if (!fp) return;
1045 ingest_lines(fp, source, system_format, now);
1046 fclose(fp);
1047}
1048
1049#if !defined(_WIN32)
1050static void ingest_command(const char *cmd, const char *source, time_t now)
1051{
1052 FILE *fp = sx_popen(cmd, "r");
1053 if (!fp) return;
1054 ingest_lines(fp, source, 0, now);
1055 sx_pclose(fp);
1056}
1057#endif
1058
1059#if defined(_WIN32)
1060/* Minimal CSV field splitter for `schtasks /Query /FO CSV`. */
1061static void ingest_schtasks(time_t now)
1062{
1063 FILE *fp = sx_popen("schtasks /Query /FO CSV /NH", "r");
1064 char line[READ_LINE];
1065
1066 if (!fp) return;
1067 while (fgets(line, sizeof(line), fp)) {
1068 char f[4][256];
1069 int nf = 0;
1070 char *p = line;
1071 size_t n = strlen(line);
1072 while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0';
1073
1074 while (*p && nf < 4) {
1075 char *out = f[nf];
1076 size_t oi = 0;
1077 if (*p == '"') {
1078 p++;
1079 while (*p && *p != '"' && oi + 1 < 256) {
1080 if (*p == '"' && p[1] == '"') { out[oi++] = '"'; p += 2; continue; }
1081 out[oi++] = *p++;
1082 }
1083 if (*p == '"') p++;
1084 } else {
1085 while (*p && *p != ',' && oi + 1 < 256) out[oi++] = *p++;
1086 }
1087 out[oi] = '\0';
1088 nf++;
1089 if (*p == ',') p++;
1090 }
1091 if (nf >= 2 && f[0][0] && strcmp(f[0], "TaskName") != 0)
1092 add_task_job(f[0], f[1], nf > 2 ? f[2] : "", now);
1093 }
1094 sx_pclose(fp);
1095}
1096#endif
1097
1098static void collect_jobs(void)
1099{
1100 time_t now = time(NULL);
1101 const char *fixture = getenv("CRONTAB_FILE");
1102
1103 g_job_count = 0;
1104 g_source_count = 0;
1105 g_truncated = 0;
1106
1107 if (fixture && *fixture) {
1108 ingest_file(fixture, "fixture", 0, now);
1109 return;
1110 }
1111
1112#if defined(_WIN32)
1113 ingest_schtasks(now);
1114#else
1115 ingest_command("crontab -l 2>/dev/null", "user", now);
1116 ingest_file("/etc/crontab", "/etc/crontab", 1, now);
1117 {
1118 DIR *d = opendir("/etc/cron.d");
1119 struct dirent *ent;
1120 if (d) {
1121 while ((ent = readdir(d)) != NULL) {
1122 char path[512];
1123 char label[MAX_SRC];
1124 if (ent->d_name[0] == '.') continue;
1125 snprintf(path, sizeof(path), "/etc/cron.d/%s", ent->d_name);
1126 snprintf(label, sizeof(label), "/etc/cron.d/%.40s", ent->d_name);
1127 ingest_file(path, label, 1, now);
1128 }
1129 closedir(d);
1130 }
1131 }
1132#endif
1133}
1134/* ---------------------------------------------------------------- */
1135/* HTTP plumbing */
1136/* ---------------------------------------------------------------- */
1137
1138static void json_header(void)
1139{
1140 fputs("Content-Type: application/json; charset=utf-8\r\n"
1141 "Cache-Control: no-store\r\n"
1142 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1143}
1144
1145static void print_runs(const time_t *runs, int count, time_t now)
1146{
1147 int i;
1148 char utc[40], loc[40];
1149
1150 putchar('[');
1151 for (i = 0; i < count; i++) {
1152 utc_stamp(runs[i], utc, sizeof(utc));
1153 local_stamp(runs[i], loc, sizeof(loc));
1154 if (i) putchar(',');
1155 fputs("{\"utc\":", stdout);
1156 json_str(utc);
1157 fputs(",\"local\":", stdout);
1158 json_str(loc);
1159 printf(",\"in_seconds\":%ld}", (long)(runs[i] - now));
1160 }
1161 putchar(']');
1162}
1163
1164static int mode_meta(void)
1165{
1166 fputs("{\"name\":\"crontab\",\"desc\":\"Cron jobs\"}\n", stdout);
1167 return 0;
1168}
1169
1170/* Field text for a keyword schedule, for the JSON fields block. */
1171static void cron_keyword_fields(const cron_t *c, char kf[5][12])
1172{
1173 if (!c->keyword[0]) {
1174 int i;
1175 for (i = 0; i < 5; i++) str_copy(kf[i], 12, c->f[i]);
1176 return;
1177 }
1178 str_copy(kf[0], 12, "0");
1179 str_copy(kf[1], 12, "0");
1180 str_copy(kf[2], 12, "*");
1181 str_copy(kf[3], 12, "*");
1182 str_copy(kf[4], 12, "*");
1183 if (strcmp(c->keyword, "@reboot") == 0) {
1184 int i;
1185 for (i = 0; i < 5; i++) str_copy(kf[i], 12, "@reboot");
1186 } else if (strcmp(c->keyword, "@hourly") == 0) {
1187 str_copy(kf[1], 12, "*");
1188 } else if (strcmp(c->keyword, "@weekly") == 0) {
1189 str_copy(kf[4], 12, "0");
1190 } else if (strcmp(c->keyword, "@monthly") == 0) {
1191 str_copy(kf[2], 12, "1");
1192 } else if (strcmp(c->keyword, "@yearly") == 0 || strcmp(c->keyword, "@annually") == 0) {
1193 str_copy(kf[2], 12, "1");
1194 str_copy(kf[3], 12, "1");
1195 }
1196}
1197
1198static int mode_json(const char *qs)
1199{
1200 char action[64];
1201 char expr[MAX_EXPR * 2];
1202 time_t now = time(NULL);
1203
1204 action[0] = '\0';
1205 get_query_val(qs, "action", action, sizeof(action));
1206
1207 json_header();
1208
1209 if (strcmp(action, "explain") == 0) {
1210 cron_t c;
1211 time_t runs[MAX_RUNS];
1212 int n = 0;
1213 char nowutc[40];
1214 char nowloc[40];
1215
1216 get_query_val(qs, "expr", expr, sizeof(expr));
1217 utc_stamp(now, nowutc, sizeof(nowutc));
1218 local_stamp(now, nowloc, sizeof(nowloc));
1219
1220 if (!expr[0]) {
1221 fputs("{\"ok\":false,\"error\":\"missing expr parameter\",\"valid\":false}\n", stdout);
1222 return 0;
1223 }
1224
1225 if (cron_parse(&c, expr)) {
1226 if (!c.boot_only) n = cron_next_runs(&c, now, runs, MAX_RUNS);
1227 } else {
1228 fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout);
1229 json_str(expr);
1230 fputs(",\"valid\":false,\"error\":", stdout);
1231 json_str(c.error[0] ? c.error : "invalid expression");
1232 fputs(",\"description\":\"\",\"keyword\":\"\",\"next\":[],"
1233 "\"now_utc\":", stdout);
1234 json_str(nowutc);
1235 fputs(",\"now_local\":", stdout);
1236 json_str(nowloc);
1237 fputs("}\n", stdout);
1238 return 0;
1239 }
1240
1241 fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout);
1242 json_str(expr);
1243 fputs(",\"valid\":true,\"keyword\":", stdout);
1244 json_str(c.keyword);
1245 fputs(",\"description\":", stdout);
1246 json_str(c.desc);
1247 fputs(",\"normalized\":", stdout);
1248 if (c.keyword[0]) {
1249 json_str(c.keyword);
1250 } else {
1251 char norm[220];
1252 snprintf(norm, sizeof(norm), "%s %s %s %s %s",
1253 c.f[0], c.f[1], c.f[2], c.f[3], c.f[4]);
1254 json_str(norm);
1255 }
1256 {
1257 char kf[5][12];
1258 cron_keyword_fields(&c, kf);
1259 fputs(",\"fields\":{\"minute\":", stdout); json_str(kf[0]);
1260 fputs(",\"hour\":", stdout); json_str(kf[1]);
1261 fputs(",\"day_of_month\":", stdout); json_str(kf[2]);
1262 fputs(",\"month\":", stdout); json_str(kf[3]);
1263 fputs(",\"day_of_week\":", stdout); json_str(kf[4]);
1264 }
1265 fputs("},\"boot_only\":", stdout); fputs(c.boot_only ? "true" : "false", stdout);
1266 fputs(",\"now_utc\":", stdout); json_str(nowutc);
1267 fputs(",\"now_local\":", stdout); json_str(nowloc);
1268 fputs(",\"next\":", stdout);
1269 print_runs(runs, n, now);
1270 putchar('}');
1271 putchar('\n');
1272 return 0;
1273 }
1274
1275 if (strcmp(action, "jobs") == 0 || strcmp(action, "list") == 0 || !action[0]) {
1276 char nowutc[40], nowloc[40];
1277 int i;
1278
1279 collect_jobs();
1280 utc_stamp(now, nowutc, sizeof(nowutc));
1281 local_stamp(now, nowloc, sizeof(nowloc));
1282
1283 fputs("{\"ok\":true,\"action\":\"jobs\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"", stdout);
1284 fputs(",\"now_utc\":", stdout); json_str(nowutc);
1285 fputs(",\"now_local\":", stdout); json_str(nowloc);
1286 printf(",\"count\":%d,\"truncated\":%s", g_job_count, g_truncated ? "true" : "false");
1287 fputs(",\"sources\":[", stdout);
1288 for (i = 0; i < g_source_count; i++) {
1289 if (i) putchar(',');
1290 json_str(g_sources[i]);
1291 }
1292 fputs("],\"jobs\":[", stdout);
1293 for (i = 0; i < g_job_count; i++) {
1294 const job_t *j = &g_jobs[i];
1295 if (i) putchar(',');
1296 fputs("{\"source\":", stdout); json_str(j->source);
1297 fputs(",\"kind\":", stdout); json_str(j->kind);
1298 fputs(",\"expr\":", stdout); json_str(j->expr);
1299 fputs(",\"command\":", stdout); json_str(j->command);
1300 fputs(",\"user\":", stdout); json_str(j->user);
1301 printf(",\"valid\":%s", j->valid ? "true" : "false");
1302 if (!j->valid) {
1303 fputs(",\"error\":", stdout);
1304 json_str(j->error);
1305 }
1306 fputs(",\"description\":", stdout);
1307 json_str(j->desc);
1308 fputs(",\"next\":", stdout);
1309 print_runs(j->next, j->next_count, now);
1310 putchar('}');
1311 }
1312 fputs("]}\n", stdout);
1313 return 0;
1314 }
1315
1316 if (strcmp(action, "info") == 0) {
1317 fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\""
1318 ",\"slug\":\"" PLUGIN_SLUG "\",\"license\":\"MIT\",\"read_only\":true"
1319 ",\"actions\":[\"jobs\",\"explain\",\"info\"]"
1320 ",\"capabilities\":[\"crontab_read\",\"cron_parse\"]"
1321 ",\"trust_notice\":\"Executes native C code on your node. Reads crontab listings and task lists; never writes a schedule and never runs a scheduled command. Makes zero outbound network requests.\"}\n",
1322 stdout);
1323 return 0;
1324 }
1325
1326 fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout);
1327 return 0;
1328}
1329
1330static void require_node_auth(void)
1331{
1332 const char *np = getenv("BOT_PASSWORD");
1333 const char *xp;
1334 const char *auth;
1335 const char *qs;
1336 char qpwd[256];
1337
1338 if (!np || !*np) return;
1339
1340 xp = getenv("HTTP_X_BOT_PASSWORD");
1341 if (xp && strcmp(xp, np) == 0) return;
1342
1343 auth = getenv("HTTP_AUTHORIZATION");
1344 if (auth) {
1345 while (*auth == ' ') auth++;
1346 if (strncmp(auth, "Bearer ", 7) == 0) {
1347 auth += 7;
1348 while (*auth == ' ') auth++;
1349 if (strcmp(auth, np) == 0) return;
1350 }
1351 }
1352
1353 qs = getenv("QUERY_STRING");
1354 if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
1355 return;
1356
1357 fputs("Status: 401 Unauthorized\r\n"
1358 "Content-Type: application/json; charset=utf-8\r\n"
1359 "Cache-Control: no-store\r\n"
1360 "X-Content-Type-Options: nosniff\r\n\r\n"
1361 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
1362 exit(0);
1363}
1364/* ---------------------------------------------------------------- */
1365/* HTML UI */
1366/* ---------------------------------------------------------------- */
1367
1368static void html_head(int embed)
1369{
1370 fputs("Content-Type: text/html; charset=utf-8\r\n"
1371 "Cache-Control: no-store\r\n"
1372 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1373
1374 fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>"
1375 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
1376 "<title>crontab</title>", stdout);
1377
1378 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout);
1379 fputs(
1380"*{box-sizing:border-box}"
1381"body{margin:0;padding:16px;background:var(--bg);color:var(--text);"
1382"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;"
1383"line-height:1.5;-webkit-font-smoothing:antialiased}"
1384".wrap{max-width:1120px;margin:0 auto}"
1385".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}"
1386".title{font-size:20px;font-weight:700;margin:0}"
1387".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;"
1388"background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}"
1389".pill.on{color:var(--accent2);border-color:rgba(48,209,88,.4)}"
1390".pill.off{color:var(--danger);border-color:rgba(255,69,58,.4)}"
1391".spacer{flex:1}"
1392".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;"
1393"padding:16px;margin-bottom:14px}"
1394".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;"
1395"color:var(--muted);font-weight:600}"
1396".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}"
1397".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}"
1398".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}"
1399".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px}"
1400"button{background:var(--accent);color:#fff;border:0;border-radius:999px;padding:7px 14px;"
1401"font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}"
1402"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}"
1403"button.sm{padding:4px 10px;font-size:12px}"
1404"button:active{transform:scale(.98)}"
1405"input{background:var(--surface2);border:1px solid var(--line);border-radius:10px;"
1406"padding:9px 12px;color:var(--text);font-size:13px;font-family:var(--mono);width:100%}"
1407"input:focus{outline:2px solid var(--accent);outline-offset:-1px}"
1408".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}"
1409".tblwrap{overflow-x:auto}"
1410"table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}"
1411"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);"
1412"font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);white-space:nowrap}"
1413"td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}"
1414"td.mono{font-family:var(--mono);font-size:12px}"
1415".cmd{font-family:var(--mono);font-size:12px;color:var(--muted);word-break:break-all;max-width:340px}"
1416".src{font-size:11px;color:var(--muted);font-family:var(--mono)}"
1417".in{font-size:12px;font-weight:600;color:var(--accent2);font-family:var(--mono);white-space:nowrap}"
1418".err{font-size:12px;color:var(--danger)}"
1419".muted{color:var(--muted)}"
1420".empty{padding:22px 8px;text-align:center;color:var(--muted)}"
1421".hide{display:none}"
1422".play{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center}"
1423".runs{margin-top:12px;display:grid;gap:6px}"
1424".run{display:flex;gap:10px;align-items:baseline;background:var(--surface2);"
1425"border:1px solid var(--line);border-radius:10px;padding:8px 12px;font-family:var(--mono);font-size:12px}"
1426".run .n{color:var(--muted);width:18px;flex:none}"
1427".run .u{font-weight:600}"
1428".run .l{color:var(--muted);margin-left:auto}"
1429"@media(max-width:640px){body{padding:10px}.card{padding:12px}"
1430".play{grid-template-columns:1fr}"
1431"th:nth-child(1),td:nth-child(1),th:nth-child(5),td:nth-child(5){display:none}"
1432"td{padding:8px 4px}th{padding:6px 4px}.cmd{max-width:none}}"
1433"</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout);
1434
1435 if (!embed)
1436 fputs("<div class='top'><a href='/' style='color:var(--accent);text-decoration:none;"
1437 "font-weight:600'>&#8592; Back to Bot</a></div>", stdout);
1438}
1439
1440static void html_body(void)
1441{
1442 fputs("<div class='top'><h1 class='title'>crontab</h1>"
1443 "<span class='pill'>" PLUGIN_VER "</span>"
1444 "<span class='pill' id='badge'>loading</span>"
1445 "<span class='spacer'></span>"
1446 "<button class='ghost embed-hide' id='themeBtn' type='button'>Theme</button>"
1447 "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>",
1448
1449 stdout);
1450
1451 /* KPIs */
1452 fputs("<div class='card'><h2>Schedule overview</h2><div class='grid'>"
1453 "<div class='kpi'><div class='k'>jobs</div><div class='v' id='k-total'>&mdash;</div></div>"
1454 "<div class='kpi'><div class='k'>parsed</div><div class='v' id='k-valid'>&mdash;</div></div>"
1455 "<div class='kpi'><div class='k'>next run</div><div class='v' id='k-next'>&mdash;</div></div>"
1456 "<div class='kpi'><div class='k'>sources</div><div class='v' id='k-src'>&mdash;</div></div>"
1457 "</div>"
1458 "<div class='row' style='margin-top:12px'>"
1459 "<input id='q' type='text' placeholder='filter by command, source or expression'>"
1460 "</div>"
1461 "<div id='note' class='muted' style='margin-top:10px'></div>"
1462 "<div class='tblwrap'><table><thead><tr>"
1463 "<th>Source</th><th>Schedule</th><th>Meaning</th><th>Next run</th><th>Command</th>"
1464 "</tr></thead><tbody id='rows'></tbody></table></div>"
1465 "<div id='empty' class='empty hide'>No scheduled entries found on this node.</div>"
1466 "</div>", stdout);
1467
1468 /* playground */
1469 fputs("<div class='card'><h2>Cron expression playground</h2>"
1470 "<div class='play'>"
1471 "<input id='ex' type='text' value='*/15 9-17 * * 1-5' spellcheck='false' "
1472 "placeholder='minute hour day-of-month month day-of-week'>"
1473 "<button id='goBtn' type='button'>Explain</button>"
1474 "</div>"
1475 "<div id='exNote' class='muted' style='margin-top:10px'>"
1476 "Accepts standard five-field expressions and @hourly, @daily, @weekly, "
1477 "@monthly, @yearly, @reboot.</div>"
1478 "<div class='runs' id='exRuns'></div></div>", stdout);
1479
1480 fputs("<div class='card'><h2>About this plugin</h2>"
1481 "<p class='muted' style='margin:0 0 8px'>Local node only. Reads "
1482 "<code>crontab -l</code>, <code>/etc/crontab</code> and <code>/etc/cron.d</code> "
1483 "on Linux and macOS, or <code>schtasks</code> on Windows. It is strictly read-only: "
1484 "no schedule is ever written and no scheduled command is ever executed.</p>"
1485 "<p class='muted' style='margin:0'>Set <code>CRONTAB_FILE</code> to inspect a fixture "
1486 "file instead of the live machine. Source is MIT licensed.</p></div>", stdout);
1487
1488 fputs("<script>\n", stdout);
1489 fputs(
1490"(function(){\n"
1491" var q = new URLSearchParams(location.search);\n"
1492" var node = q.get('node') || '';\n"
1493" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n"
1494" localStorage.getItem('bot_active_pwd') || '';\n"
1495" function base(){\n"
1496" var u = location.pathname;\n"
1497" var keep = [];\n"
1498" ['node','plugin','id','embed','pwd'].forEach(function(k){\n"
1499" var v = q.get(k); if (v) keep.push(k + '=' + encodeURIComponent(v));\n"
1500" });\n"
1501" return u + (keep.length ? '?' + keep.join('&') : '');\n"
1502" }\n"
1503" function withCtx(url){\n"
1504" if (!node && !pwd) return url;\n"
1505" return url + (url.indexOf('?') >= 0 ? '&' : '?') +\n"
1506" (node ? 'node=' + encodeURIComponent(node) : '') +\n"
1507" (node && pwd ? '&' : '') + (pwd ? 'pwd=' + encodeURIComponent(pwd) : '');\n"
1508" }\n"
1509" function get(u){\n"
1510" return fetch(withCtx(base() + '?' + u), { headers: { 'Accept':'application/json' } })\n"
1511" .then(function(r){ return r.json(); });\n"
1512" }\n"
1513" function $(id){ return document.getElementById(id); }\n"
1514" function el(tag, cls, text){\n"
1515" var e = document.createElement(tag);\n"
1516" if (cls) e.className = cls;\n"
1517" if (text !== undefined && text !== null) e.textContent = String(text);\n"
1518" return e;\n"
1519" }\n"
1520" function theme(t){ if (t) document.documentElement.setAttribute('data-theme', t); }\n"
1521" if (window.parent && window.parent !== window) {\n"
1522" var vm = q.get('theme') || localStorage.getItem('bot_theme');\n"
1523" if (vm) theme(vm);\n"
1524" } else {\n"
1525" theme(localStorage.getItem('bot_theme') ||\n"
1526" (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));\n"
1527" }\n"
1528" $('themeBtn').addEventListener('click', function(){\n"
1529" var next = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';\n"
1530" theme(next); localStorage.setItem('bot_theme', next);\n"
1531" });\n"
1532" function badge(ok, text){ var b = $('badge'); b.textContent = text; b.className = 'pill ' + (ok ? 'on' : 'off'); }\n"
1533" function human(sec){\n"
1534" if (sec === null || sec === undefined) return 'never';\n"
1535" if (sec < 0) return 'due';\n"
1536" var d = Math.floor(sec / 86400), h = Math.floor(sec % 86400 / 3600),\n"
1537" m = Math.floor(sec % 3600 / 60);\n"
1538" if (d > 0) return d + 'd ' + h + 'h';\n"
1539" if (h > 0) return h + 'h ' + m + 'm';\n"
1540" if (m > 0) return m + 'm';\n"
1541" return '<1m';\n"
1542" }\n"
1543" var DATA = { jobs: [] };\n"
1544" function matches(j){\n"
1545" var k = ($('q').value || '').trim().toLowerCase();\n"
1546" if (!k) return true;\n"
1547" var hay = ((j.command||'') + ' ' + (j.source||'') + ' ' + (j.expr||'') + ' ' + (j.description||'')).toLowerCase();\n"
1548" return hay.indexOf(k) >= 0;\n"
1549" }\n"
1550" function render(){\n"
1551" var tb = $('rows'), shown = 0, soonest = null;\n"
1552" while (tb.firstChild) tb.removeChild(tb.firstChild);\n"
1553" (DATA.jobs || []).forEach(function(j){\n"
1554" if (!matches(j)) return;\n"
1555" shown++;\n"
1556" var tr = el('tr');\n"
1557" tr.appendChild(el('td', 'src', j.source || ''));\n"
1558" tr.appendChild(el('td', 'mono', j.expr || ''));\n"
1559" var tdDesc = el('td');\n"
1560" tdDesc.appendChild(el('div', j.valid ? '' : 'err', j.valid ? (j.description || '') : ('invalid: ' + (j.error || ''))));\n"
1561" tr.appendChild(tdDesc);\n"
1562" var tdNext = el('td');\n"
1563" var n = (j.next && j.next[0]) ? j.next[0] : null;\n"
1564" if (n) {\n"
1565" tdNext.appendChild(el('div', 'in', human(n.in_seconds)));\n"
1566" tdNext.appendChild(el('div', 'src', n.local || ''));\n"
1567" if (soonest === null || n.in_seconds < soonest) soonest = n.in_seconds;\n"
1568" } else {\n"
1569" tdNext.appendChild(el('span', 'muted', '\\u2014'));\n"
1570" }\n"
1571" tr.appendChild(tdNext);\n"
1572" tr.appendChild(el('td', 'cmd', j.command || ''));\n"
1573" tb.appendChild(tr);\n"
1574" });\n"
1575" $('empty').classList.toggle('hide', shown !== 0);\n"
1576" $('k-total').textContent = (DATA.jobs || []).length;\n"
1577" $('k-valid').textContent = (DATA.jobs || []).filter(function(j){ return j.valid; }).length;\n"
1578" $('k-next').textContent = soonest === null ? '\\u2014' : human(soonest);\n"
1579" $('k-src').textContent = (DATA.sources || []).length;\n"
1580" }\n"
1581" function load(){\n"
1582" $('note').textContent = 'loading\\u2026';\n"
1583" get('action=jobs')\n"
1584" .then(function(d){\n"
1585" if (!d.ok) { $('note').textContent = d.error || 'failed'; badge(false, 'error'); return; }\n"
1586" DATA = d;\n"
1587" badge(true, d.count + ' job' + (d.count === 1 ? '' : 's'));\n"
1588" $('note').textContent = (d.sources && d.sources.length)\n"
1589" ? 'Read from: ' + d.sources.join(', ') + ' (as of ' + d.now_local + ' local)'\n"
1590" : 'No crontab sources readable on this node (as of ' + d.now_local + ' local)';\n"
1591" render();\n"
1592" })\n"
1593" .catch(function(e){ $('note').textContent = 'request failed: ' + e; badge(false, 'error'); });\n"
1594" }\n"
1595" function explain(){\n"
1596" var ex = ($('ex').value || '').trim();\n"
1597" var box = $('exRuns');\n"
1598" while (box.firstChild) box.removeChild(box.firstChild);\n"
1599" if (!ex) { $('exNote').textContent = 'Type an expression first.'; return; }\n"
1600" $('exNote').textContent = 'checking\\u2026';\n"
1601" get('action=explain&expr=' + encodeURIComponent(ex))\n"
1602" .then(function(d){\n"
1603" if (!d.ok) { $('exNote').textContent = d.error || 'failed'; return; }\n"
1604" if (!d.valid) { $('exNote').textContent = 'invalid expression'; return; }\n"
1605" $('exNote').textContent = d.description + (d.boot_only\n"
1606" ? ' \\u2014 runs at boot, so there are no clock times.'\n"
1607" : ' \\u2014 next 5 runs in your local time:');\n"
1608" (d.next || []).forEach(function(r, i){\n"
1609" var row = el('div', 'run');\n"
1610" row.appendChild(el('span', 'n', String(i + 1)));\n"
1611" row.appendChild(el('span', 'u', r.utc));\n"
1612" row.appendChild(el('span', 'l', r.local + ' local \\u00b7 in ' + human(r.in_seconds)));\n"
1613" box.appendChild(row);\n"
1614" });\n"
1615" })\n"
1616" .catch(function(e){ $('exNote').textContent = 'request failed: ' + e; });\n"
1617" }\n"
1618" $('reloadBtn').addEventListener('click', load);\n"
1619" $('goBtn').addEventListener('click', explain);\n"
1620" $('ex').addEventListener('keydown', function(e){ if (e.key === 'Enter') explain(); });\n"
1621" $('q').addEventListener('input', render);\n"
1622" load();\n"
1623" explain();\n"
1624" setInterval(load, 60000);\n"
1625"})();\n"
1626"</script></div></body></html>\n", stdout);
1627}
1628
1629static int mode_html(int embed)
1630{
1631 html_head(embed);
1632 html_body();
1633 return 0;
1634}
1635/* ---------------------------------------------------------------- */
1636/* main */
1637/* ---------------------------------------------------------------- */
1638
1639static int is_post_request(void)
1640{
1641 const char *m = getenv("REQUEST_METHOD");
1642 return m && strcmp(m, "POST") == 0;
1643}
1644
1645int main(int argc, char **argv)
1646{
1647 const char *qs;
1648 char embedv[16];
1649
1650 if (argc > 1) {
1651 if (strcmp(argv[1], "--meta") == 0) return mode_meta();
1652 if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; }
1653 if (strcmp(argv[1], "--help") == 0) {
1654 puts(PLUGIN_ID " " PLUGIN_VER);
1655 puts("usage: " PLUGIN_ID " [--meta|--version|--help]");
1656 puts(" QUERY_STRING='action=jobs' " PLUGIN_ID);
1657 puts(" QUERY_STRING='action=explain&expr=*/15 * * * *' " PLUGIN_ID);
1658 puts("Strictly read-only: never writes a crontab, never runs a scheduled command.");
1659 return 0;
1660 }
1661 }
1662 if (getenv("SX_PLUGIN_META")) return mode_meta();
1663
1664 require_node_auth();
1665
1666 qs = getenv("QUERY_STRING");
1667 if (!qs) qs = "";
1668
1669 if (strstr(qs, "action=") || strstr(qs, "format=json"))
1670 return mode_json(qs);
1671
1672 embedv[0] = '\0';
1673 if (get_query_val(qs, "embed", embedv, sizeof(embedv)))
1674 return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0);
1675 return mode_html(is_post_request() ? 0 : 0);
1676}