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