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