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