- use EXIT_{SUCCESS,FAILURE}. No object-code changes
[platform/upstream/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 #       if ENABLE_SENDMAIL
37 #               define SENDMAIL_ARGS   "localhost", line->cl_MailTo
38 #       else
39 #               define SENDMAIL_ARGS   "-ti", "oem"
40 #       endif
41 #endif
42 #ifndef CRONUPDATE
43 #define CRONUPDATE      "cron.update"
44 #endif
45 #ifndef MAXLINES
46 #define MAXLINES        256     /* max lines in non-root crontabs */
47 #endif
48
49
50 typedef struct CronFile {
51         struct CronFile *cf_Next;
52         struct CronLine *cf_LineBase;
53         char *cf_User;                  /* username                     */
54         smallint cf_Ready;              /* bool: one or more jobs ready */
55         smallint cf_Running;            /* bool: one or more jobs running */
56         smallint cf_Deleted;            /* marked for deletion, ignore  */
57 } CronFile;
58
59 typedef struct CronLine {
60         struct CronLine *cl_Next;
61         char *cl_Shell;         /* shell command                        */
62         pid_t cl_Pid;           /* running pid, 0, or armed (-1)        */
63 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
64         int cl_MailPos;         /* 'empty file' size                    */
65         smallint cl_MailFlag;   /* running pid is for mail              */
66         char *cl_MailTo;        /* whom to mail results                 */
67 #endif
68         /* ordered by size, not in natural order. makes code smaller: */
69         char cl_Dow[7];         /* 0-6, beginning sunday                */
70         char cl_Mons[12];       /* 0-11                                 */
71         char cl_Hrs[24];        /* 0-23                                 */
72         char cl_Days[32];       /* 1-31                                 */
73         char cl_Mins[60];       /* 0-59                                 */
74 } CronLine;
75
76
77 #define DaemonUid 0
78
79
80 enum {
81         OPT_l = (1 << 0),
82         OPT_L = (1 << 1),
83         OPT_f = (1 << 2),
84         OPT_b = (1 << 3),
85         OPT_S = (1 << 4),
86         OPT_c = (1 << 5),
87         OPT_d = (1 << 6) * ENABLE_DEBUG_CROND_OPTION,
88 };
89 #if ENABLE_DEBUG_CROND_OPTION
90 #define DebugOpt (option_mask32 & OPT_d)
91 #else
92 #define DebugOpt 0
93 #endif
94
95
96 struct globals {
97         unsigned LogLevel; /* = 8; */
98         const char *LogFile;
99         const char *CDir; /* = CRONTABS; */
100         CronFile *FileBase;
101 #if SETENV_LEAKS
102         char *env_var_user;
103         char *env_var_home;
104 #endif
105 };
106 #define G (*(struct globals*)&bb_common_bufsiz1)
107 #define LogLevel           (G.LogLevel               )
108 #define LogFile            (G.LogFile                )
109 #define CDir               (G.CDir                   )
110 #define FileBase           (G.FileBase               )
111 #define env_var_user       (G.env_var_user           )
112 #define env_var_home       (G.env_var_home           )
113 #define INIT_G() do { \
114         LogLevel = 8; \
115         CDir = CRONTABS; \
116 } while (0)
117
118
119 static void CheckUpdates(void);
120 static void SynchronizeDir(void);
121 static int TestJobs(time_t t1, time_t t2);
122 static void RunJobs(void);
123 static int CheckJobs(void);
124 static void RunJob(const char *user, CronLine *line);
125 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
126 static void EndJob(const char *user, CronLine *line);
127 #else
128 #define EndJob(user, line)  ((line)->cl_Pid = 0)
129 #endif
130 static void DeleteFile(const char *userName);
131
132
133 #define LVL5  "\x05"
134 #define LVL7  "\x07"
135 #define LVL8  "\x08"
136 #define LVL9  "\x09"
137 #define WARN9 "\x49"
138 #define DIE9  "\xc9"
139 /* level >= 20 is "error" */
140 #define ERR20 "\x14"
141
142 static void crondlog(const char *ctl, ...)
143 {
144         va_list va;
145         int level = (ctl[0] & 0x1f);
146
147         va_start(va, ctl);
148         if (level >= (int)LogLevel) {
149                 /* Debug mode: all to (non-redirected) stderr, */
150                 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
151                 if (!DebugOpt && LogFile) {
152                         /* Otherwise (log to file): we reopen log file at every write: */
153                         int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
154                         if (logfd >= 0)
155                                 xmove_fd(logfd, STDERR_FILENO);
156                 }
157 // TODO: ERR -> error, WARN -> warning, LVL -> info
158                 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
159         }
160         va_end(va);
161         if (ctl[0] & 0x80)
162                 exit(20);
163 }
164
165 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
166 int crond_main(int argc ATTRIBUTE_UNUSED, char **argv)
167 {
168         unsigned opt;
169
170         INIT_G();
171
172         /* "-b after -f is ignored", and so on for every pair a-b */
173         opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l")
174                         ":l+:d+"; /* -l and -d have numeric param */
175         opt = getopt32(argv, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
176                         &LogLevel, &LogFile, &CDir
177                         USE_DEBUG_CROND_OPTION(,&LogLevel));
178         /* both -d N and -l N set the same variable: LogLevel */
179
180         if (!(opt & OPT_f)) {
181                 /* close stdin, stdout, stderr.
182                  * close unused descriptors - don't need them. */
183                 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
184         }
185
186         if (!DebugOpt && LogFile == NULL) {
187                 /* logging to syslog */
188                 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
189                 logmode = LOGMODE_SYSLOG;
190         }
191
192         xchdir(CDir);
193         //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
194         setenv("SHELL", DEFAULT_SHELL, 1); /* once, for all future children */
195         crondlog(LVL9 "crond (busybox "BB_VER") started, log level %d", LogLevel);
196         SynchronizeDir();
197
198         /* main loop - synchronize to 1 second after the minute, minimum sleep
199          * of 1 second. */
200         {
201                 time_t t1 = time(NULL);
202                 time_t t2;
203                 long dt;
204                 int rescan = 60;
205                 int sleep_time = 60;
206
207                 write_pidfile("/var/run/crond.pid");
208                 for (;;) {
209                         sleep((sleep_time + 1) - (time(NULL) % sleep_time));
210
211                         t2 = time(NULL);
212                         dt = (long)t2 - (long)t1;
213
214                         /*
215                          * The file 'cron.update' is checked to determine new cron
216                          * jobs.  The directory is rescanned once an hour to deal
217                          * with any screwups.
218                          *
219                          * check for disparity.  Disparities over an hour either way
220                          * result in resynchronization.  A reverse-indexed disparity
221                          * less then an hour causes us to effectively sleep until we
222                          * match the original time (i.e. no re-execution of jobs that
223                          * have just been run).  A forward-indexed disparity less then
224                          * an hour causes intermediate jobs to be run, but only once
225                          * in the worst case.
226                          *
227                          * when running jobs, the inequality used is greater but not
228                          * equal to t1, and less then or equal to t2.
229                          */
230                         if (--rescan == 0) {
231                                 rescan = 60;
232                                 SynchronizeDir();
233                         }
234                         CheckUpdates();
235                         if (DebugOpt)
236                                 crondlog(LVL5 "wakeup dt=%ld", dt);
237                         if (dt < -60 * 60 || dt > 60 * 60) {
238                                 crondlog(WARN9 "time disparity of %d minutes detected", dt / 60);
239                         } else if (dt > 0) {
240                                 TestJobs(t1, t2);
241                                 RunJobs();
242                                 sleep(5);
243                                 if (CheckJobs() > 0) {
244                                         sleep_time = 10;
245                                 } else {
246                                         sleep_time = 60;
247                                 }
248                         }
249                         t1 = t2;
250                 }
251         }
252         return 0; /* not reached */
253 }
254
255 #if SETENV_LEAKS
256 /* We set environment *before* vfork (because we want to use vfork),
257  * so we cannot use setenv() - repeated calls to setenv() may leak memory!
258  * Using putenv(), and freeing memory after unsetenv() won't leak */
259 static void safe_setenv4(char **pvar_val, const char *var, const char *val /*, int len*/)
260 {
261         const int len = 4; /* both var names are 4 char long */
262         char *var_val = *pvar_val;
263
264         if (var_val) {
265                 var_val[len] = '\0'; /* nuke '=' */
266                 unsetenv(var_val);
267                 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_setenv4(&env_var_user, "USER", pas->pw_name);
278         safe_setenv4(&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, 5);*/
281 #else
282         setenv("USER", pas->pw_name, 1);
283         setenv("HOME", pas->pw_dir, 1);
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(LVL9 "can't chdir(%s)", pas->pw_dir);
295                 if (chdir(TMPDIR) < 0) {
296                         crondlog(DIE9 "can't 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 char *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         if (base == NULL) {
320                 return NULL;
321         }
322
323         while (!isspace(*ptr)) {
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                         if (n1 < 0) {
334                                 n1 = strtol(ptr, &ptr, 10) + off;
335                         } else {
336                                 n2 = strtol(ptr, &ptr, 10) + off;
337                         }
338                         skip = 1;
339                 } else if (names) {
340                         int i;
341
342                         for (i = 0; names[i]; i += 3) {
343                                 /* was using strncmp before... */
344                                 if (strncasecmp(ptr, &names[i], 3) == 0) {
345                                         ptr += 3;
346                                         if (n1 < 0) {
347                                                 n1 = i / 3;
348                                         } else {
349                                                 n2 = i / 3;
350                                         }
351                                         skip = 1;
352                                         break;
353                                 }
354                         }
355                 }
356
357                 /* handle optional range '-' */
358                 if (skip == 0) {
359                         crondlog(WARN9 "user %s: parse error at %s", user, base);
360                         return NULL;
361                 }
362                 if (*ptr == '-' && n2 < 0) {
363                         ++ptr;
364                         continue;
365                 }
366
367                 /*
368                  * collapse single-value ranges, handle skipmark, and fill
369                  * in the character array appropriately.
370                  */
371                 if (n2 < 0) {
372                         n2 = n1;
373                 }
374                 if (*ptr == '/') {
375                         skip = strtol(ptr + 1, &ptr, 10);
376                 }
377
378                 /*
379                  * fill array, using a failsafe is the easiest way to prevent
380                  * an endless loop
381                  */
382                 {
383                         int s0 = 1;
384                         int failsafe = 1024;
385
386                         --n1;
387                         do {
388                                 n1 = (n1 + 1) % modvalue;
389
390                                 if (--s0 == 0) {
391                                         ary[n1 % modvalue] = 1;
392                                         s0 = skip;
393                                 }
394                                 if (--failsafe == 0) {
395                                         crondlog(WARN9 "user %s: parse error at %s", user, base);
396                                         return NULL;
397                                 }
398                         } while (n1 != n2);
399
400                 }
401                 if (*ptr != ',') {
402                         break;
403                 }
404                 ++ptr;
405                 n1 = -1;
406                 n2 = -1;
407         }
408
409         if (!isspace(*ptr)) {
410                 crondlog(WARN9 "user %s: parse error at %s", user, base);
411                 return NULL;
412         }
413
414         if (DebugOpt && (LogLevel <= 5)) { /* like LVL5 */
415                 /* can't use crondlog, it inserts '\n' */
416                 int i;
417                 for (i = 0; i < modvalue; ++i)
418                         fprintf(stderr, "%d", (unsigned char)ary[i]);
419                 fputc('\n', stderr);
420         }
421         return skip_whitespace(ptr);
422 }
423
424 static void FixDayDow(CronLine *line)
425 {
426         unsigned i;
427         int weekUsed = 0;
428         int daysUsed = 0;
429
430         for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
431                 if (line->cl_Dow[i] == 0) {
432                         weekUsed = 1;
433                         break;
434                 }
435         }
436         for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
437                 if (line->cl_Days[i] == 0) {
438                         daysUsed = 1;
439                         break;
440                 }
441         }
442         if (weekUsed != daysUsed) {
443                 if (weekUsed)
444                         memset(line->cl_Days, 0, sizeof(line->cl_Days));
445                 else /* daysUsed */
446                         memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
447         }
448 }
449
450 static void SynchronizeFile(const char *fileName)
451 {
452         FILE *fi;
453         struct stat sbuf;
454         int maxEntries;
455         int maxLines;
456         char buf[1024];
457 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
458         char *mailTo = NULL;
459 #endif
460
461         if (!fileName)
462                 return;
463
464         DeleteFile(fileName);
465         fi = fopen(fileName, "r");
466         if (!fi)
467                 return;
468
469         maxEntries = MAXLINES;
470         if (strcmp(fileName, "root") == 0) {
471                 maxEntries = 65535;
472         }
473         maxLines = maxEntries * 10;
474
475         if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
476                 CronFile *file = xzalloc(sizeof(CronFile));
477                 CronLine **pline;
478
479                 file->cf_User = xstrdup(fileName);
480                 pline = &file->cf_LineBase;
481
482                 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
483                         CronLine *line;
484                         char *ptr;
485
486                         trim(buf);
487                         if (buf[0] == '\0' || buf[0] == '#') {
488                                 continue;
489                         }
490                         if (--maxEntries == 0) {
491                                 break;
492                         }
493                         if (DebugOpt) {
494                                 crondlog(LVL5 "user:%s entry:%s", fileName, buf);
495                         }
496                         /* check if line is setting MAILTO= */
497                         if (0 == strncmp("MAILTO=", buf, 7)) {
498 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
499                                 free(mailTo);
500                                 mailTo = (buf[7]) ? xstrdup(buf+7) : NULL;
501 #endif /* otherwise just ignore such lines */
502                                 continue;
503                         }
504                         *pline = line = xzalloc(sizeof(CronLine));
505                         /* parse date ranges */
506                         ptr = ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, buf);
507                         ptr = ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, ptr);
508                         ptr = ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, ptr);
509                         ptr = ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, ptr);
510                         ptr = ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, ptr);
511                         /* check failure */
512                         if (ptr == NULL) {
513                                 free(line);
514                                 continue;
515                         }
516                         /*
517                          * fix days and dow - if one is not "*" and the other
518                          * is "*", the other is set to 0, and vise-versa
519                          */
520                         FixDayDow(line);
521 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
522                         /* copy mailto (can be NULL) */
523                         line->cl_MailTo = xstrdup(mailTo);
524 #endif
525                         /* copy command */
526                         line->cl_Shell = xstrdup(ptr);
527                         if (DebugOpt) {
528                                 crondlog(LVL5 " command:%s", ptr);
529                         }
530                         pline = &line->cl_Next;
531                 }
532                 *pline = NULL;
533
534                 file->cf_Next = FileBase;
535                 FileBase = file;
536
537                 if (maxLines == 0 || maxEntries == 0) {
538                         crondlog(WARN9 "user %s: too many lines", fileName);
539                 }
540         }
541         fclose(fi);
542 }
543
544 static void CheckUpdates(void)
545 {
546         FILE *fi;
547         char buf[256];
548
549         fi = fopen(CRONUPDATE, "r");
550         if (fi != NULL) {
551                 unlink(CRONUPDATE);
552                 while (fgets(buf, sizeof(buf), fi) != NULL) {
553                         /* use first word only */
554                         SynchronizeFile(strtok(buf, " \t\r\n"));
555                 }
556                 fclose(fi);
557         }
558 }
559
560 static void SynchronizeDir(void)
561 {
562         CronFile *file;
563         /* Attempt to delete the database. */
564  again:
565         for (file = FileBase; file; file = file->cf_Next) {
566                 if (!file->cf_Deleted) {
567                         DeleteFile(file->cf_User);
568                         goto again;
569                 }
570         }
571
572         /*
573          * Remove cron update file
574          *
575          * Re-chdir, in case directory was renamed & deleted, or otherwise
576          * screwed up.
577          *
578          * scan directory and add associated users
579          */
580         unlink(CRONUPDATE);
581         if (chdir(CDir) < 0) {
582                 crondlog(DIE9 "can't chdir(%s)", CDir);
583         }
584         {
585                 DIR *dir = opendir(".");
586                 struct dirent *den;
587
588                 if (!dir)
589                         crondlog(DIE9 "can't chdir(%s)", "."); /* exits */
590                 while ((den = readdir(dir)) != NULL) {
591                         if (strchr(den->d_name, '.') != NULL) {
592                                 continue;
593                         }
594                         if (getpwnam(den->d_name)) {
595                                 SynchronizeFile(den->d_name);
596                         } else {
597                                 crondlog(LVL7 "ignoring %s", den->d_name);
598                         }
599                 }
600                 closedir(dir);
601         }
602 }
603
604 /*
605  *  DeleteFile() - delete user database
606  *
607  *  Note: multiple entries for same user may exist if we were unable to
608  *  completely delete a database due to running processes.
609  */
610 static void DeleteFile(const char *userName)
611 {
612         CronFile **pfile = &FileBase;
613         CronFile *file;
614
615         while ((file = *pfile) != NULL) {
616                 if (strcmp(userName, file->cf_User) == 0) {
617                         CronLine **pline = &file->cf_LineBase;
618                         CronLine *line;
619
620                         file->cf_Running = 0;
621                         file->cf_Deleted = 1;
622
623                         while ((line = *pline) != NULL) {
624                                 if (line->cl_Pid > 0) {
625                                         file->cf_Running = 1;
626                                         pline = &line->cl_Next;
627                                 } else {
628                                         *pline = line->cl_Next;
629                                         free(line->cl_Shell);
630                                         free(line);
631                                 }
632                         }
633                         if (file->cf_Running == 0) {
634                                 *pfile = file->cf_Next;
635                                 free(file->cf_User);
636                                 free(file);
637                         } else {
638                                 pfile = &file->cf_Next;
639                         }
640                 } else {
641                         pfile = &file->cf_Next;
642                 }
643         }
644 }
645
646 /*
647  * TestJobs()
648  *
649  * determine which jobs need to be run.  Under normal conditions, the
650  * period is about a minute (one scan).  Worst case it will be one
651  * hour (60 scans).
652  */
653 static int TestJobs(time_t t1, time_t t2)
654 {
655         int nJobs = 0;
656         time_t t;
657
658         /* Find jobs > t1 and <= t2 */
659
660         for (t = t1 - t1 % 60; t <= t2; t += 60) {
661                 struct tm *tp;
662                 CronFile *file;
663                 CronLine *line;
664
665                 if (t <= t1)
666                         continue;
667
668                 tp = localtime(&t);
669                 for (file = FileBase; file; file = file->cf_Next) {
670                         if (DebugOpt)
671                                 crondlog(LVL5 "file %s:", file->cf_User);
672                         if (file->cf_Deleted)
673                                 continue;
674                         for (line = file->cf_LineBase; line; line = line->cl_Next) {
675                                 if (DebugOpt)
676                                         crondlog(LVL5 " line %s", line->cl_Shell);
677                                 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour]
678                                  && (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
679                                  && line->cl_Mons[tp->tm_mon]
680                                 ) {
681                                         if (DebugOpt) {
682                                                 crondlog(LVL5 " job: %d %s",
683                                                         (int)line->cl_Pid, line->cl_Shell);
684                                         }
685                                         if (line->cl_Pid > 0) {
686                                                 crondlog(LVL8 "user %s: process already running: %s",
687                                                         file->cf_User, line->cl_Shell);
688                                         } else if (line->cl_Pid == 0) {
689                                                 line->cl_Pid = -1;
690                                                 file->cf_Ready = 1;
691                                                 ++nJobs;
692                                         }
693                                 }
694                         }
695                 }
696         }
697         return nJobs;
698 }
699
700 static void RunJobs(void)
701 {
702         CronFile *file;
703         CronLine *line;
704
705         for (file = FileBase; file; file = file->cf_Next) {
706                 if (!file->cf_Ready)
707                         continue;
708
709                 file->cf_Ready = 0;
710                 for (line = file->cf_LineBase; line; line = line->cl_Next) {
711                         if (line->cl_Pid >= 0)
712                                 continue;
713
714                         RunJob(file->cf_User, line);
715                         crondlog(LVL8 "USER %s pid %3d cmd %s",
716                                 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
717                         if (line->cl_Pid < 0) {
718                                 file->cf_Ready = 1;
719                         } else if (line->cl_Pid > 0) {
720                                 file->cf_Running = 1;
721                         }
722                 }
723         }
724 }
725
726 /*
727  * CheckJobs() - check for job completion
728  *
729  * Check for job completion, return number of jobs still running after
730  * all done.
731  */
732 static int CheckJobs(void)
733 {
734         CronFile *file;
735         CronLine *line;
736         int nStillRunning = 0;
737
738         for (file = FileBase; file; file = file->cf_Next) {
739                 if (file->cf_Running) {
740                         file->cf_Running = 0;
741
742                         for (line = file->cf_LineBase; line; line = line->cl_Next) {
743                                 int status, r;
744                                 if (line->cl_Pid <= 0)
745                                         continue;
746
747                                 r = waitpid(line->cl_Pid, &status, WNOHANG);
748                                 if (r < 0 || r == line->cl_Pid) {
749                                         EndJob(file->cf_User, line);
750                                         if (line->cl_Pid) {
751                                                 file->cf_Running = 1;
752                                         }
753                                 } else if (r == 0) {
754                                         file->cf_Running = 1;
755                                 }
756                         }
757                 }
758                 nStillRunning += file->cf_Running;
759         }
760         return nStillRunning;
761 }
762
763 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
764
765 // TODO: sendmail should be _run-time_ option, not compile-time!
766
767 static void
768 ForkJob(const char *user, CronLine *line, int mailFd,
769                 const char *prog, const char *cmd, const char *arg,
770                 const char *mail_filename)
771 {
772         struct passwd *pas;
773         pid_t pid;
774
775         /* prepare things before vfork */
776         pas = getpwnam(user);
777         if (!pas) {
778                 crondlog(LVL9 "can't get uid for %s", user);
779                 goto err;
780         }
781         SetEnv(pas);
782
783         pid = vfork();
784         if (pid == 0) {
785                 /* CHILD */
786                 /* change running state to the user in question */
787                 ChangeUser(pas);
788                 if (DebugOpt) {
789                         crondlog(LVL5 "child running %s", prog);
790                 }
791                 if (mailFd >= 0) {
792                         xmove_fd(mailFd, mail_filename ? 1 : 0);
793                         dup2(1, 2);
794                 }
795                 execl(prog, prog, cmd, arg, 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 if (mail_filename) {
813                 /* PARENT, FORK SUCCESS
814                  * rename mail-file based on pid of process
815                  */
816                 char mailFile2[128];
817
818                 snprintf(mailFile2, sizeof(mailFile2), "%s/cron.%s.%d", TMPDIR, user, pid);
819                 rename(mail_filename, mailFile2); // TODO: xrename?
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", user,
847                                 line->cl_Shell);
848                         line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
849                 } else {
850                         crondlog(ERR20 "cannot 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(LVL9 "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                 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
931                 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
932                                  DEFAULT_SHELL, "-c", line->cl_Shell);
933                 _exit(EXIT_SUCCESS);
934         }
935         if (pid < 0) {
936                 /* FORK FAILED */
937                 crondlog(ERR20 "can't vfork");
938  err:
939                 pid = 0;
940         }
941         line->cl_Pid = pid;
942 }
943
944 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */