/* * plugin_crontab — SCORPIOX BOT open-source cron schedule inspector * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery * 2. ?action=jobs | ?action=explain&expr=... | ?format=json -> JSON node API * 3. GET (default) -> responsive HTML schedule inspector * * Strictly READ-ONLY. It never writes a crontab, never installs a task and * never executes a scheduled command. On POSIX it reads the user's * `crontab -l` output plus /etc/crontab and the files in /etc/cron.d; on Windows it reads * `schtasks /Query /FO CSV`. Setting CRONTAB_FILE to a fixture path bypasses * all of that, which is what the offline tests use. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 #endif #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # define sx_popen _popen # define sx_pclose _pclose #else # include # include # define sx_popen popen # define sx_pclose pclose #endif #include "bot_theme_plugin.h" #define PLUGIN_SLUG "crontab" #define PLUGIN_ID "plugin_crontab" #define PLUGIN_VER "1.0.1" #define MAX_JOBS 512 #define MAX_EXPR 128 #define MAX_DESC 224 #define MAX_CMD 512 #define MAX_SRC 64 #define MAX_RUNS 5 #define HORIZON_DAYS 7305 /* twenty years: five runs even for 29 February */ #define READ_LINE 2048 /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static void json_str(const char *s) { putchar('"'); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': fputs("\\\"", stdout); break; case '\\': fputs("\\\\", stdout); break; case '\n': fputs("\\n", stdout); break; case '\r': fputs("\\r", stdout); break; case '\t': fputs("\\t", stdout); break; default: if (c < 0x20) printf("\\u%04x", c); else putchar(c); } } putchar('"'); } static void str_copy(char *dst, size_t sz, const char *src) { size_t n; if (!dst || sz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= sz) n = sz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static void str_trim(char *s) { size_t n; char *p; if (!s) return; p = s; while (*p && isspace((unsigned char)*p)) p++; if (p != s) memmove(s, p, strlen(p) + 1); n = strlen(s); while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; } static void utc_stamp(time_t t, char *buf, size_t sz) { struct tm tmv; #if defined(_WIN32) gmtime_s(&tmv, &t); #else gmtime_r(&t, &tmv); #endif if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) str_copy(buf, sz, "1970-01-01T00:00:00Z"); } static void local_stamp(time_t t, char *buf, size_t sz) { struct tm tmv; #if defined(_WIN32) localtime_s(&tmv, &t); #else localtime_r(&t, &tmv); #endif if (strftime(buf, sz, "%Y-%m-%d %H:%M", &tmv) == 0) str_copy(buf, sz, "1970-01-01 00:00"); } /* ------------------------------------------------------------------ */ /* Cron model */ /* ------------------------------------------------------------------ */ typedef struct { int valid; char error[96]; char raw[MAX_EXPR]; char keyword[16]; /* "@daily" etc; empty for 5-field syntax */ char f[5][40]; /* original field texts */ unsigned char min[60]; unsigned char hour[24]; unsigned char dom[32]; /* index 1..31 used */ unsigned char mon[13]; /* index 1..12 used */ unsigned char dow[7]; /* index 0 == Sunday */ int dom_restricted; int dow_restricted; int boot_only; /* @reboot — no computable fire times */ char desc[MAX_DESC]; } cron_t; static const char *const k_mon_names[12] = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; static const char *const k_dow_names[7] = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" }; static const char *const k_mon_long[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static const char *const k_dow_long[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static void cron_clear(cron_t *c) { memset(c, 0, sizeof(*c)); } static int name_index(const char *tok, int len, const char *const *names, int count) { int i; char buf[16]; if (len <= 0 || len >= (int)sizeof(buf)) return -1; for (i = 0; i < len; i++) buf[i] = (char)tolower((unsigned char)tok[i]); buf[len] = '\0'; for (i = 0; i < count; i++) if (strcmp(buf, names[i]) == 0) return i; return -1; } /* Plain number or 3-letter name -> value. Returns 1 on success. */ static int parse_value(const char *tok, int len, const char *const *names, int namecount, int name_offset, int *out) { int i; int v = 0; int named; if (len <= 0) return 0; named = name_index(tok, len, names, namecount); if (named >= 0) { *out = named + name_offset; return 1; } for (i = 0; i < len; i++) { if (!isdigit((unsigned char)tok[i])) return 0; v = v * 10 + (tok[i] - '0'); if (v > 100000) return 0; } *out = v; return 1; } /* * Parse one cron field into a flag array (indices lo..hi). * Accepts "*", "N", "a-b", "*/step", "a-b/step" and comma lists. * Returns 1 on success, 0 on syntax error, -1 on out-of-range value. */ static int parse_field(const char *text, int lo, int hi, const char *const *names, int namecount, int name_offset, unsigned char *flags) { char work[256]; char *item; memset(flags, 0, (size_t)(hi + 1)); if (!text || !*text) return 0; if (strlen(text) >= sizeof(work)) return 0; str_copy(work, sizeof(work), text); item = work; while (item && *item) { char *comma = strchr(item, ','); char rng[128]; const char *slash; int step = 1; int start = lo; int end = hi; int v; if (comma) *comma = '\0'; str_trim(item); if (!*item) return 0; slash = strchr(item, '/'); if (slash) { size_t off = (size_t)(slash - item); if (off >= sizeof(rng)) return 0; memcpy(rng, item, off); rng[off] = '\0'; if (!parse_value(slash + 1, (int)strlen(slash + 1), NULL, 0, 0, &step)) return 0; if (step <= 0) return 0; if (step > hi - lo + 1) step = hi - lo + 1; } else { str_copy(rng, sizeof(rng), item); } if (strcmp(rng, "*") == 0) { start = lo; end = hi; } else { const char *dash = strchr(rng, '-'); if (dash) { if (!parse_value(rng, (int)(dash - rng), names, namecount, name_offset, &start)) return 0; if (!parse_value(dash + 1, (int)strlen(dash + 1), names, namecount, name_offset, &end)) return 0; } else { if (!parse_value(rng, (int)strlen(rng), names, namecount, name_offset, &start)) return 0; end = slash ? hi : start; } } if (start < lo || start > hi || end < lo || end > hi) return -1; if (end < start) return -1; for (v = start; v <= end; v += step) flags[v] = 1; if (!comma) break; item = comma + 1; } return 1; } /* True when every value in lo..hi is selected. */ static int field_is_full(const unsigned char *flags, int lo, int hi) { int i; for (i = lo; i <= hi; i++) if (!flags[i]) return 0; return 1; } static int count_set(const unsigned char *flags, int lo, int hi) { int i, n = 0; for (i = lo; i <= hi; i++) if (flags[i]) n++; return n; } /* ---------------------------------------------------------------- */ /* Portable UTC mktime */ /* ---------------------------------------------------------------- */ /* Days since the Unix epoch for a civil date (Howard Hinnant's algorithm). */ static long days_from_civil(int y, int m, int d) { long era, yoe, doy, doe; y -= (m <= 2); era = (y >= 0 ? y : y - 399) / 400; yoe = (long)(y - era * 400); doy = (153L * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097L + doe - 719468L; } /* * Portable UTC mktime. Implemented directly rather than calling timegm(), * which is not declared by default on macOS and is missing on Windows. */ static time_t timegm_portable(struct tm *tmv) { long days = days_from_civil(tmv->tm_year + 1900, tmv->tm_mon + 1, tmv->tm_mday); return (time_t)(days * 86400L + (long)tmv->tm_hour * 3600L + (long)tmv->tm_min * 60L + (long)tmv->tm_sec); } /* ---------------------------------------------------------------- */ /* Human readable description of a parsed schedule */ /* ---------------------------------------------------------------- */ /* Append with bounds. */ static void sapp(char *dst, size_t sz, const char *src) { size_t have; if (!dst || sz == 0 || !src) return; have = strlen(dst); if (have + 1 >= sz) return; strncat(dst, src, sz - have - 1); } /* First selected index in [lo,hi], or lo when none. */ static int first_set(const unsigned char *flags, int lo, int hi) { int i; for (i = lo; i <= hi; i++) if (flags[i]) return i; return lo; } static void cron_describe_time(const cron_t *c, char *out, size_t sz) { int nm, nh; out[0] = '\0'; if (field_is_full(c->min, 0, 59) && field_is_full(c->hour, 0, 23)) { str_copy(out, sz, "Every minute"); return; } if (c->f[0][0] == '*' && c->f[0][1] == '/' && field_is_full(c->hour, 0, 23) && !strchr(c->f[0], ',')) { int step = atoi(c->f[0] + 2); if (step == 1) str_copy(out, sz, "Every minute"); else snprintf(out, sz, "Every %d minutes", step); return; } if (field_is_full(c->hour, 0, 23) && c->f[1][0] == '*') { int n = count_set(c->min, 0, 59); if (c->f[0][0] == '*' && c->f[0][1] == '\0') { str_copy(out, sz, "Every minute"); } else if (n <= 6) { int m, first = 1; sapp(out, sz, "Every hour at minute "); for (m = 0; m < 60; m++) { char t[8]; if (!c->min[m]) continue; snprintf(t, sizeof(t), "%s%d", first ? "" : " and ", m); sapp(out, sz, t); first = 0; } } else { snprintf(out, sz, "Every hour at %d selected minutes", n); } return; } if (c->f[1][0] == '*' && c->f[1][1] == '/' && c->min[0] == 0 && count_set(c->min, 0, 59) == 1 && !c->dom_restricted && !c->dow_restricted) { int step = atoi(c->f[1] + 2); snprintf(out, sz, "Every %d hours at minute %d", step, first_set(c->min, 0, 59)); return; } nm = count_set(c->min, 0, 59); nh = count_set(c->hour, 0, 23); /* uniform minute step inside a restricted hour window */ if (c->f[0][0] == '*' && c->f[0][1] == '/' && !strchr(c->f[0], ',')) { int step = atoi(c->f[0] + 2); int hlo = first_set(c->hour, 0, 23); int hhi = hlo; int h; for (h = 23; h >= 0; h--) if (c->hour[h]) { hhi = h; break; } if (step > 0 && nh > 1) { snprintf(out, sz, "Every %d minutes, between %02d:00 and %02d:59", step, hlo, hhi); return; } } if (nm == 1 && nh == 1) { snprintf(out, sz, "At %02d:%02d", first_set(c->hour, 0, 23), first_set(c->min, 0, 59)); return; } if (nm * nh <= 6) { int h, m, first = 1; sapp(out, sz, "At "); for (h = 0; h < 24; h++) { if (!c->hour[h]) continue; for (m = 0; m < 60; m++) { char t[8]; if (!c->min[m]) continue; snprintf(t, sizeof(t), "%s%02d:%02d", first ? "" : ", ", h, m); sapp(out, sz, t); first = 0; } } return; } if (nm == 1 && nh < 24) { int h, first = 1; char buf[256]; snprintf(buf, sizeof(buf), "At minute %d past hour%s ", first_set(c->min, 0, 59), nh == 1 ? "" : "s"); for (h = 0; h < 24; h++) { char t[8]; if (!c->hour[h]) continue; snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", h); sapp(buf, sizeof(buf), t); first = 0; } str_copy(out, sz, buf); return; } snprintf(out, sz, "At %d times a day", nm * nh); } static void cron_describe(const cron_t *cc, char *out, size_t sz) { cron_t c = *cc; char day[128]; out[0] = '\0'; day[0] = '\0'; if (c.keyword[0]) { if (strcmp(c.keyword, "@reboot") == 0) str_copy(out, sz, "When the system starts"); else if (strcmp(c.keyword, "@hourly") == 0) str_copy(out, sz, "Every hour, on the hour"); else if (strcmp(c.keyword, "@daily") == 0 || strcmp(c.keyword, "@midnight") == 0) str_copy(out, sz, "Every day at midnight"); else if (strcmp(c.keyword, "@weekly") == 0) str_copy(out, sz, "Every Sunday at midnight"); else if (strcmp(c.keyword, "@monthly") == 0) str_copy(out, sz, "The 1st of every month at midnight"); else if (strcmp(c.keyword, "@yearly") == 0 || strcmp(c.keyword, "@annually") == 0) str_copy(out, sz, "1 January at midnight"); else str_copy(out, sz, "Custom schedule"); return; } cron_describe_time(&c, out, sz); /* month restriction */ if (!field_is_full(c.mon, 1, 12)) { int n = count_set(c.mon, 1, 12); int i; if (n == 1) { snprintf(day, sizeof(day), "in %s", k_mon_long[first_set(c.mon, 1, 12) - 1]); } else { int first = 1; sapp(day, sizeof(day), "in "); for (i = 1; i <= 12; i++) { if (!c.mon[i]) continue; sapp(day, sizeof(day), first ? "" : ", "); sapp(day, sizeof(day), k_mon_long[i - 1]); first = 0; } } } /* day-of-month / day-of-week (classic OR semantics when both restricted) */ if (c.dom_restricted && c.dow_restricted) { int ndow = count_set(c.dow, 0, 6); int ndom = count_set(c.dom, 1, 31); char part[96]; part[0] = '\0'; if (ndow == 1) { sapp(part, sizeof(part), k_dow_long[first_set(c.dow, 0, 6)]); } else { int i, first = 1; for (i = 0; i < 7; i++) { if (!c.dow[i]) continue; sapp(part, sizeof(part), first ? "" : ", "); sapp(part, sizeof(part), k_dow_long[i]); first = 0; } } sapp(day, sizeof(day), day[0] ? " " : ""); sapp(day, sizeof(day), "on "); sapp(day, sizeof(day), part); if (ndom == 1) { char t[32]; snprintf(t, sizeof(t), " or day %d of the month", first_set(c.dom, 1, 31)); sapp(day, sizeof(day), t); } else { sapp(day, sizeof(day), " or on selected days of the month"); } } else if (c.dow_restricted) { int ndow = count_set(c.dow, 0, 6); sapp(day, sizeof(day), day[0] ? " " : ""); sapp(day, sizeof(day), "on "); if (ndow == 1) { sapp(day, sizeof(day), k_dow_long[first_set(c.dow, 0, 6)]); } else { int i, first = 1; for (i = 0; i < 7; i++) { if (!c.dow[i]) continue; sapp(day, sizeof(day), first ? "" : ", "); sapp(day, sizeof(day), k_dow_long[i]); first = 0; } } } else if (c.dom_restricted) { int ndom = count_set(c.dom, 1, 31); sapp(day, sizeof(day), day[0] ? " " : ""); if (ndom == 1) { char t[32]; snprintf(t, sizeof(t), "on day %d of the month", first_set(c.dom, 1, 31)); sapp(day, sizeof(day), t); } else if (c.f[2][0] == '*' && c.f[2][1] == '/') { char t[48]; snprintf(t, sizeof(t), "every %d days of the month", atoi(c.f[2] + 2)); sapp(day, sizeof(day), t); } else { int i, first = 1; sapp(day, sizeof(day), "on days "); for (i = 1; i <= 31; i++) { char t[8]; if (!c.dom[i]) continue; snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", i); sapp(day, sizeof(day), t); first = 0; } sapp(day, sizeof(day), " of the month"); } } if (day[0]) { char full[MAX_DESC]; snprintf(full, sizeof(full), "%s, %s", out, day); str_copy(out, sz, full); } else if (strncmp(out, "At ", 3) == 0) { sapp(out, sz, ", every day"); } } /* ---------------------------------------------------------------- */ /* Expression parsing */ /* ---------------------------------------------------------------- */ static void apply_keyword(cron_t *c, const char *kw) { int i; for (i = 0; i < 60; i++) c->min[i] = 1; for (i = 0; i < 24; i++) c->hour[i] = 1; for (i = 0; i <= 31; i++) c->dom[i] = 1; for (i = 0; i <= 12; i++) c->mon[i] = 1; for (i = 0; i < 7; i++) c->dow[i] = 1; if (strcmp(kw, "@reboot") == 0) { c->boot_only = 1; return; } memset(c->min, 0, sizeof(c->min)); c->min[0] = 1; if (strcmp(kw, "@hourly") == 0) { memset(c->hour, 0, sizeof(c->hour)); for (i = 0; i < 24; i++) c->hour[i] = 1; return; } memset(c->hour, 0, sizeof(c->hour)); c->hour[0] = 1; if (strcmp(kw, "@daily") == 0 || strcmp(kw, "@midnight") == 0) return; if (strcmp(kw, "@weekly") == 0) { memset(c->dow, 0, sizeof(c->dow)); c->dow[0] = 1; c->dow_restricted = 1; return; } if (strcmp(kw, "@monthly") == 0) { memset(c->dom, 0, sizeof(c->dom)); c->dom[1] = 1; c->dom_restricted = 1; return; } if (strcmp(kw, "@yearly") == 0 || strcmp(kw, "@annually") == 0) { memset(c->dom, 0, sizeof(c->dom)); memset(c->mon, 0, sizeof(c->mon)); c->dom[1] = 1; c->mon[1] = 1; c->dom_restricted = 1; return; } /* continue for @hourly handled above */ } /* * Parse a full cron expression: either "@keyword" or five whitespace-separated * fields. Fills c->valid / c->error. Returns c->valid. * The expression is trimmed in place into c->raw. */ static int cron_parse(cron_t *c, const char *expr) { char work[MAX_EXPR * 2]; char *tok[8]; int ntok = 0; int rc; char *p; cron_clear(c); str_copy(c->raw, sizeof(c->raw), expr ? expr : ""); str_copy(work, sizeof(work), c->raw); str_trim(work); if (!work[0]) { str_copy(c->error, sizeof(c->error), "empty expression"); return 0; } if (work[0] == '@') { char kw[24]; str_copy(kw, sizeof(kw), work); str_trim(kw); if (strcmp(kw, "@reboot") != 0 && strcmp(kw, "@hourly") != 0 && strcmp(kw, "@daily") != 0 && strcmp(kw, "@midnight") != 0 && strcmp(kw, "@weekly") != 0 && strcmp(kw, "@monthly") != 0 && strcmp(kw, "@yearly") != 0 && strcmp(kw, "@annually") != 0) { str_copy(c->error, sizeof(c->error), "unknown @keyword"); return 0; } str_copy(c->keyword, sizeof(c->keyword), kw); apply_keyword(c, kw); c->dom_restricted = c->dom_restricted || 0; c->valid = 1; cron_describe(c, c->desc, sizeof(c->desc)); return 1; } for (p = work; *p && ntok < 8; ) { while (*p && isspace((unsigned char)*p)) *p++ = '\0'; if (!*p) break; tok[ntok++] = p; while (*p && !isspace((unsigned char)*p)) p++; } if (ntok != 5) { str_copy(c->error, sizeof(c->error), ntok < 5 ? "expected 5 fields" : "too many fields"); return 0; } { int i; for (i = 0; i < 5; i++) str_copy(c->f[i], sizeof(c->f[i]), tok[i]); } rc = parse_field(c->f[0], 0, 59, NULL, 0, 0, c->min); if (rc <= 0) { str_copy(c->error, sizeof(c->error), rc < 0 ? "minute out of range 0-59" : "bad minute field"); return 0; } rc = parse_field(c->f[1], 0, 23, NULL, 0, 0, c->hour); if (rc <= 0) { str_copy(c->error, sizeof(c->error), rc < 0 ? "hour out of range 0-23" : "bad hour field"); return 0; } rc = parse_field(c->f[2], 1, 31, NULL, 0, 0, c->dom); if (rc <= 0) { str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-month out of range 1-31" : "bad day-of-month field"); return 0; } rc = parse_field(c->f[3], 1, 12, k_mon_names, 12, 1, c->mon); if (rc <= 0) { str_copy(c->error, sizeof(c->error), rc < 0 ? "month out of range 1-12" : "bad month field"); return 0; } { unsigned char tmpdow[8]; int i; rc = parse_field(c->f[4], 0, 7, k_dow_names, 7, 0, tmpdow); if (rc <= 0) { str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-week out of range 0-7" : "bad day-of-week field"); return 0; } memset(c->dow, 0, sizeof(c->dow)); for (i = 0; i <= 7; i++) if (tmpdow[i]) c->dow[i % 7] = 1; } c->dom_restricted = !field_is_full(c->dom, 1, 31); c->dow_restricted = !field_is_full(c->dow, 0, 6); c->valid = 1; cron_describe(c, c->desc, sizeof(c->desc)); return 1; } /* Day-of-week for a broken-down UTC time; 0 == Sunday. */ static int tm_dow(const struct tm *t) { return t->tm_wday; } static int day_matches(const cron_t *c, const struct tm *day) { int dom_ok = c->dom[day->tm_mday] ? 1 : 0; int dow_ok = c->dow[tm_dow(day)] ? 1 : 0; if (!c->mon[day->tm_mon + 1]) return 0; if (c->dom_restricted && c->dow_restricted) return dom_ok || dow_ok; if (c->dom_restricted) return dom_ok; if (c->dow_restricted) return dow_ok; return 1; } /* * Compute the next `want` firing times strictly after `from` (UTC). * Iterates day by day, then within matching days iterates hours and minutes * using the parsed bitmaps. Returns the number of timestamps written. */ static int cron_next_runs(const cron_t *c, time_t from, time_t *out, int want) { struct tm base; int got = 0; int d; if (!c->valid || c->boot_only) return 0; { time_t t = from; #if defined(_WIN32) gmtime_s(&base, &t); #else gmtime_r(&t, &base); #endif } for (d = 0; d < HORIZON_DAYS && got < want; d++) { struct tm day; time_t day_start; int h, m; day = base; day.tm_mday += d; day.tm_hour = 0; day.tm_min = 0; day.tm_sec = 0; day.tm_isdst = 0; day_start = timegm_portable(&day); if (day_start == (time_t)-1) continue; #if defined(_WIN32) gmtime_s(&day, &day_start); #else gmtime_r(&day_start, &day); #endif if (!day_matches(c, &day)) continue; for (h = 0; h < 24 && got < want; h++) { if (!c->hour[h]) continue; for (m = 0; m < 60 && got < want; m++) { time_t cand; if (!c->min[m]) continue; cand = day_start + (time_t)h * 3600 + (time_t)m * 60; if (cand <= from) continue; out[got++] = cand; } } } return got; } /* ---------------------------------------------------------------- */ /* Job collection */ /* ---------------------------------------------------------------- */ typedef struct { char source[MAX_SRC]; char expr[MAX_EXPR]; char command[MAX_CMD]; char user[64]; char kind[12]; /* "cron" or "task" */ int valid; char error[96]; char desc[MAX_DESC]; int next_count; time_t next[MAX_RUNS]; } job_t; static job_t g_jobs[MAX_JOBS]; static int g_job_count; static char g_sources[16][MAX_SRC]; static int g_source_count; static int g_truncated; static void note_source(const char *name) { int i; if (!name || !*name) return; for (i = 0; i < g_source_count; i++) if (strcmp(g_sources[i], name) == 0) return; if (g_source_count < (int)(sizeof(g_sources) / sizeof(g_sources[0]))) str_copy(g_sources[g_source_count++], MAX_SRC, name); } static job_t *job_new(void) { job_t *j; if (g_job_count >= MAX_JOBS) { g_truncated = 1; return NULL; } j = &g_jobs[g_job_count++]; memset(j, 0, sizeof(*j)); return j; } /* Skip blank lines, comments and environment assignments. */ static int cron_line_skippable(const char *s) { const char *p; if (!s) return 1; while (*s && isspace((unsigned char)*s)) s++; if (!*s) return 1; if (*s == '#') return 1; /* NAME = value (no whitespace inside the name) */ for (p = s; *p && (isalnum((unsigned char)*p) || *p == '_'); p++) ; if (p > s && *p == '=') return 1; return 0; } /* * Split one crontab line into an expression and a command. * system format: 5 fields, user, command (/etc/crontab, /etc/cron.d entries) * user format: 5 fields, command (crontab -l) * Returns 1 on success. */ static int split_cron_line(const char *line, int system_format, char *expr, size_t expr_sz, char *user, size_t user_sz, char *cmd, size_t cmd_sz) { char work[READ_LINE]; char *p; int fields_needed = system_format ? 6 : 5; int got = 0; expr[0] = user[0] = cmd[0] = '\0'; str_copy(work, sizeof(work), line); str_trim(work); if (!work[0]) return 0; /* @keyword form */ if (work[0] == '@') { p = work; while (*p && !isspace((unsigned char)*p)) p++; str_copy(expr, expr_sz, work); expr[strlen(work) - strlen(p) >= expr_sz ? expr_sz - 1 : strlen(work) - strlen(p)] = '\0'; if (*p) { char *rest = p; while (*rest && isspace((unsigned char)*rest)) rest++; if (system_format) { char *u = rest; while (*u && !isspace((unsigned char)*u)) u++; str_copy(user, user_sz, rest); user[strlen(rest) - strlen(u) >= user_sz ? user_sz - 1 : strlen(rest) - strlen(u)] = '\0'; while (*u && isspace((unsigned char)*u)) u++; str_copy(cmd, cmd_sz, u); } else { str_copy(cmd, cmd_sz, rest); } } return 1; } p = work; while (*p && got < fields_needed) { char *start; while (*p && isspace((unsigned char)*p)) p++; if (!*p) break; start = p; while (*p && !isspace((unsigned char)*p)) p++; if (got < 5) { size_t len = (size_t)(p - start); size_t have = strlen(expr); if (have + len + 2 < expr_sz) { if (have) expr[have++] = ' '; memcpy(expr + have, start, len); expr[have + len] = '\0'; } } else { size_t len = (size_t)(p - start); if (len >= user_sz) len = user_sz - 1; memcpy(user, start, len); user[len] = '\0'; } got++; } if (got < fields_needed) return 0; while (*p && isspace((unsigned char)*p)) p++; str_copy(cmd, cmd_sz, p); return 1; } static void add_cron_job(const char *source, const char *line, int system_format, time_t now) { char expr[MAX_EXPR], user[64], cmd[MAX_CMD]; job_t *j; if (!split_cron_line(line, system_format, expr, sizeof(expr), user, sizeof(user), cmd, sizeof(cmd))) return; if (!expr[0]) return; j = job_new(); if (!j) return; str_copy(j->source, sizeof(j->source), source); str_copy(j->expr, sizeof(j->expr), expr); str_copy(j->command, sizeof(j->command), cmd); str_copy(j->user, sizeof(j->user), user); str_copy(j->kind, sizeof(j->kind), "cron"); { cron_t c; if (cron_parse(&c, expr)) { j->valid = 1; str_copy(j->desc, sizeof(j->desc), c.desc); if (c.boot_only) str_copy(j->desc, sizeof(j->desc), "When the system starts (no scheduled times)"); else j->next_count = cron_next_runs(&c, now, j->next, MAX_RUNS); } else { j->valid = 0; str_copy(j->error, sizeof(j->error), c.error); str_copy(j->desc, sizeof(j->desc), "Unrecognised schedule expression"); } } note_source(source); } #if defined(_WIN32) static void add_task_job(const char *name, const char *nextrun, const char *status, time_t now) { job_t *j = job_new(); (void)now; if (!j) return; str_copy(j->source, sizeof(j->source), "schtasks"); str_copy(j->kind, sizeof(j->kind), "task"); str_copy(j->expr, sizeof(j->expr), "task"); str_copy(j->command, sizeof(j->command), name); str_copy(j->user, sizeof(j->user), ""); j->valid = 1; { char d[MAX_DESC]; snprintf(d, sizeof(d), "%s%s%s", status && *status ? status : "Scheduled Windows task", nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? " - next " : "", nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? nextrun : ""); str_copy(j->desc, sizeof(j->desc), d); } note_source("schtasks"); } #endif /* Feed a whole file (or popen stream) of crontab lines. */ static void ingest_lines(FILE *fp, const char *source, int system_format, time_t now) { char line[READ_LINE]; int forced = system_format; while (fp && fgets(line, sizeof(line), fp)) { char probe[READ_LINE]; size_t n = strlen(line); while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; str_copy(probe, sizeof(probe), line); str_trim(probe); /* fixture directives: "# sx:system" / "# sx:user" / "# sx:source NAME" */ if (strncmp(probe, "# sx:", 5) == 0) { const char *d = probe + 5; if (strncmp(d, "system", 6) == 0) { forced = 1; continue; } if (strncmp(d, "user", 4) == 0) { forced = 0; continue; } continue; } if (cron_line_skippable(line)) continue; add_cron_job(source, line, forced, now); } } static void ingest_file(const char *path, const char *source, int system_format, time_t now) { FILE *fp = fopen(path, "r"); if (!fp) return; ingest_lines(fp, source, system_format, now); fclose(fp); } #if !defined(_WIN32) static void ingest_command(const char *cmd, const char *source, time_t now) { FILE *fp = sx_popen(cmd, "r"); if (!fp) return; ingest_lines(fp, source, 0, now); sx_pclose(fp); } #endif #if defined(_WIN32) /* Minimal CSV field splitter for `schtasks /Query /FO CSV`. */ static void ingest_schtasks(time_t now) { FILE *fp = sx_popen("schtasks /Query /FO CSV /NH", "r"); char line[READ_LINE]; if (!fp) return; while (fgets(line, sizeof(line), fp)) { char f[4][256]; int nf = 0; char *p = line; size_t n = strlen(line); while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; while (*p && nf < 4) { char *out = f[nf]; size_t oi = 0; if (*p == '"') { p++; while (*p && *p != '"' && oi + 1 < 256) { if (*p == '"' && p[1] == '"') { out[oi++] = '"'; p += 2; continue; } out[oi++] = *p++; } if (*p == '"') p++; } else { while (*p && *p != ',' && oi + 1 < 256) out[oi++] = *p++; } out[oi] = '\0'; nf++; if (*p == ',') p++; } if (nf >= 2 && f[0][0] && strcmp(f[0], "TaskName") != 0) add_task_job(f[0], f[1], nf > 2 ? f[2] : "", now); } sx_pclose(fp); } #endif static void collect_jobs(void) { time_t now = time(NULL); const char *fixture = getenv("CRONTAB_FILE"); g_job_count = 0; g_source_count = 0; g_truncated = 0; if (fixture && *fixture) { ingest_file(fixture, "fixture", 0, now); return; } #if defined(_WIN32) ingest_schtasks(now); #else ingest_command("crontab -l 2>/dev/null", "user", now); ingest_file("/etc/crontab", "/etc/crontab", 1, now); { DIR *d = opendir("/etc/cron.d"); struct dirent *ent; if (d) { while ((ent = readdir(d)) != NULL) { char path[512]; char label[MAX_SRC]; if (ent->d_name[0] == '.') continue; snprintf(path, sizeof(path), "/etc/cron.d/%s", ent->d_name); snprintf(label, sizeof(label), "/etc/cron.d/%.40s", ent->d_name); ingest_file(path, label, 1, now); } closedir(d); } } #endif } /* ---------------------------------------------------------------- */ /* HTTP plumbing */ /* ---------------------------------------------------------------- */ static void json_header(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void print_runs(const time_t *runs, int count, time_t now) { int i; char utc[40], loc[40]; putchar('['); for (i = 0; i < count; i++) { utc_stamp(runs[i], utc, sizeof(utc)); local_stamp(runs[i], loc, sizeof(loc)); if (i) putchar(','); fputs("{\"utc\":", stdout); json_str(utc); fputs(",\"local\":", stdout); json_str(loc); printf(",\"in_seconds\":%ld}", (long)(runs[i] - now)); } putchar(']'); } static int mode_meta(void) { fputs("{\"name\":\"crontab\",\"desc\":\"Cron jobs\"}\n", stdout); return 0; } /* Field text for a keyword schedule, for the JSON fields block. */ static void cron_keyword_fields(const cron_t *c, char kf[5][12]) { if (!c->keyword[0]) { int i; for (i = 0; i < 5; i++) str_copy(kf[i], 12, c->f[i]); return; } str_copy(kf[0], 12, "0"); str_copy(kf[1], 12, "0"); str_copy(kf[2], 12, "*"); str_copy(kf[3], 12, "*"); str_copy(kf[4], 12, "*"); if (strcmp(c->keyword, "@reboot") == 0) { int i; for (i = 0; i < 5; i++) str_copy(kf[i], 12, "@reboot"); } else if (strcmp(c->keyword, "@hourly") == 0) { str_copy(kf[1], 12, "*"); } else if (strcmp(c->keyword, "@weekly") == 0) { str_copy(kf[4], 12, "0"); } else if (strcmp(c->keyword, "@monthly") == 0) { str_copy(kf[2], 12, "1"); } else if (strcmp(c->keyword, "@yearly") == 0 || strcmp(c->keyword, "@annually") == 0) { str_copy(kf[2], 12, "1"); str_copy(kf[3], 12, "1"); } } static int mode_json(const char *qs) { char action[64]; char expr[MAX_EXPR * 2]; time_t now = time(NULL); action[0] = '\0'; get_query_val(qs, "action", action, sizeof(action)); json_header(); if (strcmp(action, "explain") == 0) { cron_t c; time_t runs[MAX_RUNS]; int n = 0; char nowutc[40]; char nowloc[40]; get_query_val(qs, "expr", expr, sizeof(expr)); utc_stamp(now, nowutc, sizeof(nowutc)); local_stamp(now, nowloc, sizeof(nowloc)); if (!expr[0]) { fputs("{\"ok\":false,\"error\":\"missing expr parameter\",\"valid\":false}\n", stdout); return 0; } if (cron_parse(&c, expr)) { if (!c.boot_only) n = cron_next_runs(&c, now, runs, MAX_RUNS); } else { fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout); json_str(expr); fputs(",\"valid\":false,\"error\":", stdout); json_str(c.error[0] ? c.error : "invalid expression"); fputs(",\"description\":\"\",\"keyword\":\"\",\"next\":[]," "\"now_utc\":", stdout); json_str(nowutc); fputs(",\"now_local\":", stdout); json_str(nowloc); fputs("}\n", stdout); return 0; } fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout); json_str(expr); fputs(",\"valid\":true,\"keyword\":", stdout); json_str(c.keyword); fputs(",\"description\":", stdout); json_str(c.desc); fputs(",\"normalized\":", stdout); if (c.keyword[0]) { json_str(c.keyword); } else { char norm[220]; snprintf(norm, sizeof(norm), "%s %s %s %s %s", c.f[0], c.f[1], c.f[2], c.f[3], c.f[4]); json_str(norm); } { char kf[5][12]; cron_keyword_fields(&c, kf); fputs(",\"fields\":{\"minute\":", stdout); json_str(kf[0]); fputs(",\"hour\":", stdout); json_str(kf[1]); fputs(",\"day_of_month\":", stdout); json_str(kf[2]); fputs(",\"month\":", stdout); json_str(kf[3]); fputs(",\"day_of_week\":", stdout); json_str(kf[4]); } fputs("},\"boot_only\":", stdout); fputs(c.boot_only ? "true" : "false", stdout); fputs(",\"now_utc\":", stdout); json_str(nowutc); fputs(",\"now_local\":", stdout); json_str(nowloc); fputs(",\"next\":", stdout); print_runs(runs, n, now); putchar('}'); putchar('\n'); return 0; } if (strcmp(action, "jobs") == 0 || strcmp(action, "list") == 0 || !action[0]) { char nowutc[40], nowloc[40]; int i; collect_jobs(); utc_stamp(now, nowutc, sizeof(nowutc)); local_stamp(now, nowloc, sizeof(nowloc)); fputs("{\"ok\":true,\"action\":\"jobs\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"", stdout); fputs(",\"now_utc\":", stdout); json_str(nowutc); fputs(",\"now_local\":", stdout); json_str(nowloc); printf(",\"count\":%d,\"truncated\":%s", g_job_count, g_truncated ? "true" : "false"); fputs(",\"sources\":[", stdout); for (i = 0; i < g_source_count; i++) { if (i) putchar(','); json_str(g_sources[i]); } fputs("],\"jobs\":[", stdout); for (i = 0; i < g_job_count; i++) { const job_t *j = &g_jobs[i]; if (i) putchar(','); fputs("{\"source\":", stdout); json_str(j->source); fputs(",\"kind\":", stdout); json_str(j->kind); fputs(",\"expr\":", stdout); json_str(j->expr); fputs(",\"command\":", stdout); json_str(j->command); fputs(",\"user\":", stdout); json_str(j->user); printf(",\"valid\":%s", j->valid ? "true" : "false"); if (!j->valid) { fputs(",\"error\":", stdout); json_str(j->error); } fputs(",\"description\":", stdout); json_str(j->desc); fputs(",\"next\":", stdout); print_runs(j->next, j->next_count, now); putchar('}'); } fputs("]}\n", stdout); return 0; } if (strcmp(action, "info") == 0) { fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"" ",\"slug\":\"" PLUGIN_SLUG "\",\"license\":\"MIT\",\"read_only\":true" ",\"actions\":[\"jobs\",\"explain\",\"info\"]" ",\"capabilities\":[\"crontab_read\",\"cron_parse\"]" ",\"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", stdout); return 0; } fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); return 0; } static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; const char *qs; char qpwd[256]; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ---------------------------------------------------------------- */ /* HTML UI */ /* ---------------------------------------------------------------- */ static void html_head(int embed) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); fputs("\n" "" "crontab", stdout); fputs(SX_BOT_THEME_PREPAINT "" SX_BOT_THEME_HANDOFF "
", stdout); if (!embed) fputs("", stdout); } static void html_body(void) { fputs("

