aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

cron.c (12291B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #if FEATURE_LOGGER_SYSLOG || FEATURE_CRON_DAEMON
      4 #ifndef _DEFAULT_SOURCE
      5 #define _DEFAULT_SOURCE
      6 #endif
      7 #endif
      8 
      9 #include <sys/types.h>
     10 #include <sys/wait.h>
     11 
     12 #include <ctype.h>
     13 #include <errno.h>
     14 #include <limits.h>
     15 #include <signal.h>
     16 #include <stdarg.h>
     17 #include <stdio.h>
     18 #include <stdlib.h>
     19 #include <string.h>
     20 #include <syslog.h>
     21 #include <time.h>
     22 #include <unistd.h>
     23 
     24 #include "paths.h"
     25 #include "queue.h"
     26 #include "util.h"
     27 #include "wexec.h"
     28 
     29 struct field {
     30   enum { ERROR, WILDCARD, NUMBER, RANGE, REPEAT, LIST } type;
     31   long *val;
     32   int   len;
     33 };
     34 
     35 struct ctabentry {
     36   struct field min;
     37   struct field hour;
     38   struct field mday;
     39   struct field mon;
     40   struct field wday;
     41   char        *cmd;
     42   TAILQ_ENTRY(ctabentry) entry;
     43 };
     44 
     45 struct jobentry {
     46   char *cmd;
     47   pid_t pid;
     48   TAILQ_ENTRY(jobentry) entry;
     49 };
     50 
     51 static sig_atomic_t chldreap;
     52 static sig_atomic_t reload;
     53 static sig_atomic_t quit;
     54 static TAILQ_HEAD(, ctabentry) ctabhead = TAILQ_HEAD_INITIALIZER(ctabhead);
     55 static TAILQ_HEAD(, jobentry) jobhead   = TAILQ_HEAD_INITIALIZER(jobhead);
     56 static char *config  = "/etc/crontab";
     57 static char *pidfile = "/var/run/crond.pid";
     58 static int   nflag;
     59 
     60 static void
     61 loginfo(const char *fmt, ...)
     62 {
     63   va_list ap;
     64   va_start(ap, fmt);
     65 #if FEATURE_LOGGER_SYSLOG
     66   if (nflag == 0)
     67     vsyslog(LOG_INFO, fmt, ap);
     68   else
     69 #endif
     70     vfprintf(stdout, fmt, ap);
     71   fflush(stdout);
     72   va_end(ap);
     73 }
     74 
     75 static void
     76 logwarn(const char *fmt, ...)
     77 {
     78   va_list ap;
     79   va_start(ap, fmt);
     80 #if FEATURE_LOGGER_SYSLOG
     81   if (nflag == 0)
     82     vsyslog(LOG_WARNING, fmt, ap);
     83   else
     84 #endif
     85     vfprintf(stderr, fmt, ap);
     86   va_end(ap);
     87 }
     88 
     89 static void
     90 logerr(const char *fmt, ...)
     91 {
     92   va_list ap;
     93   va_start(ap, fmt);
     94 #if FEATURE_LOGGER_SYSLOG
     95   if (nflag == 0)
     96     vsyslog(LOG_ERR, fmt, ap);
     97   else
     98 #endif
     99     vfprintf(stderr, fmt, ap);
    100   va_end(ap);
    101 }
    102 
    103 static void
    104 runjob(char *cmd)
    105 {
    106   struct jobentry *je;
    107   time_t           t;
    108   pid_t            pid;
    109 
    110   t = time(NULL);
    111 
    112   /* if command is already running, skip it */
    113   TAILQ_FOREACH(je, &jobhead, entry)
    114   {
    115     if (strcmp(je->cmd, cmd) == 0) {
    116       loginfo("already running %s pid: %d at %s", je->cmd, je->pid, ctime(&t));
    117       return;
    118     }
    119   }
    120 
    121   switch ((pid = fork())) {
    122     case -1:
    123       logerr("error: failed to fork job: %s time: %s", cmd, ctime(&t));
    124       return;
    125     case 0:
    126       setsid();
    127       loginfo("run: %s pid: %d at %s", cmd, getpid(), ctime(&t));
    128       wexecv_self(ARUU_PATH_BIN "/sh", (char *const[]){"sh", "-c", cmd, NULL});
    129       logerr("error: failed to execute job: %s time: %s", cmd, ctime(&t));
    130       _exit(1);
    131     default:
    132       je      = emalloc(sizeof(*je));
    133       je->cmd = estrdup(cmd);
    134       je->pid = pid;
    135       TAILQ_INSERT_TAIL(&jobhead, je, entry);
    136   }
    137 }
    138 
    139 static void
    140 waitjob(void)
    141 {
    142   struct jobentry *je, *tmp;
    143   int              status;
    144   time_t           t;
    145   pid_t            pid;
    146 
    147   t = time(NULL);
    148 
    149   while ((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
    150     je = NULL;
    151     TAILQ_FOREACH(tmp, &jobhead, entry)
    152     {
    153       if (tmp->pid == pid) {
    154         je = tmp;
    155         break;
    156       }
    157     }
    158     if (je) {
    159       TAILQ_REMOVE(&jobhead, je, entry);
    160       free(je->cmd);
    161       free(je);
    162     }
    163     if (WIFEXITED(status) == 1)
    164       loginfo("complete: pid: %d returned: %d time: %s", pid, WEXITSTATUS(status), ctime(&t));
    165     else if (WIFSIGNALED(status) == 1)
    166       loginfo(
    167           "complete: pid: %d terminated by signal: %s "
    168           "time: %s",
    169           pid,
    170           strsignal(WTERMSIG(status)),
    171           ctime(&t)
    172       );
    173     else if (WIFSTOPPED(status) == 1)
    174       loginfo(
    175           "complete: pid: %d stopped by signal: %s time: "
    176           "%s",
    177           pid,
    178           strsignal(WSTOPSIG(status)),
    179           ctime(&t)
    180       );
    181   }
    182 }
    183 
    184 static int
    185 isleap(int year)
    186 {
    187   if (year % 400 == 0)
    188     return 1;
    189   if (year % 100 == 0)
    190     return 0;
    191   return (year % 4 == 0);
    192 }
    193 
    194 static int
    195 daysinmon(int mon, int year)
    196 {
    197   int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    198   if (year < 1900)
    199     year += 1900;
    200   if (isleap(year))
    201     days[1] = 29;
    202   return days[mon];
    203 }
    204 
    205 static int
    206 matchentry(struct ctabentry *cte, struct tm *tm)
    207 {
    208   struct {
    209     struct field *f;
    210     int           tm;
    211     int           len;
    212   } matchtbl[] = {
    213       {.f = &cte->min, .tm = tm->tm_min, .len = 60},
    214       {.f = &cte->hour, .tm = tm->tm_hour, .len = 24},
    215       {.f = &cte->mday, .tm = tm->tm_mday, .len = daysinmon(tm->tm_mon, tm->tm_year)},
    216       {.f = &cte->mon, .tm = tm->tm_mon, .len = 12},
    217       {.f = &cte->wday, .tm = tm->tm_wday, .len = 7},
    218   };
    219   size_t i;
    220   int    j;
    221 
    222   for (i = 0; i < LEN(matchtbl); i++) {
    223     switch (matchtbl[i].f->type) {
    224       case WILDCARD:
    225         continue;
    226       case NUMBER:
    227         if (matchtbl[i].f->val[0] == matchtbl[i].tm)
    228           continue;
    229         break;
    230       case RANGE:
    231         if (matchtbl[i].f->val[0] <= matchtbl[i].tm)
    232           if (matchtbl[i].f->val[1] >= matchtbl[i].tm)
    233             continue;
    234         break;
    235       case REPEAT:
    236         if (matchtbl[i].tm > 0) {
    237           if (matchtbl[i].tm % matchtbl[i].f->val[0] == 0)
    238             continue;
    239         } else {
    240           if (matchtbl[i].len % matchtbl[i].f->val[0] == 0)
    241             continue;
    242         }
    243         break;
    244       case LIST:
    245         for (j = 0; j < matchtbl[i].f->len; j++)
    246           if (matchtbl[i].f->val[j] == matchtbl[i].tm)
    247             break;
    248         if (j < matchtbl[i].f->len)
    249           continue;
    250         break;
    251       default:
    252         break;
    253     }
    254     break;
    255   }
    256   if (i != LEN(matchtbl))
    257     return 0;
    258   return 1;
    259 }
    260 
    261 static int
    262 parsefield(const char *field, long low, long high, struct field *f)
    263 {
    264   int         i;
    265   char       *e1, *e2;
    266   const char *p;
    267 
    268   p = field;
    269   while (isdigit(*p))
    270     p++;
    271 
    272   f->type = ERROR;
    273 
    274   switch (*p) {
    275     case '*':
    276       if (strcmp(field, "*") == 0) {
    277         f->val  = NULL;
    278         f->len  = 0;
    279         f->type = WILDCARD;
    280       } else if (strncmp(field, "*/", 2) == 0) {
    281         f->val = emalloc(sizeof(*f->val));
    282         f->len = 1;
    283 
    284         errno     = 0;
    285         f->val[0] = strtol(field + 2, &e1, 10);
    286         if (e1[0] != '\0' || errno != 0 || f->val[0] == 0)
    287           break;
    288 
    289         f->type = REPEAT;
    290       }
    291       break;
    292     case '\0':
    293       f->val = emalloc(sizeof(*f->val));
    294       f->len = 1;
    295 
    296       errno     = 0;
    297       f->val[0] = strtol(field, &e1, 10);
    298       if (e1[0] != '\0' || errno != 0)
    299         break;
    300 
    301       f->type = NUMBER;
    302       break;
    303     case '-':
    304       f->val = emalloc(2 * sizeof(*f->val));
    305       f->len = 2;
    306 
    307       errno     = 0;
    308       f->val[0] = strtol(field, &e1, 10);
    309       if (e1[0] != '-' || errno != 0)
    310         break;
    311 
    312       errno     = 0;
    313       f->val[1] = strtol(e1 + 1, &e2, 10);
    314       if (e2[0] != '\0' || errno != 0)
    315         break;
    316 
    317       f->type = RANGE;
    318       break;
    319     case ',':
    320       for (i = 1; isdigit(*p) || *p == ','; p++)
    321         if (*p == ',')
    322           i++;
    323       f->val = emalloc(i * sizeof(*f->val));
    324       f->len = i;
    325 
    326       errno     = 0;
    327       f->val[0] = strtol(field, &e1, 10);
    328       if (f->val[0] < low || f->val[0] > high)
    329         break;
    330 
    331       for (i = 1; *e1 == ',' && errno == 0; i++) {
    332         errno     = 0;
    333         f->val[i] = strtol(e1 + 1, &e2, 10);
    334         e1        = e2;
    335       }
    336       if (e1[0] != '\0' || errno != 0)
    337         break;
    338 
    339       f->type = LIST;
    340       break;
    341     default:
    342       return -1;
    343   }
    344 
    345   for (i = 0; i < f->len; i++)
    346     if (f->val[i] < low || f->val[i] > high)
    347       f->type = ERROR;
    348 
    349   if (f->type == ERROR) {
    350     free(f->val);
    351     return -1;
    352   }
    353 
    354   return 0;
    355 }
    356 
    357 static void
    358 freecte(struct ctabentry *cte, int nfields)
    359 {
    360   switch (nfields) {
    361     case 6:
    362       free(cte->cmd);
    363       /* fallthrough */
    364     case 5:
    365       free(cte->wday.val);
    366       /* fallthrough */
    367     case 4:
    368       free(cte->mon.val);
    369       /* fallthrough */
    370     case 3:
    371       free(cte->mday.val);
    372       /* fallthrough */
    373     case 2:
    374       free(cte->hour.val);
    375       /* fallthrough */
    376     case 1:
    377       free(cte->min.val);
    378   }
    379   free(cte);
    380 }
    381 
    382 static void
    383 unloadentries(void)
    384 {
    385   struct ctabentry *cte, *tmp;
    386 
    387   for (cte = TAILQ_FIRST(&ctabhead); cte; cte = tmp) {
    388     tmp = TAILQ_NEXT(cte, entry);
    389     TAILQ_REMOVE(&ctabhead, cte, entry);
    390     freecte(cte, 6);
    391   }
    392 }
    393 
    394 static int
    395 loadentries(void)
    396 {
    397   struct ctabentry *cte;
    398   FILE             *fp;
    399   char             *line = NULL, *p, *col;
    400   int               r    = 0, y;
    401   size_t            size = 0;
    402   ssize_t           len;
    403   struct fieldlimits {
    404     char         *name;
    405     long          min;
    406     long          max;
    407     struct field *f;
    408   } flim[] = {
    409       {"min", 0, 59, NULL},
    410       {"hour", 0, 23, NULL},
    411       {"mday", 1, 31, NULL},
    412       {"mon", 1, 12, NULL},
    413       {"wday", 0, 6, NULL}
    414   };
    415   size_t x;
    416 
    417   if ((fp = fopen(config, "r")) == NULL) {
    418     logerr("error: can't open %s: %s\n", config, strerror(errno));
    419     return -1;
    420   }
    421 
    422   for (y = 0; (len = getline(&line, &size, fp)) != -1; y++) {
    423     p = line;
    424     if (line[0] == '#' || line[0] == '\n' || line[0] == '\0')
    425       continue;
    426 
    427     cte       = emalloc(sizeof(*cte));
    428     flim[0].f = &cte->min;
    429     flim[1].f = &cte->hour;
    430     flim[2].f = &cte->mday;
    431     flim[3].f = &cte->mon;
    432     flim[4].f = &cte->wday;
    433 
    434     for (x = 0; x < LEN(flim); x++) {
    435       do
    436         col = strsep(&p, "\t\n ");
    437       while (col && col[0] == '\0');
    438 
    439       if (!col || parsefield(col, flim[x].min, flim[x].max, flim[x].f) < 0) {
    440         logerr(
    441             "error: failed to parse `%s' field on "
    442             "line %d\n",
    443             flim[x].name,
    444             y + 1
    445         );
    446         freecte(cte, x);
    447         r = -1;
    448         break;
    449       }
    450     }
    451 
    452     if (r == -1)
    453       break;
    454 
    455     col = strsep(&p, "\n");
    456     if (col)
    457       while (col[0] == '\t' || col[0] == ' ')
    458         col++;
    459     if (!col || col[0] == '\0') {
    460       logerr("error: missing `cmd' field on line %d\n", y + 1);
    461       freecte(cte, 5);
    462       r = -1;
    463       break;
    464     }
    465     cte->cmd = estrdup(col);
    466 
    467     TAILQ_INSERT_TAIL(&ctabhead, cte, entry);
    468   }
    469 
    470   if (r < 0)
    471     unloadentries();
    472 
    473   free(line);
    474   fclose(fp);
    475 
    476   return r;
    477 }
    478 
    479 static void
    480 reloadentries(void)
    481 {
    482   unloadentries();
    483   if (loadentries() < 0)
    484     logwarn("warning: discarding old crontab entries\n");
    485 }
    486 
    487 static void
    488 sighandler(int sig)
    489 {
    490   switch (sig) {
    491     case SIGCHLD:
    492       chldreap = 1;
    493       break;
    494     case SIGHUP:
    495       reload = 1;
    496       break;
    497     case SIGTERM:
    498       quit = 1;
    499       break;
    500   }
    501 }
    502 
    503 static void
    504 usage(void)
    505 {
    506   eprintf("usage: %s [-f file] [-n]\n", argv0);
    507 }
    508 
    509 // ?man cron: cron daemon
    510 // ?man daemon to run scheduled background commands
    511 int
    512 main(int argc, char *argv[])
    513 {
    514   FILE             *fp;
    515   struct ctabentry *cte;
    516   time_t            t;
    517   struct tm        *tm;
    518   struct sigaction  sa;
    519 
    520   ARGBEGIN
    521   {
    522     // ?man -n: print line numbers or counts
    523     case 'n':
    524       nflag = 1;
    525       break;
    526     // ?man -f:str: force the operation
    527     case 'f':
    528       config = EARGF(usage());
    529       break;
    530     default:
    531       usage();
    532   }
    533   ARGEND
    534 
    535   if (argc > 0)
    536     usage();
    537 
    538   if (nflag == 0) {
    539 #if FEATURE_LOGGER_SYSLOG
    540     openlog(argv[0], LOG_CONS | LOG_PID, LOG_CRON);
    541 #endif
    542 #if FEATURE_CRON_DAEMON
    543     if (daemon(1, 0) < 0) {
    544       logerr("error: failed to daemonize %s\n", strerror(errno));
    545       return 1;
    546     }
    547 #else
    548     eprintf("cron: daemon support not built\n");
    549 #endif
    550     if ((fp = fopen(pidfile, "w"))) {
    551       fprintf(fp, "%d\n", getpid());
    552       fclose(fp);
    553     }
    554   }
    555 
    556   sa.sa_handler = sighandler;
    557   sigfillset(&sa.sa_mask);
    558   sa.sa_flags = SA_RESTART;
    559   sigaction(SIGCHLD, &sa, NULL);
    560   sigaction(SIGHUP, &sa, NULL);
    561   sigaction(SIGTERM, &sa, NULL);
    562 
    563   loadentries();
    564 
    565   while (1) {
    566     t = time(NULL);
    567     sleep(60 - t % 60);
    568 
    569     if (quit == 1) {
    570       if (nflag == 0)
    571         unlink(pidfile);
    572       unloadentries();
    573       /* dont wait or kill forked processes, just exit */
    574       break;
    575     }
    576 
    577     if (reload == 1 || chldreap == 1) {
    578       if (reload == 1) {
    579         reloadentries();
    580         reload = 0;
    581       }
    582       if (chldreap == 1) {
    583         waitjob();
    584         chldreap = 0;
    585       }
    586       continue;
    587     }
    588 
    589     TAILQ_FOREACH(cte, &ctabhead, entry)
    590     {
    591       t  = time(NULL);
    592       tm = localtime(&t);
    593       if (matchentry(cte, tm) == 1)
    594         runjob(cte->cmd);
    595     }
    596   }
    597 
    598 #if FEATURE_LOGGER_SYSLOG
    599   if (nflag == 0)
    600     closelog();
    601 #endif
    602 
    603   return 0;
    604 }