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