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