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