c7ee793a56665672dee6e4804f1fd716cfee3fb5
[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_DEBUG_CROND_OPTION,
84 };
85 #if ENABLE_DEBUG_CROND_OPTION
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_DEBUG_CROND_OPTION(":d-l")
170                         ":l+:d+"; /* -l and -d have numeric param */
171         opt = getopt32(argv, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
172                         &LogLevel, &LogFile, &CDir
173                         USE_DEBUG_CROND_OPTION(,&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         setenv("SHELL", DEFAULT_SHELL, 1); /* 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_setenv4(char **pvar_val, const char *var, const char *val /*, int len*/)
256 {
257         const int len = 4; /* both var names are 4 char long */
258         char *var_val = *pvar_val;
259
260         if (var_val) {
261                 var_val[len] = '\0'; /* nuke '=' */
262                 unsetenv(var_val);
263                 free(var_val);
264         }
265         *pvar_val = xasprintf("%s=%s", var, val);
266         putenv(*pvar_val);
267 }
268 #endif
269
270 static void SetEnv(struct passwd *pas)
271 {
272 #if SETENV_LEAKS
273         safe_setenv4(&env_var_user, "USER", pas->pw_name);
274         safe_setenv4(&env_var_home, "HOME", pas->pw_dir);
275         /* if we want to set user's shell instead: */
276         /*safe_setenv(env_var_user, "SHELL", pas->pw_shell, 5);*/
277 #else
278         setenv("USER", pas->pw_name, 1);
279         setenv("HOME", pas->pw_dir, 1);
280 #endif
281         /* currently, we use constant one: */
282         /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
283 }
284
285 static void ChangeUser(struct passwd *pas)
286 {
287         /* careful: we're after vfork! */
288         change_identity(pas); /* - initgroups, setgid, setuid */
289         if (chdir(pas->pw_dir) < 0) {
290                 crondlog(LVL9 "can't chdir(%s)", pas->pw_dir);
291                 if (chdir(TMPDIR) < 0) {
292                         crondlog(DIE9 "can't chdir(%s)", TMPDIR); /* exits */
293                 }
294         }
295 }
296
297 static const char DowAry[] ALIGN1 =
298         "sun""mon""tue""wed""thu""fri""sat"
299         /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
300 ;
301
302 static const char MonAry[] ALIGN1 =
303         "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
304         /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
305 ;
306
307 static void ParseField(char *user, char *ary, int modvalue, int off,
308                                 const char *names, char *ptr)
309 /* 'names' is a pointer to a set of 3-char abbreviations */
310 {
311         char *base = ptr;
312         int n1 = -1;
313         int n2 = -1;
314
315         // this can't happen due to config_read()
316         /*if (base == NULL)
317                 return;*/
318
319         while (1) {
320                 int skip = 0;
321
322                 /* Handle numeric digit or symbol or '*' */
323                 if (*ptr == '*') {
324                         n1 = 0;         /* everything will be filled */
325                         n2 = modvalue - 1;
326                         skip = 1;
327                         ++ptr;
328                 } else if (isdigit(*ptr)) {
329                         if (n1 < 0) {
330                                 n1 = strtol(ptr, &ptr, 10) + off;
331                         } else {
332                                 n2 = strtol(ptr, &ptr, 10) + off;
333                         }
334                         skip = 1;
335                 } else if (names) {
336                         int i;
337
338                         for (i = 0; names[i]; i += 3) {
339                                 /* was using strncmp before... */
340                                 if (strncasecmp(ptr, &names[i], 3) == 0) {
341                                         ptr += 3;
342                                         if (n1 < 0) {
343                                                 n1 = i / 3;
344                                         } else {
345                                                 n2 = i / 3;
346                                         }
347                                         skip = 1;
348                                         break;
349                                 }
350                         }
351                 }
352
353                 /* handle optional range '-' */
354                 if (skip == 0) {
355                         goto err;
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                                         goto err;
391                                 }
392                         } while (n1 != n2);
393
394                 }
395                 if (*ptr != ',') {
396                         break;
397                 }
398                 ++ptr;
399                 n1 = -1;
400                 n2 = -1;
401         }
402
403         if (*ptr) {
404  err:
405                 crondlog(WARN9 "user %s: parse error at %s", user, base);
406                 return;
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 }
417
418 static void FixDayDow(CronLine *line)
419 {
420         unsigned i;
421         int weekUsed = 0;
422         int daysUsed = 0;
423
424         for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
425                 if (line->cl_Dow[i] == 0) {
426                         weekUsed = 1;
427                         break;
428                 }
429         }
430         for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
431                 if (line->cl_Days[i] == 0) {
432                         daysUsed = 1;
433                         break;
434                 }
435         }
436         if (weekUsed != daysUsed) {
437                 if (weekUsed)
438                         memset(line->cl_Days, 0, sizeof(line->cl_Days));
439                 else /* daysUsed */
440                         memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
441         }
442 }
443
444 static void SynchronizeFile(const char *fileName)
445 {
446         struct parser_t *parser;
447         struct stat sbuf;
448         int maxLines;
449         char *tokens[6];
450 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
451         char *mailTo = NULL;
452 #endif
453
454         if (!fileName)
455                 return;
456
457         DeleteFile(fileName);
458         parser = config_open(fileName);
459         if (!parser)
460                 return;
461
462         maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
463
464         if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
465                 CronFile *file = xzalloc(sizeof(CronFile));
466                 CronLine **pline;
467                 int n;
468
469                 file->cf_User = xstrdup(fileName);
470                 pline = &file->cf_LineBase;
471
472                 while (--maxLines
473                  && (n = config_read(parser, tokens, 6, 1, "# \t", PARSE_LAST_IS_GREEDY|PARSE_KEEP_COPY))
474                 ) {
475                         CronLine *line;
476
477                         if (DebugOpt)
478                                 crondlog(LVL5 "user:%s entry:%s", fileName, parser->data);
479
480                         /* check if line is setting MAILTO= */
481                         if (0 == strncmp(tokens[0], "MAILTO=", 7)) {
482 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
483                                 free(mailTo);
484                                 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
485 #endif /* otherwise just ignore such lines */
486                                 continue;
487                         }
488                         /* check if a minimum of tokens is specified */
489                         if (n < 6)
490                                 continue;
491                         *pline = line = xzalloc(sizeof(CronLine));
492                         /* parse date ranges */
493                         ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, tokens[0]);
494                         ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, tokens[1]);
495                         ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, tokens[2]);
496                         ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, tokens[3]);
497                         ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, tokens[4]);
498                         /*
499                          * fix days and dow - if one is not "*" and the other
500                          * is "*", the other is set to 0, and vise-versa
501                          */
502                         FixDayDow(line);
503 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
504                         /* copy mailto (can be NULL) */
505                         line->cl_MailTo = xstrdup(mailTo);
506 #endif
507                         /* copy command */
508                         line->cl_Shell = xstrdup(tokens[5]);
509                         if (DebugOpt) {
510                                 crondlog(LVL5 " command:%s", tokens[5]);
511                         }
512                         pline = &line->cl_Next;
513 //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]);
514                 }
515                 *pline = NULL;
516
517                 file->cf_Next = FileBase;
518                 FileBase = file;
519
520                 if (maxLines == 0) {
521                         crondlog(WARN9 "user %s: too many lines", fileName);
522                 }
523         }
524         config_close(parser);
525 }
526
527 static void CheckUpdates(void)
528 {
529         FILE *fi;
530         char buf[256];
531
532         fi = fopen(CRONUPDATE, "r");
533         if (fi != NULL) {
534                 unlink(CRONUPDATE);
535                 while (fgets(buf, sizeof(buf), fi) != NULL) {
536                         /* use first word only */
537                         SynchronizeFile(strtok(buf, " \t\r\n"));
538                 }
539                 fclose(fi);
540         }
541 }
542
543 static void SynchronizeDir(void)
544 {
545         CronFile *file;
546         /* Attempt to delete the database. */
547  again:
548         for (file = FileBase; file; file = file->cf_Next) {
549                 if (!file->cf_Deleted) {
550                         DeleteFile(file->cf_User);
551                         goto again;
552                 }
553         }
554
555         /*
556          * Remove cron update file
557          *
558          * Re-chdir, in case directory was renamed & deleted, or otherwise
559          * screwed up.
560          *
561          * scan directory and add associated users
562          */
563         unlink(CRONUPDATE);
564         if (chdir(CDir) < 0) {
565                 crondlog(DIE9 "can't chdir(%s)", CDir);
566         }
567         {
568                 DIR *dir = opendir(".");
569                 struct dirent *den;
570
571                 if (!dir)
572                         crondlog(DIE9 "can't chdir(%s)", "."); /* exits */
573                 while ((den = readdir(dir)) != NULL) {
574                         if (strchr(den->d_name, '.') != NULL) {
575                                 continue;
576                         }
577                         if (getpwnam(den->d_name)) {
578                                 SynchronizeFile(den->d_name);
579                         } else {
580                                 crondlog(LVL7 "ignoring %s", den->d_name);
581                         }
582                 }
583                 closedir(dir);
584         }
585 }
586
587 /*
588  *  DeleteFile() - delete user database
589  *
590  *  Note: multiple entries for same user may exist if we were unable to
591  *  completely delete a database due to running processes.
592  */
593 static void DeleteFile(const char *userName)
594 {
595         CronFile **pfile = &FileBase;
596         CronFile *file;
597
598         while ((file = *pfile) != NULL) {
599                 if (strcmp(userName, file->cf_User) == 0) {
600                         CronLine **pline = &file->cf_LineBase;
601                         CronLine *line;
602
603                         file->cf_Running = 0;
604                         file->cf_Deleted = 1;
605
606                         while ((line = *pline) != NULL) {
607                                 if (line->cl_Pid > 0) {
608                                         file->cf_Running = 1;
609                                         pline = &line->cl_Next;
610                                 } else {
611                                         *pline = line->cl_Next;
612                                         free(line->cl_Shell);
613                                         free(line);
614                                 }
615                         }
616                         if (file->cf_Running == 0) {
617                                 *pfile = file->cf_Next;
618                                 free(file->cf_User);
619                                 free(file);
620                         } else {
621                                 pfile = &file->cf_Next;
622                         }
623                 } else {
624                         pfile = &file->cf_Next;
625                 }
626         }
627 }
628
629 /*
630  * TestJobs()
631  *
632  * determine which jobs need to be run.  Under normal conditions, the
633  * period is about a minute (one scan).  Worst case it will be one
634  * hour (60 scans).
635  */
636 static int TestJobs(time_t t1, time_t t2)
637 {
638         int nJobs = 0;
639         time_t t;
640
641         /* Find jobs > t1 and <= t2 */
642
643         for (t = t1 - t1 % 60; t <= t2; t += 60) {
644                 struct tm *tp;
645                 CronFile *file;
646                 CronLine *line;
647
648                 if (t <= t1)
649                         continue;
650
651                 tp = localtime(&t);
652                 for (file = FileBase; file; file = file->cf_Next) {
653                         if (DebugOpt)
654                                 crondlog(LVL5 "file %s:", file->cf_User);
655                         if (file->cf_Deleted)
656                                 continue;
657                         for (line = file->cf_LineBase; line; line = line->cl_Next) {
658                                 if (DebugOpt)
659                                         crondlog(LVL5 " line %s", line->cl_Shell);
660                                 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour]
661                                  && (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
662                                  && line->cl_Mons[tp->tm_mon]
663                                 ) {
664                                         if (DebugOpt) {
665                                                 crondlog(LVL5 " job: %d %s",
666                                                         (int)line->cl_Pid, line->cl_Shell);
667                                         }
668                                         if (line->cl_Pid > 0) {
669                                                 crondlog(LVL8 "user %s: process already running: %s",
670                                                         file->cf_User, line->cl_Shell);
671                                         } else if (line->cl_Pid == 0) {
672                                                 line->cl_Pid = -1;
673                                                 file->cf_Ready = 1;
674                                                 ++nJobs;
675                                         }
676                                 }
677                         }
678                 }
679         }
680         return nJobs;
681 }
682
683 static void RunJobs(void)
684 {
685         CronFile *file;
686         CronLine *line;
687
688         for (file = FileBase; file; file = file->cf_Next) {
689                 if (!file->cf_Ready)
690                         continue;
691
692                 file->cf_Ready = 0;
693                 for (line = file->cf_LineBase; line; line = line->cl_Next) {
694                         if (line->cl_Pid >= 0)
695                                 continue;
696
697                         RunJob(file->cf_User, line);
698                         crondlog(LVL8 "USER %s pid %3d cmd %s",
699                                 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
700                         if (line->cl_Pid < 0) {
701                                 file->cf_Ready = 1;
702                         } else if (line->cl_Pid > 0) {
703                                 file->cf_Running = 1;
704                         }
705                 }
706         }
707 }
708
709 /*
710  * CheckJobs() - check for job completion
711  *
712  * Check for job completion, return number of jobs still running after
713  * all done.
714  */
715 static int CheckJobs(void)
716 {
717         CronFile *file;
718         CronLine *line;
719         int nStillRunning = 0;
720
721         for (file = FileBase; file; file = file->cf_Next) {
722                 if (file->cf_Running) {
723                         file->cf_Running = 0;
724
725                         for (line = file->cf_LineBase; line; line = line->cl_Next) {
726                                 int status, r;
727                                 if (line->cl_Pid <= 0)
728                                         continue;
729
730                                 r = waitpid(line->cl_Pid, &status, WNOHANG);
731                                 if (r < 0 || r == line->cl_Pid) {
732                                         EndJob(file->cf_User, line);
733                                         if (line->cl_Pid) {
734                                                 file->cf_Running = 1;
735                                         }
736                                 } else if (r == 0) {
737                                         file->cf_Running = 1;
738                                 }
739                         }
740                 }
741                 nStillRunning += file->cf_Running;
742         }
743         return nStillRunning;
744 }
745
746 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
747
748 // TODO: sendmail should be _run-time_ option, not compile-time!
749
750 static void
751 ForkJob(const char *user, CronLine *line, int mailFd,
752                 const char *prog, const char *cmd, const char *arg,
753                 const char *mail_filename)
754 {
755         struct passwd *pas;
756         pid_t pid;
757
758         /* prepare things before vfork */
759         pas = getpwnam(user);
760         if (!pas) {
761                 crondlog(LVL9 "can't get uid for %s", user);
762                 goto err;
763         }
764         SetEnv(pas);
765
766         pid = vfork();
767         if (pid == 0) {
768                 /* CHILD */
769                 /* change running state to the user in question */
770                 ChangeUser(pas);
771                 if (DebugOpt) {
772                         crondlog(LVL5 "child running %s", prog);
773                 }
774                 if (mailFd >= 0) {
775                         xmove_fd(mailFd, mail_filename ? 1 : 0);
776                         dup2(1, 2);
777                 }
778                 execlp(prog, prog, cmd, arg, NULL);
779                 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user, prog, cmd, arg);
780                 if (mail_filename) {
781                         fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
782                 }
783                 _exit(EXIT_SUCCESS);
784         }
785
786         line->cl_Pid = pid;
787         if (pid < 0) {
788                 /* FORK FAILED */
789                 crondlog(ERR20 "can't vfork");
790  err:
791                 line->cl_Pid = 0;
792                 if (mail_filename) {
793                         unlink(mail_filename);
794                 }
795         } else if (mail_filename) {
796                 /* PARENT, FORK SUCCESS
797                  * rename mail-file based on pid of process
798                  */
799                 char mailFile2[128];
800
801                 snprintf(mailFile2, sizeof(mailFile2), "%s/cron.%s.%d", TMPDIR, user, pid);
802                 rename(mail_filename, mailFile2); // TODO: xrename?
803         }
804
805         /*
806          * Close the mail file descriptor.. we can't just leave it open in
807          * a structure, closing it later, because we might run out of descriptors
808          */
809         if (mailFd >= 0) {
810                 close(mailFd);
811         }
812 }
813
814 static void RunJob(const char *user, CronLine *line)
815 {
816         char mailFile[128];
817         int mailFd = -1;
818
819         line->cl_Pid = 0;
820         line->cl_MailFlag = 0;
821
822         if (line->cl_MailTo) {
823                 /* open mail file - owner root so nobody can screw with it. */
824                 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
825                 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
826
827                 if (mailFd >= 0) {
828                         line->cl_MailFlag = 1;
829                         fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_MailTo,
830                                 line->cl_Shell);
831                         line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
832                 } else {
833                         crondlog(ERR20 "cannot create mail file %s for user %s, "
834                                         "discarding output", mailFile, user);
835                 }
836         }
837
838         ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
839 }
840
841 /*
842  * EndJob - called when job terminates and when mail terminates
843  */
844 static void EndJob(const char *user, CronLine *line)
845 {
846         int mailFd;
847         char mailFile[128];
848         struct stat sbuf;
849
850         /* No job */
851         if (line->cl_Pid <= 0) {
852                 line->cl_Pid = 0;
853                 return;
854         }
855
856         /*
857          * End of job and no mail file
858          * End of sendmail job
859          */
860         snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, line->cl_Pid);
861         line->cl_Pid = 0;
862
863         if (line->cl_MailFlag == 0) {
864                 return;
865         }
866         line->cl_MailFlag = 0;
867
868         /*
869          * End of primary job - check for mail file.  If size has increased and
870          * the file is still valid, we sendmail it.
871          */
872         mailFd = open(mailFile, O_RDONLY);
873         unlink(mailFile);
874         if (mailFd < 0) {
875                 return;
876         }
877
878         if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
879          || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
880          || !S_ISREG(sbuf.st_mode)
881         ) {
882                 close(mailFd);
883                 return;
884         }
885         if (line->cl_MailTo)
886                 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
887 }
888
889 #else /* crond without sendmail */
890
891 static void RunJob(const char *user, CronLine *line)
892 {
893         struct passwd *pas;
894         pid_t pid;
895
896         /* prepare things before vfork */
897         pas = getpwnam(user);
898         if (!pas) {
899                 crondlog(LVL9 "can't get uid for %s", user);
900                 goto err;
901         }
902         SetEnv(pas);
903
904         /* fork as the user in question and run program */
905         pid = vfork();
906         if (pid == 0) {
907                 /* CHILD */
908                 /* change running state to the user in question */
909                 ChangeUser(pas);
910                 if (DebugOpt) {
911                         crondlog(LVL5 "child running %s", DEFAULT_SHELL);
912                 }
913                 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
914                 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
915                                  DEFAULT_SHELL, "-c", line->cl_Shell);
916                 _exit(EXIT_SUCCESS);
917         }
918         if (pid < 0) {
919                 /* FORK FAILED */
920                 crondlog(ERR20 "can't vfork");
921  err:
922                 pid = 0;
923         }
924         line->cl_Pid = pid;
925 }
926
927 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */