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