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