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