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.
14 //usage:#define crond_trivial_usage
15 //usage: "-fbS -l N " IF_FEATURE_CROND_D("-d N ") "-L LOGFILE -c DIR"
16 //usage:#define crond_full_usage "\n\n"
17 //usage: " -f Foreground"
18 //usage: "\n -b Background (default)"
19 //usage: "\n -S Log to syslog (default)"
20 //usage: "\n -l Set log level. 0 is the most verbose, default 8"
21 //usage: IF_FEATURE_CROND_D(
22 //usage: "\n -d Set log level, log to stderr"
24 //usage: "\n -L Log to file"
25 //usage: "\n -c Working dir"
30 /* glibc frees previous setenv'ed value when we do next setenv()
31 * of the same variable. uclibc does not do this! */
32 #if (defined(__GLIBC__) && !defined(__UCLIBC__)) /* || OTHER_SAFE_LIBC... */
33 # define SETENV_LEAKS 0
35 # define SETENV_LEAKS 1
39 #define TMPDIR CONFIG_FEATURE_CROND_DIR
40 #define CRONTABS CONFIG_FEATURE_CROND_DIR "/crontabs"
42 # define SENDMAIL "sendmail"
45 # define SENDMAIL_ARGS "-ti"
48 # define CRONUPDATE "cron.update"
51 # define MAXLINES 256 /* max lines in non-root crontabs */
55 typedef struct CronFile {
56 struct CronFile *cf_next;
57 struct CronLine *cf_lines;
59 smallint cf_wants_starting; /* bool: one or more jobs ready */
60 smallint cf_has_running; /* bool: one or more jobs running */
61 smallint cf_deleted; /* marked for deletion (but still has running jobs) */
64 typedef struct CronLine {
65 struct CronLine *cl_next;
66 char *cl_cmd; /* shell command */
67 pid_t cl_pid; /* >0:running, <0:needs to be started in this minute, 0:dormant */
68 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
69 int cl_empty_mail_size; /* size of mail header only, 0 if no mailfile */
70 char *cl_mailto; /* whom to mail results, may be NULL */
72 /* ordered by size, not in natural order. makes code smaller: */
73 char cl_Dow[7]; /* 0-6, beginning sunday */
74 char cl_Mons[12]; /* 0-11 */
75 char cl_Hrs[24]; /* 0-23 */
76 char cl_Days[32]; /* 1-31 */
77 char cl_Mins[60]; /* 0-59 */
91 OPT_d = (1 << 6) * ENABLE_FEATURE_CROND_D,
93 #if ENABLE_FEATURE_CROND_D
94 # define DebugOpt (option_mask32 & OPT_d)
101 unsigned log_level; /* = 8; */
102 time_t crontab_dir_mtime;
103 const char *log_filename;
104 const char *crontab_dir_name; /* = CRONTABS; */
105 CronFile *cron_files;
111 #define G (*(struct globals*)&bb_common_bufsiz1)
112 #define INIT_G() do { \
114 G.crontab_dir_name = CRONTABS; \
118 /* 0 is the most verbose, default 8 */
124 /* level >= 20 is "error" */
127 static void crondlog(const char *ctl, ...) __attribute__ ((format (printf, 1, 2)));
128 static void crondlog(const char *ctl, ...)
131 int level = (ctl[0] & 0x1f);
134 if (level >= (int)G.log_level) {
135 /* Debug mode: all to (non-redirected) stderr, */
136 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
137 if (!DebugOpt && G.log_filename) {
138 /* Otherwise (log to file): we reopen log file at every write: */
139 int logfd = open_or_warn(G.log_filename, O_WRONLY | O_CREAT | O_APPEND);
141 xmove_fd(logfd, STDERR_FILENO);
143 /* When we log to syslog, level > 8 is logged at LOG_ERR
144 * syslog level, level <= 8 is logged at LOG_INFO. */
146 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
149 vasprintf(&msg, ctl + 1, va);
150 bb_info_msg("%s: %s", applet_name, msg);
159 static const char DowAry[] ALIGN1 =
160 "sun""mon""tue""wed""thu""fri""sat"
161 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
164 static const char MonAry[] ALIGN1 =
165 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
166 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
169 static void ParseField(char *user, char *ary, int modvalue, int off,
170 const char *names, char *ptr)
171 /* 'names' is a pointer to a set of 3-char abbreviations */
177 // this can't happen due to config_read()
184 /* Handle numeric digit or symbol or '*' */
186 n1 = 0; /* everything will be filled */
190 } else if (isdigit(*ptr)) {
193 n1 = strtol(ptr, &endp, 10) + off;
195 n2 = strtol(ptr, &endp, 10) + off;
197 ptr = endp; /* gcc likes temp var for &endp */
202 for (i = 0; names[i]; i += 3) {
203 /* was using strncmp before... */
204 if (strncasecmp(ptr, &names[i], 3) == 0) {
217 /* handle optional range '-' */
221 if (*ptr == '-' && n2 < 0) {
227 * collapse single-value ranges, handle skipmark, and fill
228 * in the character array appropriately.
235 skip = strtol(ptr + 1, &endp, 10);
236 ptr = endp; /* gcc likes temp var for &endp */
240 * fill array, using a failsafe is the easiest way to prevent
249 n1 = (n1 + 1) % modvalue;
252 ary[n1 % modvalue] = 1;
255 if (--failsafe == 0) {
270 crondlog(WARN9 "user %s: parse error at %s", user, base);
274 if (DebugOpt && (G.log_level <= 5)) { /* like LVL5 */
275 /* can't use crondlog, it inserts '\n' */
277 for (i = 0; i < modvalue; ++i)
278 fprintf(stderr, "%d", (unsigned char)ary[i]);
279 bb_putchar_stderr('\n');
283 static void FixDayDow(CronLine *line)
289 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
290 if (line->cl_Dow[i] == 0) {
295 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
296 if (line->cl_Days[i] == 0) {
301 if (weekUsed != daysUsed) {
303 memset(line->cl_Days, 0, sizeof(line->cl_Days));
305 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
310 * delete_cronfile() - delete user database
312 * Note: multiple entries for same user may exist if we were unable to
313 * completely delete a database due to running processes.
315 //FIXME: we will start a new job even if the old job is running
316 //if crontab was reloaded: crond thinks that "new" job is different from "old"
317 //even if they are in fact completely the same. Example
320 // 0-59 * * * * long_running_job2
321 //User edits crontab to:
322 // 0-59 * * * * job1_updated
323 // 0-59 * * * * long_running_job2
324 //Bug: crond can now start another long_running_job2 even if old one
326 //OTOH most other versions of cron do not wait for job termination anyway,
327 //they end up with multiple copies of jobs if they don't terminate soon enough.
328 static void delete_cronfile(const char *userName)
330 CronFile **pfile = &G.cron_files;
333 while ((file = *pfile) != NULL) {
334 if (strcmp(userName, file->cf_username) == 0) {
335 CronLine **pline = &file->cf_lines;
338 file->cf_has_running = 0;
339 file->cf_deleted = 1;
341 while ((line = *pline) != NULL) {
342 if (line->cl_pid > 0) {
343 file->cf_has_running = 1;
344 pline = &line->cl_next;
346 *pline = line->cl_next;
351 if (file->cf_has_running == 0) {
352 *pfile = file->cf_next;
353 free(file->cf_username);
358 pfile = &file->cf_next;
362 static void load_crontab(const char *fileName)
364 struct parser_t *parser;
368 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
372 delete_cronfile(fileName);
374 if (!getpwnam(fileName)) {
375 crondlog(LVL7 "ignoring file '%s' (no such user)", fileName);
379 parser = config_open(fileName);
383 maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
385 if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DAEMON_UID) {
386 CronFile *file = xzalloc(sizeof(CronFile));
390 file->cf_username = xstrdup(fileName);
391 pline = &file->cf_lines;
398 n = config_read(parser, tokens, 6, 1, "# \t", PARSE_NORMAL | PARSE_KEEP_COPY);
403 crondlog(LVL5 "user:%s entry:%s", fileName, parser->data);
405 /* check if line is setting MAILTO= */
406 if (0 == strncmp(tokens[0], "MAILTO=", 7)) {
407 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
409 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
410 #endif /* otherwise just ignore such lines */
413 /* check if a minimum of tokens is specified */
416 *pline = line = xzalloc(sizeof(*line));
417 /* parse date ranges */
418 ParseField(file->cf_username, line->cl_Mins, 60, 0, NULL, tokens[0]);
419 ParseField(file->cf_username, line->cl_Hrs, 24, 0, NULL, tokens[1]);
420 ParseField(file->cf_username, line->cl_Days, 32, 0, NULL, tokens[2]);
421 ParseField(file->cf_username, line->cl_Mons, 12, -1, MonAry, tokens[3]);
422 ParseField(file->cf_username, line->cl_Dow, 7, 0, DowAry, tokens[4]);
424 * fix days and dow - if one is not "*" and the other
425 * is "*", the other is set to 0, and vise-versa
428 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
429 /* copy mailto (can be NULL) */
430 line->cl_mailto = xstrdup(mailTo);
433 line->cl_cmd = xstrdup(tokens[5]);
435 crondlog(LVL5 " command:%s", tokens[5]);
437 pline = &line->cl_next;
438 //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]);
442 file->cf_next = G.cron_files;
446 crondlog(WARN9 "user %s: too many lines", fileName);
449 config_close(parser);
452 static void process_cron_update_file(void)
457 fi = fopen_for_read(CRONUPDATE);
460 while (fgets(buf, sizeof(buf), fi) != NULL) {
461 /* use first word only */
462 skip_non_whitespace(buf)[0] = '\0';
469 static void rescan_crontab_dir(void)
473 /* Delete all files until we only have ones with running jobs (or none) */
475 for (file = G.cron_files; file; file = file->cf_next) {
476 if (!file->cf_deleted) {
477 delete_cronfile(file->cf_username);
482 /* Remove cron update file */
484 /* Re-chdir, in case directory was renamed & deleted */
485 if (chdir(G.crontab_dir_name) < 0) {
486 crondlog(DIE9 "chdir(%s)", G.crontab_dir_name);
489 /* Scan directory and add associated users */
491 DIR *dir = opendir(".");
495 crondlog(DIE9 "chdir(%s)", "."); /* exits */
496 while ((den = readdir(dir)) != NULL) {
497 if (strchr(den->d_name, '.') != NULL) {
500 load_crontab(den->d_name);
507 /* We set environment *before* vfork (because we want to use vfork),
508 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
509 * Using putenv(), and freeing memory after unsetenv() won't leak */
510 static void safe_setenv(char **pvar_val, const char *var, const char *val)
512 char *var_val = *pvar_val;
515 bb_unsetenv_and_free(var_val);
517 *pvar_val = xasprintf("%s=%s", var, val);
522 static void set_env_vars(struct passwd *pas)
525 safe_setenv(&G.env_var_user, "USER", pas->pw_name);
526 safe_setenv(&G.env_var_home, "HOME", pas->pw_dir);
527 /* if we want to set user's shell instead: */
528 /*safe_setenv(G.env_var_shell, "SHELL", pas->pw_shell);*/
530 xsetenv("USER", pas->pw_name);
531 xsetenv("HOME", pas->pw_dir);
533 /* currently, we use constant one: */
534 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
537 static void change_user(struct passwd *pas)
539 /* careful: we're after vfork! */
540 change_identity(pas); /* - initgroups, setgid, setuid */
541 if (chdir(pas->pw_dir) < 0) {
542 crondlog(WARN9 "chdir(%s)", pas->pw_dir);
543 if (chdir(TMPDIR) < 0) {
544 crondlog(DIE9 "chdir(%s)", TMPDIR); /* exits */
549 // TODO: sendmail should be _run-time_ option, not compile-time!
550 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
553 fork_job(const char *user, int mailFd,
555 const char *shell_cmd /* if NULL, we run sendmail */
560 /* prepare things before vfork */
561 pas = getpwnam(user);
563 crondlog(WARN9 "can't get uid for %s", user);
571 /* initgroups, setgid, setuid, and chdir to home or TMPDIR */
574 crondlog(LVL5 "child running %s", prog);
577 xmove_fd(mailFd, shell_cmd ? 1 : 0);
580 /* crond 3.0pl1-100 puts tasks in separate process groups */
582 execlp(prog, prog, (shell_cmd ? "-c" : SENDMAIL_ARGS), shell_cmd, (char *) NULL);
583 crondlog(ERR20 "can't execute '%s' for user %s", prog, user);
585 fdprintf(1, "Exec failed: %s -c %s\n", prog, shell_cmd);
592 crondlog(ERR20 "can't vfork");
595 } /* else: PARENT, FORK SUCCESS */
598 * Close the mail file descriptor.. we can't just leave it open in
599 * a structure, closing it later, because we might run out of descriptors
607 static void start_one_job(const char *user, CronLine *line)
613 line->cl_empty_mail_size = 0;
615 if (line->cl_mailto) {
616 /* Open mail file (owner is root so nobody can screw with it) */
617 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
618 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
621 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_mailto,
623 line->cl_empty_mail_size = lseek(mailFd, 0, SEEK_CUR);
625 crondlog(ERR20 "can't create mail file %s for user %s, "
626 "discarding output", mailFile, user);
630 line->cl_pid = fork_job(user, mailFd, DEFAULT_SHELL, line->cl_cmd);
632 if (line->cl_pid <= 0) {
635 /* rename mail-file based on pid of process */
636 char *mailFile2 = xasprintf("%s/cron.%s.%d", TMPDIR, user, (int)line->cl_pid);
637 rename(mailFile, mailFile2); // TODO: xrename?
644 * process_finished_job - called when job terminates and when mail terminates
646 static void process_finished_job(const char *user, CronLine *line)
659 if (line->cl_empty_mail_size <= 0) {
660 /* End of job and no mail file, or end of sendmail job */
665 * End of primary job - check for mail file.
666 * If size has changed and the file is still valid, we send it.
668 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, (int)pid);
669 mailFd = open(mailFile, O_RDONLY);
675 if (fstat(mailFd, &sbuf) < 0
676 || sbuf.st_uid != DAEMON_UID
677 || sbuf.st_nlink != 0
678 || sbuf.st_size == line->cl_empty_mail_size
679 || !S_ISREG(sbuf.st_mode)
684 line->cl_empty_mail_size = 0;
685 /* if (line->cl_mailto) - always true if cl_empty_mail_size was nonzero */
686 line->cl_pid = fork_job(user, mailFd, SENDMAIL, NULL);
689 #else /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
691 static void start_one_job(const char *user, CronLine *line)
696 pas = getpwnam(user);
698 crondlog(WARN9 "can't get uid for %s", user);
702 /* Prepare things before vfork */
705 /* Fork as the user in question and run program */
709 /* initgroups, setgid, setuid, and chdir to home or TMPDIR */
712 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
714 /* crond 3.0pl1-100 puts tasks in separate process groups */
716 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_cmd, (char *) NULL);
717 crondlog(ERR20 "can't execute '%s' for user %s", DEFAULT_SHELL, user);
722 crondlog(ERR20 "can't vfork");
729 #define process_finished_job(user, line) ((line)->cl_pid = 0)
731 #endif /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
734 * Determine which jobs need to be run. Under normal conditions, the
735 * period is about a minute (one scan). Worst case it will be one
738 static void flag_starting_jobs(time_t t1, time_t t2)
742 /* Find jobs > t1 and <= t2 */
744 for (t = t1 - t1 % 60; t <= t2; t += 60) {
753 for (file = G.cron_files; file; file = file->cf_next) {
755 crondlog(LVL5 "file %s:", file->cf_username);
756 if (file->cf_deleted)
758 for (line = file->cf_lines; line; line = line->cl_next) {
760 crondlog(LVL5 " line %s", line->cl_cmd);
761 if (line->cl_Mins[ptm->tm_min]
762 && line->cl_Hrs[ptm->tm_hour]
763 && (line->cl_Days[ptm->tm_mday] || line->cl_Dow[ptm->tm_wday])
764 && line->cl_Mons[ptm->tm_mon]
767 crondlog(LVL5 " job: %d %s",
768 (int)line->cl_pid, line->cl_cmd);
770 if (line->cl_pid > 0) {
771 crondlog(LVL8 "user %s: process already running: %s",
772 file->cf_username, line->cl_cmd);
773 } else if (line->cl_pid == 0) {
775 file->cf_wants_starting = 1;
783 static void start_jobs(void)
788 for (file = G.cron_files; file; file = file->cf_next) {
789 if (!file->cf_wants_starting)
792 file->cf_wants_starting = 0;
793 for (line = file->cf_lines; line; line = line->cl_next) {
795 if (line->cl_pid >= 0)
798 start_one_job(file->cf_username, line);
800 crondlog(LVL8 "USER %s pid %3d cmd %s",
801 file->cf_username, (int)pid, line->cl_cmd);
803 file->cf_wants_starting = 1;
806 file->cf_has_running = 1;
813 * Check for job completion, return number of jobs still running after
816 static int check_completions(void)
820 int num_still_running = 0;
822 for (file = G.cron_files; file; file = file->cf_next) {
823 if (!file->cf_has_running)
826 file->cf_has_running = 0;
827 for (line = file->cf_lines; line; line = line->cl_next) {
830 if (line->cl_pid <= 0)
833 r = waitpid(line->cl_pid, NULL, WNOHANG);
834 if (r < 0 || r == line->cl_pid) {
835 process_finished_job(file->cf_username, line);
836 if (line->cl_pid == 0) {
837 /* sendmail was not started for it */
840 /* else: sendmail was started, job is still running, fall thru */
842 /* else: r == 0: "process is still running" */
843 file->cf_has_running = 1;
845 //FIXME: if !file->cf_has_running && file->deleted: delete it!
846 //otherwise deleted entries will stay forever, right?
847 num_still_running += file->cf_has_running;
849 return num_still_running;
852 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
853 int crond_main(int argc UNUSED_PARAM, char **argv)
862 /* "-b after -f is ignored", and so on for every pair a-b */
863 opt_complementary = "f-b:b-f:S-L:L-S" IF_FEATURE_CROND_D(":d-l")
864 /* -l and -d have numeric param */
865 ":l+" IF_FEATURE_CROND_D(":d+");
866 opts = getopt32(argv, "l:L:fbSc:" IF_FEATURE_CROND_D("d:"),
867 &G.log_level, &G.log_filename, &G.crontab_dir_name
868 IF_FEATURE_CROND_D(,&G.log_level));
869 /* both -d N and -l N set the same variable: G.log_level */
871 if (!(opts & OPT_f)) {
872 /* close stdin, stdout, stderr.
873 * close unused descriptors - don't need them. */
874 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
877 if (!(opts & OPT_d) && G.log_filename == NULL) {
878 /* logging to syslog */
879 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
880 logmode = LOGMODE_SYSLOG;
883 xchdir(G.crontab_dir_name);
884 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
885 xsetenv("SHELL", DEFAULT_SHELL); /* once, for all future children */
886 crondlog(LVL8 "crond (busybox "BB_VER") started, log level %d", G.log_level);
887 rescan_crontab_dir();
888 write_pidfile("/var/run/crond.pid");
901 /* Synchronize to 1 minute, minimum 1 second */
902 sleep(sleep_time - (time(NULL) % sleep_time) + 1);
905 dt = (long)t2 - (long)t1;
908 * The file 'cron.update' is checked to determine new cron
909 * jobs. The directory is rescanned once an hour to deal
912 * Check for time jump. Disparities over an hour either way
913 * result in resynchronization. A negative disparity
914 * less than an hour causes us to effectively sleep until we
915 * match the original time (i.e. no re-execution of jobs that
916 * have just been run). A positive disparity less than
917 * an hour causes intermediate jobs to be run, but only once
920 * When running jobs, the inequality used is greater but not
921 * equal to t1, and less then or equal to t2.
923 if (stat(G.crontab_dir_name, &sbuf) != 0)
924 sbuf.st_mtime = 0; /* force update (once) if dir was deleted */
925 if (G.crontab_dir_mtime != sbuf.st_mtime) {
926 G.crontab_dir_mtime = sbuf.st_mtime;
931 rescan_crontab_dir();
933 process_cron_update_file();
935 crondlog(LVL5 "wakeup dt=%ld", dt);
936 if (dt < -60 * 60 || dt > 60 * 60) {
937 crondlog(WARN9 "time disparity of %ld minutes detected", dt / 60);
938 /* and we do not run any jobs in this case */
940 /* Usual case: time advances forward, as expected */
941 flag_starting_jobs(t1, t2);
943 if (check_completions() > 0) {
944 /* some jobs are still running */
950 /* else: time jumped back, do not run any jobs */
953 return 0; /* not reached */