crontab

" "" PLUGIN_VER "" "loading" "" "" "
", stdout); /* KPIs */ fputs("

Schedule overview

" "
jobs
—
" "
parsed
—
" "
next run
—
" "
sources
—
" "
" "
" "" "
" "
" "
" "" "
SourceScheduleMeaningNext runCommand
" "
No scheduled entries found on this node.
" "
", stdout); /* playground */ fputs("

Cron expression playground

" "
" "" "" "
" "
" "Accepts standard five-field expressions and @hourly, @daily, @weekly, " "@monthly, @yearly, @reboot.
" "
", stdout); fputs("

About this plugin

" "

Local node only. Reads " "crontab -l, /etc/crontab and /etc/cron.d " "on Linux and macOS, or schtasks on Windows. It is strictly read-only: " "no schedule is ever written and no scheduled command is ever executed.

" "

Set CRONTAB_FILE to inspect a fixture " "file instead of the live machine. Source is MIT licensed.

", stdout); fputs("
\n", stdout); } static int mode_html(int embed) { html_head(embed); html_body(); return 0; } /* ---------------------------------------------------------------- */ /* main */ /* ---------------------------------------------------------------- */ static int is_post_request(void) { const char *m = getenv("REQUEST_METHOD"); return m && strcmp(m, "POST") == 0; } int main(int argc, char **argv) { const char *qs; char embedv[16]; if (argc > 1) { if (strcmp(argv[1], "--meta") == 0) return mode_meta(); if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; } if (strcmp(argv[1], "--help") == 0) { puts(PLUGIN_ID " " PLUGIN_VER); puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); puts(" QUERY_STRING='action=jobs' " PLUGIN_ID); puts(" QUERY_STRING='action=explain&expr=*/15 * * * *' " PLUGIN_ID); puts("Strictly read-only: never writes a crontab, never runs a scheduled command."); return 0; } } if (getenv("SX_PLUGIN_META")) return mode_meta(); require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; if (strstr(qs, "action=") || strstr(qs, "format=json")) return mode_json(qs); embedv[0] = '\0'; if (get_query_val(qs, "embed", embedv, sizeof(embedv))) return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); return mode_html(is_post_request() ? 0 : 0); }