1 /* vi: set sw=4 ts=4: */
3 * crond -d[#] -c <crondir> -f -b
5 * run as root, but NOT setuid root
7 * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com)
9 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
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
22 # define SETENV_LEAKS 1
26 #define TMPDIR CONFIG_FEATURE_CROND_DIR
27 #define CRONTABS CONFIG_FEATURE_CROND_DIR "/crontabs"
29 # define SENDMAIL "sendmail"
32 # define SENDMAIL_ARGS "-ti"
35 # define CRONUPDATE "cron.update"
38 # define MAXLINES 256 /* max lines in non-root crontabs */
42 typedef struct CronFile {
43 struct CronFile *cf_next;
44 struct CronLine *cf_lines;
46 smallint cf_wants_starting; /* bool: one or more jobs ready */
47 smallint cf_has_running; /* bool: one or more jobs running */
48 smallint cf_deleted; /* marked for deletion (but still has running jobs) */
51 typedef struct CronLine {
52 struct CronLine *cl_next;
53 char *cl_cmd; /* shell command */
54 pid_t cl_pid; /* >0:running, <0:needs to be started in this minute, 0:dormant */
55 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
56 int cl_empty_mail_size; /* size of mail header only, 0 if no mailfile */
57 char *cl_mailto; /* whom to mail results, may be NULL */
59 /* ordered by size, not in natural order. makes code smaller: */
60 char cl_Dow[7]; /* 0-6, beginning sunday */
61 char cl_Mons[12]; /* 0-11 */
62 char cl_Hrs[24]; /* 0-23 */
63 char cl_Days[32]; /* 1-31 */
64 char cl_Mins[60]; /* 0-59 */
78 OPT_d = (1 << 6) * ENABLE_FEATURE_CROND_D,
80 #if ENABLE_FEATURE_CROND_D
81 # define DebugOpt (option_mask32 & OPT_d)
88 unsigned log_level; /* = 8; */
89 time_t crontab_dir_mtime;
90 const char *log_filename;
91 const char *crontab_dir_name; /* = CRONTABS; */
98 #define G (*(struct globals*)&bb_common_bufsiz1)
99 #define INIT_G() do { \
101 G.crontab_dir_name = CRONTABS; \
105 /* 0 is the most verbose, default 8 */
111 /* level >= 20 is "error" */
114 static void crondlog(const char *ctl, ...) __attribute__ ((format (printf, 1, 2)));
115 static void crondlog(const char *ctl, ...)
118 int level = (ctl[0] & 0x1f);
121 if (level >= (int)G.log_level) {
122 /* Debug mode: all to (non-redirected) stderr, */
123 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
124 if (!DebugOpt && G.log_filename) {
125 /* Otherwise (log to file): we reopen log file at every write: */
126 int logfd = open3_or_warn(G.log_filename, O_WRONLY | O_CREAT | O_APPEND, 0666);
128 xmove_fd(logfd, STDERR_FILENO);
130 /* When we log to syslog, level > 8 is logged at LOG_ERR
131 * syslog level, level <= 8 is logged at LOG_INFO. */
133 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
136 vasprintf(&msg, ctl + 1, va);
137 bb_info_msg("%s: %s", applet_name, msg);
146 static const char DowAry[] ALIGN1 =
147 "sun""mon""tue""wed""thu""fri""sat"
148 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
151 static const char MonAry[] ALIGN1 =
152 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
153 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
156 static void ParseField(char *user, char *ary, int modvalue, int off,
157 const char *names, char *ptr)
158 /* 'names' is a pointer to a set of 3-char abbreviations */
164 // this can't happen due to config_read()
171 /* Handle numeric digit or symbol or '*' */
173 n1 = 0; /* everything will be filled */
177 } else if (isdigit(*ptr)) {
180 n1 = strtol(ptr, &endp, 10) + off;
182 n2 = strtol(ptr, &endp, 10) + off;
184 ptr = endp; /* gcc likes temp var for &endp */
189 for (i = 0; names[i]; i += 3) {
190 /* was using strncmp before... */
191 if (strncasecmp(ptr, &names[i], 3) == 0) {
204 /* handle optional range '-' */
208 if (*ptr == '-' && n2 < 0) {
214 * collapse single-value ranges, handle skipmark, and fill
215 * in the character array appropriately.
222 skip = strtol(ptr + 1, &endp, 10);
223 ptr = endp; /* gcc likes temp var for &endp */
227 * fill array, using a failsafe is the easiest way to prevent
236 n1 = (n1 + 1) % modvalue;
239 ary[n1 % modvalue] = 1;
242 if (--failsafe == 0) {
257 crondlog(WARN9 "user %s: parse error at %s", user, base);
261 if (DebugOpt && (G.log_level <= 5)) { /* like LVL5 */
262 /* can't use crondlog, it inserts '\n' */
264 for (i = 0; i < modvalue; ++i)
265 fprintf(stderr, "%d", (unsigned char)ary[i]);
266 bb_putchar_stderr('\n');
270 static void FixDayDow(CronLine *line)
276 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
277 if (line->cl_Dow[i] == 0) {
282 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
283 if (line->cl_Days[i] == 0) {
288 if (weekUsed != daysUsed) {
290 memset(line->cl_Days, 0, sizeof(line->cl_Days));
292 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
297 * delete_cronfile() - delete user database
299 * Note: multiple entries for same user may exist if we were unable to
300 * completely delete a database due to running processes.
302 //FIXME: we will start a new job even if the old job is running
303 //if crontab was reloaded: crond thinks that "new" job is different from "old"
304 //even if they are in fact completely the same. Example
307 // 0-59 * * * * long_running_job2
308 //User edits crontab to:
309 // 0-59 * * * * job1_updated
310 // 0-59 * * * * long_running_job2
311 //Bug: crond can now start another long_running_job2 even if old one
313 //OTOH most other versions of cron do not wait for job termination anyway,
314 //they end up with multiple copies of jobs if they don't terminate soon enough.
315 static void delete_cronfile(const char *userName)
317 CronFile **pfile = &G.cron_files;
320 while ((file = *pfile) != NULL) {
321 if (strcmp(userName, file->cf_username) == 0) {
322 CronLine **pline = &file->cf_lines;
325 file->cf_has_running = 0;
326 file->cf_deleted = 1;
328 while ((line = *pline) != NULL) {
329 if (line->cl_pid > 0) {
330 file->cf_has_running = 1;
331 pline = &line->cl_next;
333 *pline = line->cl_next;
338 if (file->cf_has_running == 0) {
339 *pfile = file->cf_next;
340 free(file->cf_username);
345 pfile = &file->cf_next;
349 static void load_crontab(const char *fileName)
351 struct parser_t *parser;
355 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
359 delete_cronfile(fileName);
361 if (!getpwnam(fileName)) {
362 crondlog(LVL7 "ignoring file '%s' (no such user)", fileName);
366 parser = config_open(fileName);
370 maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
372 if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DAEMON_UID) {
373 CronFile *file = xzalloc(sizeof(CronFile));
377 file->cf_username = xstrdup(fileName);
378 pline = &file->cf_lines;
385 n = config_read(parser, tokens, 6, 1, "# \t", PARSE_NORMAL | PARSE_KEEP_COPY);
390 crondlog(LVL5 "user:%s entry:%s", fileName, parser->data);
392 /* check if line is setting MAILTO= */
393 if (0 == strncmp(tokens[0], "MAILTO=", 7)) {
394 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
396 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
397 #endif /* otherwise just ignore such lines */
400 /* check if a minimum of tokens is specified */
403 *pline = line = xzalloc(sizeof(*line));
404 /* parse date ranges */
405 ParseField(file->cf_username, line->cl_Mins, 60, 0, NULL, tokens[0]);
406 ParseField(file->cf_username, line->cl_Hrs, 24, 0, NULL, tokens[1]);
407 ParseField(file->cf_username, line->cl_Days, 32, 0, NULL, tokens[2]);
408 ParseField(file->cf_username, line->cl_Mons, 12, -1, MonAry, tokens[3]);
409 ParseField(file->cf_username, line->cl_Dow, 7, 0, DowAry, tokens[4]);
411 * fix days and dow - if one is not "*" and the other
412 * is "*", the other is set to 0, and vise-versa
415 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
416 /* copy mailto (can be NULL) */
417 line->cl_mailto = xstrdup(mailTo);
420 line->cl_cmd = xstrdup(tokens[5]);
422 crondlog(LVL5 " command:%s", tokens[5]);
424 pline = &line->cl_next;
425 //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]);
429 file->cf_next = G.cron_files;
433 crondlog(WARN9 "user %s: too many lines", fileName);
436 config_close(parser);
439 static void process_cron_update_file(void)
444 fi = fopen_for_read(CRONUPDATE);
447 while (fgets(buf, sizeof(buf), fi) != NULL) {
448 /* use first word only */
449 skip_non_whitespace(buf)[0] = '\0';
456 static void rescan_crontab_dir(void)
460 /* Delete all files until we only have ones with running jobs (or none) */
462 for (file = G.cron_files; file; file = file->cf_next) {
463 if (!file->cf_deleted) {
464 delete_cronfile(file->cf_username);
469 /* Remove cron update file */
471 /* Re-chdir, in case directory was renamed & deleted */
472 if (chdir(G.crontab_dir_name) < 0) {
473 crondlog(DIE9 "chdir(%s)", G.crontab_dir_name);
476 /* Scan directory and add associated users */
478 DIR *dir = opendir(".");
482 crondlog(DIE9 "chdir(%s)", "."); /* exits */
483 while ((den = readdir(dir)) != NULL) {
484 if (strchr(den->d_name, '.') != NULL) {
487 load_crontab(den->d_name);
494 /* We set environment *before* vfork (because we want to use vfork),
495 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
496 * Using putenv(), and freeing memory after unsetenv() won't leak */
497 static void safe_setenv(char **pvar_val, const char *var, const char *val)
499 char *var_val = *pvar_val;
502 bb_unsetenv_and_free(var_val);
504 *pvar_val = xasprintf("%s=%s", var, val);
509 static void set_env_vars(struct passwd *pas)
512 safe_setenv(&G.env_var_user, "USER", pas->pw_name);
513 safe_setenv(&G.env_var_home, "HOME", pas->pw_dir);
514 /* if we want to set user's shell instead: */
515 /*safe_setenv(G.env_var_shell, "SHELL", pas->pw_shell);*/
517 xsetenv("USER", pas->pw_name);
518 xsetenv("HOME", pas->pw_dir);
520 /* currently, we use constant one: */
521 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
524 static void change_user(struct passwd *pas)
526 /* careful: we're after vfork! */
527 change_identity(pas); /* - initgroups, setgid, setuid */
528 if (chdir(pas->pw_dir) < 0) {
529 crondlog(WARN9 "chdir(%s)", pas->pw_dir);
530 if (chdir(TMPDIR) < 0) {
531 crondlog(DIE9 "chdir(%s)", TMPDIR); /* exits */
536 // TODO: sendmail should be _run-time_ option, not compile-time!
537 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
540 fork_job(const char *user, int mailFd,
542 const char *shell_cmd /* if NULL, we run sendmail */
547 /* prepare things before vfork */
548 pas = getpwnam(user);
550 crondlog(WARN9 "can't get uid for %s", user);
558 /* initgroups, setgid, setuid, and chdir to home or TMPDIR */
561 crondlog(LVL5 "child running %s", prog);
564 xmove_fd(mailFd, shell_cmd ? 1 : 0);
567 /* crond 3.0pl1-100 puts tasks in separate process groups */
569 execlp(prog, prog, (shell_cmd ? "-c" : SENDMAIL_ARGS), shell_cmd, (char *) NULL);
570 crondlog(ERR20 "can't execute '%s' for user %s", prog, user);
572 fdprintf(1, "Exec failed: %s -c %s\n", prog, shell_cmd);
579 crondlog(ERR20 "can't vfork");
582 } /* else: PARENT, FORK SUCCESS */
585 * Close the mail file descriptor.. we can't just leave it open in
586 * a structure, closing it later, because we might run out of descriptors
594 static void start_one_job(const char *user, CronLine *line)
600 line->cl_empty_mail_size = 0;
602 if (line->cl_mailto) {
603 /* Open mail file (owner is root so nobody can screw with it) */
604 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
605 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
608 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_mailto,
610 line->cl_empty_mail_size = lseek(mailFd, 0, SEEK_CUR);
612 crondlog(ERR20 "can't create mail file %s for user %s, "
613 "discarding output", mailFile, user);
617 line->cl_pid = fork_job(user, mailFd, DEFAULT_SHELL, line->cl_cmd);
619 if (line->cl_pid <= 0) {
622 /* rename mail-file based on pid of process */
623 char *mailFile2 = xasprintf("%s/cron.%s.%d", TMPDIR, user, (int)line->cl_pid);
624 rename(mailFile, mailFile2); // TODO: xrename?
631 * process_finished_job - called when job terminates and when mail terminates
633 static void process_finished_job(const char *user, CronLine *line)
646 if (line->cl_empty_mail_size <= 0) {
647 /* End of job and no mail file, or end of sendmail job */
652 * End of primary job - check for mail file.
653 * If size has changed and the file is still valid, we send it.
655 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, (int)pid);
656 mailFd = open(mailFile, O_RDONLY);
662 if (fstat(mailFd, &sbuf) < 0
663 || sbuf.st_uid != DAEMON_UID
664 || sbuf.st_nlink != 0
665 || sbuf.st_size == line->cl_empty_mail_size
666 || !S_ISREG(sbuf.st_mode)
671 line->cl_empty_mail_size = 0;
672 /* if (line->cl_mailto) - always true if cl_empty_mail_size was nonzero */
673 line->cl_pid = fork_job(user, mailFd, SENDMAIL, NULL);
676 #else /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
678 static void start_one_job(const char *user, CronLine *line)
683 pas = getpwnam(user);
685 crondlog(WARN9 "can't get uid for %s", user);
689 /* Prepare things before vfork */
692 /* Fork as the user in question and run program */
696 /* initgroups, setgid, setuid, and chdir to home or TMPDIR */
699 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
701 /* crond 3.0pl1-100 puts tasks in separate process groups */
703 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_cmd, (char *) NULL);
704 crondlog(ERR20 "can't execute '%s' for user %s", DEFAULT_SHELL, user);
709 crondlog(ERR20 "can't vfork");
716 #define process_finished_job(user, line) ((line)->cl_pid = 0)
718 #endif /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
721 * Determine which jobs need to be run. Under normal conditions, the
722 * period is about a minute (one scan). Worst case it will be one
725 static void flag_starting_jobs(time_t t1, time_t t2)
729 /* Find jobs > t1 and <= t2 */
731 for (t = t1 - t1 % 60; t <= t2; t += 60) {
740 for (file = G.cron_files; file; file = file->cf_next) {
742 crondlog(LVL5 "file %s:", file->cf_username);
743 if (file->cf_deleted)
745 for (line = file->cf_lines; line; line = line->cl_next) {
747 crondlog(LVL5 " line %s", line->cl_cmd);
748 if (line->cl_Mins[ptm->tm_min]
749 && line->cl_Hrs[ptm->tm_hour]
750 && (line->cl_Days[ptm->tm_mday] || line->cl_Dow[ptm->tm_wday])
751 && line->cl_Mons[ptm->tm_mon]
754 crondlog(LVL5 " job: %d %s",
755 (int)line->cl_pid, line->cl_cmd);
757 if (line->cl_pid > 0) {
758 crondlog(LVL8 "user %s: process already running: %s",
759 file->cf_username, line->cl_cmd);
760 } else if (line->cl_pid == 0) {
762 file->cf_wants_starting = 1;
770 static void start_jobs(void)
775 for (file = G.cron_files; file; file = file->cf_next) {
776 if (!file->cf_wants_starting)
779 file->cf_wants_starting = 0;
780 for (line = file->cf_lines; line; line = line->cl_next) {
782 if (line->cl_pid >= 0)
785 start_one_job(file->cf_username, line);
787 crondlog(LVL8 "USER %s pid %3d cmd %s",
788 file->cf_username, (int)pid, line->cl_cmd);
790 file->cf_wants_starting = 1;
793 file->cf_has_running = 1;
800 * Check for job completion, return number of jobs still running after
803 static int check_completions(void)
807 int num_still_running = 0;
809 for (file = G.cron_files; file; file = file->cf_next) {
810 if (!file->cf_has_running)
813 file->cf_has_running = 0;
814 for (line = file->cf_lines; line; line = line->cl_next) {
817 if (line->cl_pid <= 0)
820 r = waitpid(line->cl_pid, NULL, WNOHANG);
821 if (r < 0 || r == line->cl_pid) {
822 process_finished_job(file->cf_username, line);
823 if (line->cl_pid == 0) {
824 /* sendmail was not started for it */
827 /* else: sendmail was started, job is still running, fall thru */
829 /* else: r == 0: "process is still running" */
830 file->cf_has_running = 1;
832 //FIXME: if !file->cf_has_running && file->deleted: delete it!
833 //otherwise deleted entries will stay forever, right?
834 num_still_running += file->cf_has_running;
836 return num_still_running;
839 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
840 int crond_main(int argc UNUSED_PARAM, char **argv)
849 /* "-b after -f is ignored", and so on for every pair a-b */
850 opt_complementary = "f-b:b-f:S-L:L-S" IF_FEATURE_CROND_D(":d-l")
851 ":l+:d+"; /* -l and -d have numeric param */
852 opts = getopt32(argv, "l:L:fbSc:" IF_FEATURE_CROND_D("d:"),
853 &G.log_level, &G.log_filename, &G.crontab_dir_name
854 IF_FEATURE_CROND_D(,&G.log_level));
855 /* both -d N and -l N set the same variable: G.log_level */
857 if (!(opts & OPT_f)) {
858 /* close stdin, stdout, stderr.
859 * close unused descriptors - don't need them. */
860 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
863 if (!(opts & OPT_d) && G.log_filename == NULL) {
864 /* logging to syslog */
865 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
866 logmode = LOGMODE_SYSLOG;
869 xchdir(G.crontab_dir_name);
870 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
871 xsetenv("SHELL", DEFAULT_SHELL); /* once, for all future children */
872 crondlog(LVL8 "crond (busybox "BB_VER") started, log level %d", G.log_level);
873 rescan_crontab_dir();
874 write_pidfile("/var/run/crond.pid");
887 /* Synchronize to 1 minute, minimum 1 second */
888 sleep(sleep_time - (time(NULL) % sleep_time) + 1);
891 dt = (long)t2 - (long)t1;
894 * The file 'cron.update' is checked to determine new cron
895 * jobs. The directory is rescanned once an hour to deal
898 * Check for time jump. Disparities over an hour either way
899 * result in resynchronization. A negative disparity
900 * less than an hour causes us to effectively sleep until we
901 * match the original time (i.e. no re-execution of jobs that
902 * have just been run). A positive disparity less than
903 * an hour causes intermediate jobs to be run, but only once
906 * When running jobs, the inequality used is greater but not
907 * equal to t1, and less then or equal to t2.
909 if (stat(G.crontab_dir_name, &sbuf) != 0)
910 sbuf.st_mtime = 0; /* force update (once) if dir was deleted */
911 if (G.crontab_dir_mtime != sbuf.st_mtime) {
912 G.crontab_dir_mtime = sbuf.st_mtime;
917 rescan_crontab_dir();
919 process_cron_update_file();
921 crondlog(LVL5 "wakeup dt=%ld", dt);
922 if (dt < -60 * 60 || dt > 60 * 60) {
923 crondlog(WARN9 "time disparity of %ld minutes detected", dt / 60);
924 /* and we do not run any jobs in this case */
926 /* Usual case: time advances forward, as expected */
927 flag_starting_jobs(t1, t2);
929 if (check_completions() > 0) {
930 /* some jobs are still running */
936 /* else: time jumped back, do not run any jobs */
939 return 0; /* not reached */