crond: support @daily etc
[oweals/busybox.git] / miscutils / crond.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * run as root, but NOT setuid root
4  *
5  * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com)
6  * (version 2.3.2)
7  * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10  */
11 //config:config CROND
12 //config:       bool "crond"
13 //config:       default y
14 //config:       select FEATURE_SYSLOG
15 //config:       help
16 //config:         Crond is a background daemon that parses individual crontab
17 //config:         files and executes commands on behalf of the users in question.
18 //config:         This is a port of dcron from slackware. It uses files of the
19 //config:         format /var/spool/cron/crontabs/<username> files, for example:
20 //config:             $ cat /var/spool/cron/crontabs/root
21 //config:             # Run daily cron jobs at 4:40 every day:
22 //config:             40 4 * * * /etc/cron/daily > /dev/null 2>&1
23 //config:
24 //config:config FEATURE_CROND_D
25 //config:       bool "Support option -d to redirect output to stderr"
26 //config:       depends on CROND
27 //config:       default y
28 //config:       help
29 //config:         -d N sets loglevel (0:most verbose) and directs all output to stderr.
30 //config:
31 //config:config FEATURE_CROND_CALL_SENDMAIL
32 //config:       bool "Report command output via email (using sendmail)"
33 //config:       default y
34 //config:       depends on CROND
35 //config:       help
36 //config:         Command output will be sent to corresponding user via email.
37 //config:
38 //config:config FEATURE_CROND_SPECIAL_TIMES
39 //config:       bool "Support special times (@reboot, @daily, etc) in crontabs"
40 //config:       default y
41 //config:       depends on CROND
42 //config:       help
43 //config:         string        meaning
44 //config:         ------        -------
45 //config:         @reboot       Run once, at startup
46 //config:         @yearly       Run once a year:  "0 0 1 1 *"
47 //config:         @annually     Same as @yearly:  "0 0 1 1 *"
48 //config:         @monthly      Run once a month: "0 0 1 * *"
49 //config:         @weekly       Run once a week:  "0 0 * * 0"
50 //config:         @daily        Run once a day:   "0 0 * * *"
51 //config:         @midnight     Same as @daily:   "0 0 * * *"
52 //config:         @hourly       Run once an hour: "0 * * * *"
53 //config:
54 //config:config FEATURE_CROND_DIR
55 //config:       string "crond spool directory"
56 //config:       default "/var/spool/cron"
57 //config:       depends on CROND || CRONTAB
58 //config:       help
59 //config:         Location of crond spool.
60
61 //applet:IF_CROND(APPLET(crond, BB_DIR_USR_SBIN, BB_SUID_DROP))
62
63 //kbuild:lib-$(CONFIG_CROND) += crond.o
64
65 //usage:#define crond_trivial_usage
66 //usage:       "-fbS -l N " IF_FEATURE_CROND_D("-d N ") "-L LOGFILE -c DIR"
67 //usage:#define crond_full_usage "\n\n"
68 //usage:       "        -f      Foreground"
69 //usage:     "\n        -b      Background (default)"
70 //usage:     "\n        -S      Log to syslog (default)"
71 //usage:     "\n        -l N    Set log level. Most verbose 0, default 8"
72 //usage:        IF_FEATURE_CROND_D(
73 //usage:     "\n        -d N    Set log level, log to stderr"
74 //usage:        )
75 //usage:     "\n        -L FILE Log to FILE"
76 //usage:     "\n        -c DIR  Cron dir. Default:"CONFIG_FEATURE_CROND_DIR"/crontabs"
77
78 #include "libbb.h"
79 #include "common_bufsiz.h"
80 #include <syslog.h>
81
82 /* glibc frees previous setenv'ed value when we do next setenv()
83  * of the same variable. uclibc does not do this! */
84 #if (defined(__GLIBC__) && !defined(__UCLIBC__)) /* || OTHER_SAFE_LIBC... */
85 # define SETENV_LEAKS 0
86 #else
87 # define SETENV_LEAKS 1
88 #endif
89
90
91 #define CRON_DIR        CONFIG_FEATURE_CROND_DIR
92 #define CRONTABS        CONFIG_FEATURE_CROND_DIR "/crontabs"
93 #define CRON_REBOOT     CONFIG_PID_FILE_PATH "/crond.reboot"
94 #ifndef SENDMAIL
95 # define SENDMAIL       "sendmail"
96 #endif
97 #ifndef SENDMAIL_ARGS
98 # define SENDMAIL_ARGS  "-ti"
99 #endif
100 #ifndef CRONUPDATE
101 # define CRONUPDATE     "cron.update"
102 #endif
103 #ifndef MAXLINES
104 # define MAXLINES       256  /* max lines in non-root crontabs */
105 #endif
106
107
108 typedef struct CronFile {
109         struct CronFile *cf_next;
110         struct CronLine *cf_lines;
111         char *cf_username;
112         smallint cf_wants_starting;     /* bool: one or more jobs ready */
113         smallint cf_has_running;        /* bool: one or more jobs running */
114         smallint cf_deleted;            /* marked for deletion (but still has running jobs) */
115 } CronFile;
116
117 typedef struct CronLine {
118         struct CronLine *cl_next;
119         char *cl_cmd;                   /* shell command */
120         pid_t cl_pid;                   /* >0:running, <0:needs to be started in this minute, 0:dormant */
121 #define START_ME_REBOOT -2
122 #define START_ME_NORMAL -1
123 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
124         int cl_empty_mail_size;         /* size of mail header only, 0 if no mailfile */
125         char *cl_mailto;                /* whom to mail results, may be NULL */
126 #endif
127         char *cl_shell;
128         /* ordered by size, not in natural order. makes code smaller: */
129         char cl_Dow[7];                 /* 0-6, beginning sunday */
130         char cl_Mons[12];               /* 0-11 */
131         char cl_Hrs[24];                /* 0-23 */
132         char cl_Days[32];               /* 1-31 */
133         char cl_Mins[60];               /* 0-59 */
134 } CronLine;
135
136
137 #define DAEMON_UID 0
138
139
140 enum {
141         OPT_l = (1 << 0),
142         OPT_L = (1 << 1),
143         OPT_f = (1 << 2),
144         OPT_b = (1 << 3),
145         OPT_S = (1 << 4),
146         OPT_c = (1 << 5),
147         OPT_d = (1 << 6) * ENABLE_FEATURE_CROND_D,
148 };
149
150 struct globals {
151         unsigned log_level; /* = 8; */
152         time_t crontab_dir_mtime;
153         const char *log_filename;
154         const char *crontab_dir_name; /* = CRONTABS; */
155         CronFile *cron_files;
156 #if SETENV_LEAKS
157         char *env_var_user;
158         char *env_var_home;
159         char *env_var_shell;
160         char *env_var_logname;
161 #endif
162 } FIX_ALIASING;
163 #define G (*(struct globals*)bb_common_bufsiz1)
164 #define INIT_G() do { \
165         setup_common_bufsiz(); \
166         G.log_level = 8; \
167         G.crontab_dir_name = CRONTABS; \
168 } while (0)
169
170 /* Log levels:
171  * 0 is the most verbose, default 8.
172  * For some reason, in fact only 5, 7 and 8 are used.
173  */
174 static void crondlog(unsigned level, const char *msg, va_list va)
175 {
176         if (level >= G.log_level) {
177                 /*
178                  * We are called only for info meesages.
179                  * Warnings/errors use plain bb_[p]error_msg's, which
180                  * need not touch syslog_level
181                  * (they are ok with LOG_ERR default).
182                  */
183                 syslog_level = LOG_INFO;
184                 bb_verror_msg(msg, va, /* strerr: */ NULL);
185                 syslog_level = LOG_ERR;
186         }
187 }
188
189 static void log5(const char *msg, ...)
190 {
191         va_list va;
192         va_start(va, msg);
193         crondlog(4, msg, va);
194         va_end(va);
195 }
196
197 static void log7(const char *msg, ...)
198 {
199         va_list va;
200         va_start(va, msg);
201         crondlog(7, msg, va);
202         va_end(va);
203 }
204
205 static void log8(const char *msg, ...)
206 {
207         va_list va;
208         va_start(va, msg);
209         crondlog(8, msg, va);
210         va_end(va);
211 }
212
213
214 static const char DowAry[] ALIGN1 =
215         "sun""mon""tue""wed""thu""fri""sat"
216 ;
217
218 static const char MonAry[] ALIGN1 =
219         "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
220 ;
221
222 static void ParseField(char *user, char *ary, int modvalue, int off,
223                                 const char *names, char *ptr)
224 /* 'names' is a pointer to a set of 3-char abbreviations */
225 {
226         char *base = ptr;
227         int n1 = -1;
228         int n2 = -1;
229
230         // this can't happen due to config_read()
231         /*if (base == NULL)
232                 return;*/
233
234         while (1) {
235                 int skip = 0;
236
237                 /* Handle numeric digit or symbol or '*' */
238                 if (*ptr == '*') {
239                         n1 = 0;  /* everything will be filled */
240                         n2 = modvalue - 1;
241                         skip = 1;
242                         ++ptr;
243                 } else if (isdigit(*ptr)) {
244                         char *endp;
245                         if (n1 < 0) {
246                                 n1 = strtol(ptr, &endp, 10) + off;
247                         } else {
248                                 n2 = strtol(ptr, &endp, 10) + off;
249                         }
250                         ptr = endp; /* gcc likes temp var for &endp */
251                         skip = 1;
252                 } else if (names) {
253                         int i;
254
255                         for (i = 0; names[i]; i += 3) {
256                                 /* was using strncmp before... */
257                                 if (strncasecmp(ptr, &names[i], 3) == 0) {
258                                         ptr += 3;
259                                         if (n1 < 0) {
260                                                 n1 = i / 3;
261                                         } else {
262                                                 n2 = i / 3;
263                                         }
264                                         skip = 1;
265                                         break;
266                                 }
267                         }
268                 }
269
270                 /* handle optional range '-' */
271                 if (skip == 0) {
272                         goto err;
273                 }
274                 if (*ptr == '-' && n2 < 0) {
275                         ++ptr;
276                         continue;
277                 }
278
279                 /*
280                  * collapse single-value ranges, handle skipmark, and fill
281                  * in the character array appropriately.
282                  */
283                 if (n2 < 0) {
284                         n2 = n1;
285                 }
286                 if (*ptr == '/') {
287                         char *endp;
288                         skip = strtol(ptr + 1, &endp, 10);
289                         ptr = endp; /* gcc likes temp var for &endp */
290                 }
291
292                 /*
293                  * fill array, using a failsafe is the easiest way to prevent
294                  * an endless loop
295                  */
296                 {
297                         int s0 = 1;
298                         int failsafe = 1024;
299
300                         --n1;
301                         do {
302                                 n1 = (n1 + 1) % modvalue;
303
304                                 if (--s0 == 0) {
305                                         ary[n1 % modvalue] = 1;
306                                         s0 = skip;
307                                 }
308                                 if (--failsafe == 0) {
309                                         goto err;
310                                 }
311                         } while (n1 != n2);
312                 }
313                 if (*ptr != ',') {
314                         break;
315                 }
316                 ++ptr;
317                 n1 = -1;
318                 n2 = -1;
319         }
320
321         if (*ptr) {
322  err:
323                 bb_error_msg("user %s: parse error at %s", user, base);
324                 return;
325         }
326
327         /* can't use log5 (it inserts newlines), open-coding it */
328         if (G.log_level <= 5 && logmode != LOGMODE_SYSLOG) {
329                 int i;
330                 for (i = 0; i < modvalue; ++i)
331                         fprintf(stderr, "%d", (unsigned char)ary[i]);
332                 bb_putchar_stderr('\n');
333         }
334 }
335
336 static void FixDayDow(CronLine *line)
337 {
338         unsigned i;
339         int weekUsed = 0;
340         int daysUsed = 0;
341
342         for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
343                 if (line->cl_Dow[i] == 0) {
344                         weekUsed = 1;
345                         break;
346                 }
347         }
348         for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
349                 if (line->cl_Days[i] == 0) {
350                         daysUsed = 1;
351                         break;
352                 }
353         }
354         if (weekUsed != daysUsed) {
355                 if (weekUsed)
356                         memset(line->cl_Days, 0, sizeof(line->cl_Days));
357                 else /* daysUsed */
358                         memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
359         }
360 }
361
362 /*
363  * delete_cronfile() - delete user database
364  *
365  * Note: multiple entries for same user may exist if we were unable to
366  * completely delete a database due to running processes.
367  */
368 //FIXME: we will start a new job even if the old job is running
369 //if crontab was reloaded: crond thinks that "new" job is different from "old"
370 //even if they are in fact completely the same. Example
371 //Crontab was:
372 // 0-59 * * * * job1
373 // 0-59 * * * * long_running_job2
374 //User edits crontab to:
375 // 0-59 * * * * job1_updated
376 // 0-59 * * * * long_running_job2
377 //Bug: crond can now start another long_running_job2 even if old one
378 //is still running.
379 //OTOH most other versions of cron do not wait for job termination anyway,
380 //they end up with multiple copies of jobs if they don't terminate soon enough.
381 static void delete_cronfile(const char *userName)
382 {
383         CronFile **pfile = &G.cron_files;
384         CronFile *file;
385
386         while ((file = *pfile) != NULL) {
387                 if (strcmp(userName, file->cf_username) == 0) {
388                         CronLine **pline = &file->cf_lines;
389                         CronLine *line;
390
391                         file->cf_has_running = 0;
392                         file->cf_deleted = 1;
393
394                         while ((line = *pline) != NULL) {
395                                 if (line->cl_pid > 0) {
396                                         file->cf_has_running = 1;
397                                         pline = &line->cl_next;
398                                 } else {
399                                         *pline = line->cl_next;
400                                         free(line->cl_cmd);
401                                         free(line);
402                                 }
403                         }
404                         if (file->cf_has_running == 0) {
405                                 *pfile = file->cf_next;
406                                 free(file->cf_username);
407                                 free(file);
408                                 continue;
409                         }
410                 }
411                 pfile = &file->cf_next;
412         }
413 }
414
415 static void load_crontab(const char *fileName)
416 {
417         struct parser_t *parser;
418         struct stat sbuf;
419         int maxLines;
420         char *tokens[6];
421 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
422         char *mailTo = NULL;
423 #endif
424         char *shell = NULL;
425
426         delete_cronfile(fileName);
427
428         if (!getpwnam(fileName)) {
429                 log7("ignoring file '%s' (no such user)", fileName);
430                 return;
431         }
432
433         parser = config_open(fileName);
434         if (!parser)
435                 return;
436
437         maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
438
439         if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DAEMON_UID) {
440                 CronFile *file = xzalloc(sizeof(CronFile));
441                 CronLine **pline;
442                 int n;
443
444                 file->cf_username = xstrdup(fileName);
445                 pline = &file->cf_lines;
446
447                 while (1) {
448                         CronLine *line;
449
450                         if (!--maxLines) {
451                                 bb_error_msg("user %s: too many lines", fileName);
452                                 break;
453                         }
454
455                         n = config_read(parser, tokens, 6, 1, "# \t", PARSE_NORMAL | PARSE_KEEP_COPY);
456                         if (!n)
457                                 break;
458
459                         log5("user:%s entry:%s", fileName, parser->data);
460
461                         /* check if line is setting MAILTO= */
462                         if (is_prefixed_with(tokens[0], "MAILTO=")) {
463 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
464                                 free(mailTo);
465                                 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
466 #endif /* otherwise just ignore such lines */
467                                 continue;
468                         }
469                         if (is_prefixed_with(tokens[0], "SHELL=")) {
470                                 free(shell);
471                                 shell = xstrdup(&tokens[0][6]);
472                                 continue;
473                         }
474 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
475                         if (tokens[0][0] == '@') {
476                                 /*
477                                  * "@daily /a/script/to/run PARAM1 PARAM2..."
478                                  */
479                                 typedef struct SpecialEntry {
480                                         const char *name;
481                                         const char tokens[8];
482                                 } SpecialEntry;
483                                 static const SpecialEntry SpecAry[] = {
484                                         /*              hour  day   month weekday */
485                                         { "yearly",     "0\0" "1\0" "1\0" "*" },
486                                         { "annually",   "0\0" "1\0" "1\0" "*" },
487                                         { "monthly",    "0\0" "1\0" "*\0" "*" },
488                                         { "weekly",     "0\0" "*\0" "*\0" "0" },
489                                         { "daily",      "0\0" "*\0" "*\0" "*" },
490                                         { "midnight",   "0\0" "*\0" "*\0" "*" },
491                                         { "hourly",     "*\0" "*\0" "*\0" "*" },
492                                         { "reboot",     ""                    },
493                                 };
494                                 const SpecialEntry *e = SpecAry;
495
496                                 if (n < 2)
497                                         continue;
498                                 for (;;) {
499                                         if (strcmp(e->name, tokens[0] + 1) == 0) {
500                                                 /*
501                                                  * tokens[1] is only the first word of command,
502                                                  * find the entire command in unmodified string:
503                                                  */
504                                                 tokens[5] = strstr(
505                                                         skip_non_whitespace(skip_whitespace(parser->data)),
506                                                         /* ^^^^ avoids mishandling e.g. "@daily aily PARAM" */
507                                                         tokens[1]
508                                                 );
509                                                 if (e->tokens[0]) {
510                                                         char *et = (char*)e->tokens;
511                                                         /* minute is "0" for all specials */
512                                                         tokens[0] = (char*)"0";
513                                                         tokens[1] = et;
514                                                         tokens[2] = et + 2;
515                                                         tokens[3] = et + 4;
516                                                         tokens[4] = et + 6;
517                                                 }
518                                                 goto got_it;
519                                         }
520                                         if (!e->tokens[0])
521                                                 break;
522                                         e++;
523                                 }
524                                 continue; /* bad line (unrecognized '@foo') */
525                         }
526 #endif
527 //TODO: handle HOME= too? "man crontab" says:
528 //name = value
529 //
530 //where the spaces around the equal-sign (=) are optional, and any subsequent
531 //non-leading spaces in value will be part of the value assigned to name.
532 //The value string may be placed in quotes (single or double, but matching)
533 //to preserve leading or trailing blanks.
534 //
535 //Several environment variables are set up automatically by the cron(8) daemon.
536 //SHELL is set to /bin/sh, and LOGNAME and HOME are set from the /etc/passwd
537 //line of the crontab's owner. HOME and SHELL may be overridden by settings
538 //in the crontab; LOGNAME may not.
539
540                         /* check if a minimum of tokens is specified */
541                         if (n < 6)
542                                 continue;
543  IF_FEATURE_CROND_SPECIAL_TIMES(
544   got_it:
545  )
546                         *pline = line = xzalloc(sizeof(*line));
547 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
548                         if (tokens[0][0] == '@') { /* "@reboot" line */
549                                 file->cf_wants_starting = 1;
550                                 line->cl_pid = START_ME_REBOOT; /* wants to start */
551                                 /* line->cl_Mins/Hrs/etc stay zero: never match any time */
552                         } else
553 #endif
554                         {
555                                 /* parse date ranges */
556                                 ParseField(file->cf_username, line->cl_Mins, 60, 0, NULL, tokens[0]);
557                                 ParseField(file->cf_username, line->cl_Hrs, 24, 0, NULL, tokens[1]);
558                                 ParseField(file->cf_username, line->cl_Days, 32, 0, NULL, tokens[2]);
559                                 ParseField(file->cf_username, line->cl_Mons, 12, -1, MonAry, tokens[3]);
560                                 ParseField(file->cf_username, line->cl_Dow, 7, 0, DowAry, tokens[4]);
561                                 /*
562                                  * fix days and dow - if one is not "*" and the other
563                                  * is "*", the other is set to 0, and vise-versa
564                                  */
565                                 FixDayDow(line);
566                         }
567 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
568                         /* copy mailto (can be NULL) */
569                         line->cl_mailto = xstrdup(mailTo);
570 #endif
571                         line->cl_shell = xstrdup(shell);
572                         /* copy command */
573                         line->cl_cmd = xstrdup(tokens[5]);
574                         pline = &line->cl_next;
575 //bb_error_msg("M[%s]F[%s][%s][%s][%s][%s][%s]", mailTo, tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]);
576                 }
577                 *pline = NULL;
578
579                 file->cf_next = G.cron_files;
580                 G.cron_files = file;
581         }
582         config_close(parser);
583 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
584         free(mailTo);
585 #endif
586         free(shell);
587 }
588
589 static void process_cron_update_file(void)
590 {
591         FILE *fi;
592         char buf[256];
593
594         fi = fopen_for_read(CRONUPDATE);
595         if (fi != NULL) {
596                 unlink(CRONUPDATE);
597                 while (fgets(buf, sizeof(buf), fi) != NULL) {
598                         /* use first word only */
599                         skip_non_whitespace(buf)[0] = '\0';
600                         load_crontab(buf);
601                 }
602                 fclose(fi);
603         }
604 }
605
606 static void rescan_crontab_dir(void)
607 {
608         CronFile *file;
609
610         /* Delete all files until we only have ones with running jobs (or none) */
611  again:
612         for (file = G.cron_files; file; file = file->cf_next) {
613                 if (!file->cf_deleted) {
614                         delete_cronfile(file->cf_username);
615                         goto again;
616                 }
617         }
618
619         /* Remove cron update file */
620         unlink(CRONUPDATE);
621         /* Re-chdir, in case directory was renamed & deleted */
622         xchdir(G.crontab_dir_name);
623
624         /* Scan directory and add associated users */
625         {
626                 DIR *dir = opendir(".");
627                 struct dirent *den;
628
629                 /* xopendir exists, but "can't open '.'" is not informative */
630                 if (!dir)
631                         bb_error_msg_and_die("can't open '%s'", G.crontab_dir_name);
632                 while ((den = readdir(dir)) != NULL) {
633                         if (strchr(den->d_name, '.') != NULL) {
634                                 continue;
635                         }
636                         load_crontab(den->d_name);
637                 }
638                 closedir(dir);
639         }
640 }
641
642 #if SETENV_LEAKS
643 /* We set environment *before* vfork (because we want to use vfork),
644  * so we cannot use setenv() - repeated calls to setenv() may leak memory!
645  * Using putenv(), and freeing memory after unsetenv() won't leak */
646 static void safe_setenv(char **pvar_val, const char *var, const char *val)
647 {
648         char *var_val = *pvar_val;
649
650         if (var_val) {
651                 bb_unsetenv_and_free(var_val);
652         }
653         *pvar_val = xasprintf("%s=%s", var, val);
654         putenv(*pvar_val);
655 }
656 #endif
657
658 static void set_env_vars(struct passwd *pas, const char *shell)
659 {
660         /* POSIX requires crond to set up at least HOME, LOGNAME, PATH, SHELL.
661          * We assume crond inherited suitable PATH.
662          */
663 #if SETENV_LEAKS
664         safe_setenv(&G.env_var_logname, "LOGNAME", pas->pw_name);
665         safe_setenv(&G.env_var_user, "USER", pas->pw_name);
666         safe_setenv(&G.env_var_home, "HOME", pas->pw_dir);
667         safe_setenv(&G.env_var_shell, "SHELL", shell);
668 #else
669         xsetenv("LOGNAME", pas->pw_name);
670         xsetenv("USER", pas->pw_name);
671         xsetenv("HOME", pas->pw_dir);
672         xsetenv("SHELL", shell);
673 #endif
674 }
675
676 static void change_user(struct passwd *pas)
677 {
678         /* careful: we're after vfork! */
679         change_identity(pas); /* - initgroups, setgid, setuid */
680         if (chdir(pas->pw_dir) < 0) {
681                 bb_error_msg("can't change directory to '%s'", pas->pw_dir);
682                 xchdir(CRON_DIR);
683         }
684 }
685
686 // TODO: sendmail should be _run-time_ option, not compile-time!
687 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
688
689 static pid_t
690 fork_job(const char *user, int mailFd, CronLine *line, bool run_sendmail)
691 {
692         struct passwd *pas;
693         const char *shell, *prog;
694         smallint sv_logmode;
695         pid_t pid;
696
697         /* prepare things before vfork */
698         pas = getpwnam(user);
699         if (!pas) {
700                 bb_error_msg("can't get uid for %s", user);
701                 goto err;
702         }
703
704         shell = line->cl_shell ? line->cl_shell : DEFAULT_SHELL;
705         prog = run_sendmail ? SENDMAIL : shell;
706
707         set_env_vars(pas, shell);
708
709         sv_logmode = logmode;
710         pid = vfork();
711         if (pid == 0) {
712                 /* CHILD */
713                 /* initgroups, setgid, setuid, and chdir to home or CRON_DIR */
714                 change_user(pas);
715                 log5("child running %s", prog);
716                 if (mailFd >= 0) {
717                         xmove_fd(mailFd, run_sendmail ? 0 : 1);
718                         dup2(1, 2);
719                 }
720                 /* crond 3.0pl1-100 puts tasks in separate process groups */
721                 bb_setpgrp();
722                 if (!run_sendmail)
723                         execlp(prog, prog, "-c", line->cl_cmd, (char *) NULL);
724                 else
725                         execlp(prog, prog, SENDMAIL_ARGS, (char *) NULL);
726                 /*
727                  * I want this error message on stderr too,
728                  * even if other messages go only to syslog:
729                  */
730                 logmode |= LOGMODE_STDIO;
731                 bb_error_msg_and_die("can't execute '%s' for user %s", prog, user);
732         }
733         logmode = sv_logmode;
734
735         if (pid < 0) {
736                 bb_perror_msg("vfork");
737  err:
738                 pid = 0;
739         } /* else: PARENT, FORK SUCCESS */
740
741         /*
742          * Close the mail file descriptor.. we can't just leave it open in
743          * a structure, closing it later, because we might run out of descriptors
744          */
745         if (mailFd >= 0) {
746                 close(mailFd);
747         }
748         return pid;
749 }
750
751 static pid_t start_one_job(const char *user, CronLine *line)
752 {
753         char mailFile[128];
754         int mailFd = -1;
755
756         line->cl_pid = 0;
757         line->cl_empty_mail_size = 0;
758
759         if (line->cl_mailto) {
760                 /* Open mail file (owner is root so nobody can screw with it) */
761                 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", CRON_DIR, user, getpid());
762                 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
763
764                 if (mailFd >= 0) {
765                         fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_mailto,
766                                 line->cl_cmd);
767                         line->cl_empty_mail_size = lseek(mailFd, 0, SEEK_CUR);
768                 } else {
769                         bb_error_msg("can't create mail file %s for user %s, "
770                                         "discarding output", mailFile, user);
771                 }
772         }
773
774         line->cl_pid = fork_job(user, mailFd, line, /*sendmail?*/ 0);
775         if (mailFd >= 0) {
776                 if (line->cl_pid <= 0) {
777                         unlink(mailFile);
778                 } else {
779                         /* rename mail-file based on pid of process */
780                         char *mailFile2 = xasprintf("%s/cron.%s.%d", CRON_DIR, user, (int)line->cl_pid);
781                         rename(mailFile, mailFile2); // TODO: xrename?
782                         free(mailFile2);
783                 }
784         }
785
786         return line->cl_pid;
787 }
788
789 /*
790  * process_finished_job - called when job terminates and when mail terminates
791  */
792 static void process_finished_job(const char *user, CronLine *line)
793 {
794         pid_t pid;
795         int mailFd;
796         char mailFile[128];
797         struct stat sbuf;
798
799         pid = line->cl_pid;
800         line->cl_pid = 0;
801         if (pid <= 0) {
802                 /* No job */
803                 return;
804         }
805         if (line->cl_empty_mail_size <= 0) {
806                 /* End of job and no mail file, or end of sendmail job */
807                 return;
808         }
809
810         /*
811          * End of primary job - check for mail file.
812          * If size has changed and the file is still valid, we send it.
813          */
814         snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", CRON_DIR, user, (int)pid);
815         mailFd = open(mailFile, O_RDONLY);
816         unlink(mailFile);
817         if (mailFd < 0) {
818                 return;
819         }
820
821         if (fstat(mailFd, &sbuf) < 0
822          || sbuf.st_uid != DAEMON_UID
823          || sbuf.st_nlink != 0
824          || sbuf.st_size == line->cl_empty_mail_size
825          || !S_ISREG(sbuf.st_mode)
826         ) {
827                 close(mailFd);
828                 return;
829         }
830         line->cl_empty_mail_size = 0;
831         /* if (line->cl_mailto) - always true if cl_empty_mail_size was nonzero */
832                 line->cl_pid = fork_job(user, mailFd, line, /*sendmail?*/ 1);
833 }
834
835 #else /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
836
837 static pid_t start_one_job(const char *user, CronLine *line)
838 {
839         const char *shell;
840         struct passwd *pas;
841         pid_t pid;
842
843         pas = getpwnam(user);
844         if (!pas) {
845                 bb_error_msg("can't get uid for %s", user);
846                 goto err;
847         }
848
849         /* Prepare things before vfork */
850         shell = line->cl_shell ? line->cl_shell : DEFAULT_SHELL;
851         set_env_vars(pas, shell);
852
853         /* Fork as the user in question and run program */
854         pid = vfork();
855         if (pid == 0) {
856                 /* CHILD */
857                 /* initgroups, setgid, setuid, and chdir to home or CRON_DIR */
858                 change_user(pas);
859                 log5("child running %s", shell);
860                 /* crond 3.0pl1-100 puts tasks in separate process groups */
861                 bb_setpgrp();
862                 execl(shell, shell, "-c", line->cl_cmd, (char *) NULL);
863                 bb_error_msg_and_die("can't execute '%s' for user %s", shell, user);
864         }
865         if (pid < 0) {
866                 bb_perror_msg("vfork");
867  err:
868                 pid = 0;
869         }
870         line->cl_pid = pid;
871         return pid;
872 }
873
874 #define process_finished_job(user, line)  ((line)->cl_pid = 0)
875
876 #endif /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
877
878 /*
879  * Determine which jobs need to be run.  Under normal conditions, the
880  * period is about a minute (one scan).  Worst case it will be one
881  * hour (60 scans).
882  */
883 static void flag_starting_jobs(time_t t1, time_t t2)
884 {
885         time_t t;
886
887         /* Find jobs > t1 and <= t2 */
888
889         for (t = t1 - t1 % 60; t <= t2; t += 60) {
890                 struct tm *ptm;
891                 CronFile *file;
892                 CronLine *line;
893
894                 if (t <= t1)
895                         continue;
896
897                 ptm = localtime(&t);
898                 for (file = G.cron_files; file; file = file->cf_next) {
899                         log5("file %s:", file->cf_username);
900                         if (file->cf_deleted)
901                                 continue;
902                         for (line = file->cf_lines; line; line = line->cl_next) {
903                                 log5(" line %s", line->cl_cmd);
904                                 if (line->cl_Mins[ptm->tm_min]
905                                  && line->cl_Hrs[ptm->tm_hour]
906                                  && (line->cl_Days[ptm->tm_mday] || line->cl_Dow[ptm->tm_wday])
907                                  && line->cl_Mons[ptm->tm_mon]
908                                 ) {
909                                         log5(" job: %d %s",
910                                                         (int)line->cl_pid, line->cl_cmd);
911                                         if (line->cl_pid > 0) {
912                                                 log8("user %s: process already running: %s",
913                                                         file->cf_username, line->cl_cmd);
914                                         } else if (line->cl_pid == 0) {
915                                                 line->cl_pid = START_ME_NORMAL;
916                                                 file->cf_wants_starting = 1;
917                                         }
918                                 }
919                         }
920                 }
921         }
922 }
923
924 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
925 static int touch_reboot_file(void)
926 {
927         int fd = open(CRON_REBOOT, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, 0000);
928         if (fd >= 0) {
929                 close(fd);
930                 return 1;
931         }
932         /* File (presumably) exists - this is not the first run after reboot */
933         return 0;
934 }
935 #endif
936
937 static void start_jobs(int wants_start)
938 {
939         CronFile *file;
940         CronLine *line;
941
942         for (file = G.cron_files; file; file = file->cf_next) {
943                 if (!file->cf_wants_starting)
944                         continue;
945
946                 file->cf_wants_starting = 0;
947                 for (line = file->cf_lines; line; line = line->cl_next) {
948                         pid_t pid;
949                         if (line->cl_pid != wants_start)
950                                 continue;
951
952                         pid = start_one_job(file->cf_username, line);
953                         log8("USER %s pid %3d cmd %s",
954                                 file->cf_username, (int)pid, line->cl_cmd);
955                         if (pid < 0) {
956                                 file->cf_wants_starting = 1;
957                         }
958                         if (pid > 0) {
959                                 file->cf_has_running = 1;
960                         }
961                 }
962         }
963 }
964
965 /*
966  * Check for job completion, return number of jobs still running after
967  * all done.
968  */
969 static int check_completions(void)
970 {
971         CronFile *file;
972         CronLine *line;
973         int num_still_running = 0;
974
975         for (file = G.cron_files; file; file = file->cf_next) {
976                 if (!file->cf_has_running)
977                         continue;
978
979                 file->cf_has_running = 0;
980                 for (line = file->cf_lines; line; line = line->cl_next) {
981                         int r;
982
983                         if (line->cl_pid <= 0)
984                                 continue;
985
986                         r = waitpid(line->cl_pid, NULL, WNOHANG);
987                         if (r < 0 || r == line->cl_pid) {
988                                 process_finished_job(file->cf_username, line);
989                                 if (line->cl_pid == 0) {
990                                         /* sendmail was not started for it */
991                                         continue;
992                                 }
993                                 /* else: sendmail was started, job is still running, fall thru */
994                         }
995                         /* else: r == 0: "process is still running" */
996                         file->cf_has_running = 1;
997                 }
998 //FIXME: if !file->cf_has_running && file->deleted: delete it!
999 //otherwise deleted entries will stay forever, right?
1000                 num_still_running += file->cf_has_running;
1001         }
1002         return num_still_running;
1003 }
1004
1005 static void reopen_logfile_to_stderr(void)
1006 {
1007         if (G.log_filename) {
1008                 int logfd = open_or_warn(G.log_filename, O_WRONLY | O_CREAT | O_APPEND);
1009                 if (logfd >= 0)
1010                         xmove_fd(logfd, STDERR_FILENO);
1011         }
1012 }
1013
1014 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1015 int crond_main(int argc UNUSED_PARAM, char **argv)
1016 {
1017         time_t t2;
1018         unsigned rescan;
1019         unsigned sleep_time;
1020         unsigned opts;
1021
1022         INIT_G();
1023
1024         /* "-b after -f is ignored", and so on for every pair a-b */
1025         opt_complementary = "f-b:b-f:S-L:L-S" IF_FEATURE_CROND_D(":d-l")
1026                         /* -l and -d have numeric param */
1027                         ":l+" IF_FEATURE_CROND_D(":d+");
1028         opts = getopt32(argv, "l:L:fbSc:" IF_FEATURE_CROND_D("d:"),
1029                         &G.log_level, &G.log_filename, &G.crontab_dir_name
1030                         IF_FEATURE_CROND_D(,&G.log_level));
1031         /* both -d N and -l N set the same variable: G.log_level */
1032
1033         if (!(opts & OPT_f)) {
1034                 /* close stdin, stdout, stderr.
1035                  * close unused descriptors - don't need them. */
1036                 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
1037         }
1038
1039         if (!(opts & OPT_d) && G.log_filename == NULL) {
1040                 /* logging to syslog */
1041                 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
1042                 logmode = LOGMODE_SYSLOG;
1043         }
1044
1045         //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
1046
1047         reopen_logfile_to_stderr();
1048         xchdir(G.crontab_dir_name);
1049         log8("crond (busybox "BB_VER") started, log level %d", G.log_level);
1050         rescan_crontab_dir();
1051         write_pidfile(CONFIG_PID_FILE_PATH "/crond.pid");
1052 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
1053         if (touch_reboot_file())
1054                 start_jobs(START_ME_REBOOT); /* start @reboot entries, if any */
1055 #endif
1056
1057         /* Main loop */
1058         t2 = time(NULL);
1059         rescan = 60;
1060         sleep_time = 60;
1061         for (;;) {
1062                 struct stat sbuf;
1063                 time_t t1;
1064                 long dt;
1065
1066                 /* Synchronize to 1 minute, minimum 1 second */
1067                 t1 = t2;
1068                 sleep(sleep_time - (time(NULL) % sleep_time));
1069                 t2 = time(NULL);
1070                 dt = (long)t2 - (long)t1;
1071
1072                 reopen_logfile_to_stderr();
1073
1074                 /*
1075                  * The file 'cron.update' is checked to determine new cron
1076                  * jobs.  The directory is rescanned once an hour to deal
1077                  * with any screwups.
1078                  *
1079                  * Check for time jump.  Disparities over an hour either way
1080                  * result in resynchronization.  A negative disparity
1081                  * less than an hour causes us to effectively sleep until we
1082                  * match the original time (i.e. no re-execution of jobs that
1083                  * have just been run).  A positive disparity less than
1084                  * an hour causes intermediate jobs to be run, but only once
1085                  * in the worst case.
1086                  *
1087                  * When running jobs, the inequality used is greater but not
1088                  * equal to t1, and less then or equal to t2.
1089                  */
1090                 if (stat(G.crontab_dir_name, &sbuf) != 0)
1091                         sbuf.st_mtime = 0; /* force update (once) if dir was deleted */
1092                 if (G.crontab_dir_mtime != sbuf.st_mtime) {
1093                         G.crontab_dir_mtime = sbuf.st_mtime;
1094                         rescan = 1;
1095                 }
1096                 if (--rescan == 0) {
1097                         rescan = 60;
1098                         rescan_crontab_dir();
1099                 }
1100                 process_cron_update_file();
1101                 log5("wakeup dt=%ld", dt);
1102                 if (dt < -60 * 60 || dt > 60 * 60) {
1103                         bb_error_msg("time disparity of %ld minutes detected", dt / 60);
1104                         /* and we do not run any jobs in this case */
1105                 } else if (dt > 0) {
1106                         /* Usual case: time advances forward, as expected */
1107                         flag_starting_jobs(t1, t2);
1108                         start_jobs(START_ME_NORMAL);
1109                         sleep_time = 60;
1110                         if (check_completions() > 0) {
1111                                 /* some jobs are still running */
1112                                 sleep_time = 10;
1113                         }
1114                 }
1115                 /* else: time jumped back, do not run any jobs */
1116         } /* for (;;) */
1117
1118         return 0; /* not reached */
1119 }