1 /* vi: set sw=4 ts=4: */
3 * run as root, but NOT setuid root
5 * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com)
7 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
9 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 //config: bool "crond (14 kb)"
14 //config: select FEATURE_SYSLOG
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
24 //config:config FEATURE_CROND_D
25 //config: bool "Support -d (redirect output to stderr)"
26 //config: depends on CROND
29 //config: -d N sets loglevel (0:most verbose) and directs all output to stderr.
31 //config:config FEATURE_CROND_CALL_SENDMAIL
32 //config: bool "Report command output via email (using sendmail)"
34 //config: depends on CROND
36 //config: Command output will be sent to corresponding user via email.
38 //config:config FEATURE_CROND_SPECIAL_TIMES
39 //config: bool "Support special times (@reboot, @daily, etc) in crontabs"
41 //config: depends on CROND
43 //config: string meaning
44 //config: ------ -------
45 //config: @reboot Run once, at startup
46 //config: @yearly Run once a year: "0 0 1 1 *"
47 //config: @annually Same as @yearly: "0 0 1 1 *"
48 //config: @monthly Run once a month: "0 0 1 * *"
49 //config: @weekly Run once a week: "0 0 * * 0"
50 //config: @daily Run once a day: "0 0 * * *"
51 //config: @midnight Same as @daily: "0 0 * * *"
52 //config: @hourly Run once an hour: "0 * * * *"
54 //config:config FEATURE_CROND_DIR
55 //config: string "crond spool directory"
56 //config: default "/var/spool/cron"
57 //config: depends on CROND || CRONTAB
59 //config: Location of crond spool.
61 //applet:IF_CROND(APPLET(crond, BB_DIR_USR_SBIN, BB_SUID_DROP))
63 //kbuild:lib-$(CONFIG_CROND) += crond.o
65 //usage:#define crond_trivial_usage
66 //usage: "-fbS -l N " IF_FEATURE_CROND_D("-d N ") "-L LOGFILE -c DIR"
67 //usage:#define crond_full_usage "\n\n"
68 //usage: " -f Foreground"
69 //usage: "\n -b Background (default)"
70 //usage: "\n -S Log to syslog (default)"
71 //usage: "\n -l N Set log level. Most verbose 0, default 8"
72 //usage: IF_FEATURE_CROND_D(
73 //usage: "\n -d N Set log level, log to stderr"
75 //usage: "\n -L FILE Log to FILE"
76 //usage: "\n -c DIR Cron dir. Default:"CONFIG_FEATURE_CROND_DIR"/crontabs"
79 #include "common_bufsiz.h"
83 /* If libc tracks and reuses setenv()-allocated memory, ok to set this to 0 */
84 /* Neither glibc nor uclibc do that! */
85 # define SETENV_LEAKS 0
87 # define SETENV_LEAKS 1
91 #define CRON_DIR CONFIG_FEATURE_CROND_DIR
92 #define CRONTABS CONFIG_FEATURE_CROND_DIR "/crontabs"
93 #define CRON_REBOOT CONFIG_PID_FILE_PATH "/crond.reboot"
95 # define SENDMAIL "sendmail"
98 # define SENDMAIL_ARGS "-ti"
101 # define CRONUPDATE "cron.update"
104 # define MAXLINES 256 /* max lines in non-root crontabs */
108 typedef struct CronFile {
109 struct CronFile *cf_next;
110 struct CronLine *cf_lines;
112 smallint cf_wants_starting; /* bool: one or more jobs ready */
113 smallint cf_has_running; /* bool: one or more jobs running */
114 smallint cf_deleted; /* marked for deletion (but still has running jobs) */
117 typedef struct CronLine {
118 struct CronLine *cl_next;
119 char *cl_cmd; /* shell command */
120 pid_t cl_pid; /* >0:running, <0:needs to be started in this minute, 0:dormant */
121 #define START_ME_REBOOT -2
122 #define START_ME_NORMAL -1
123 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
124 int cl_empty_mail_size; /* size of mail header only, 0 if no mailfile */
125 char *cl_mailto; /* whom to mail results, may be NULL */
128 /* ordered by size, not in natural order. makes code smaller: */
129 char cl_Dow[7]; /* 0-6, beginning sunday */
130 char cl_Mons[12]; /* 0-11 */
131 char cl_Hrs[24]; /* 0-23 */
132 char cl_Days[32]; /* 1-31 */
133 char cl_Mins[60]; /* 0-59 */
147 OPT_d = (1 << 6) * ENABLE_FEATURE_CROND_D,
151 unsigned log_level; /* = 8; */
152 time_t crontab_dir_mtime;
153 const char *log_filename;
154 const char *crontab_dir_name; /* = CRONTABS; */
155 CronFile *cron_files;
161 char *env_var_logname;
164 #define G (*(struct globals*)bb_common_bufsiz1)
165 #define INIT_G() do { \
166 setup_common_bufsiz(); \
168 G.crontab_dir_name = CRONTABS; \
172 * 0 is the most verbose, default 8.
173 * For some reason, in fact only 5, 7 and 8 are used.
175 static void crondlog(unsigned level, const char *msg, va_list va)
177 if (level >= G.log_level) {
179 * We are called only for info meesages.
180 * Warnings/errors use plain bb_[p]error_msg's, which
181 * need not touch syslog_level
182 * (they are ok with LOG_ERR default).
184 bb_vinfo_msg(msg, va);
188 static void log5(const char *msg, ...)
192 crondlog(4, msg, va);
196 static void log7(const char *msg, ...)
200 crondlog(7, msg, va);
204 static void log8(const char *msg, ...)
208 crondlog(8, msg, va);
213 static const char DowAry[] ALIGN1 =
214 "sun""mon""tue""wed""thu""fri""sat"
217 static const char MonAry[] ALIGN1 =
218 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
221 static void ParseField(char *user, char *ary, int modvalue, int off,
222 const char *names, char *ptr)
223 /* 'names' is a pointer to a set of 3-char abbreviations */
229 // this can't happen due to config_read()
236 /* Handle numeric digit or symbol or '*' */
238 n1 = 0; /* everything will be filled */
242 } else if (isdigit(*ptr)) {
245 n1 = strtol(ptr, &endp, 10) + off;
247 n2 = strtol(ptr, &endp, 10) + off;
249 ptr = endp; /* gcc likes temp var for &endp */
254 for (i = 0; names[i]; i += 3) {
255 /* was using strncmp before... */
256 if (strncasecmp(ptr, &names[i], 3) == 0) {
269 /* handle optional range '-' */
273 if (*ptr == '-' && n2 < 0) {
279 * collapse single-value ranges, handle skipmark, and fill
280 * in the character array appropriately.
287 skip = strtol(ptr + 1, &endp, 10);
288 ptr = endp; /* gcc likes temp var for &endp */
292 * fill array, using a failsafe is the easiest way to prevent
301 n1 = (n1 + 1) % modvalue;
304 ary[n1 % modvalue] = 1;
307 if (--failsafe == 0) {
322 bb_error_msg("user %s: parse error at %s", user, base);
326 /* can't use log5 (it inserts newlines), open-coding it */
327 if (G.log_level <= 5 && logmode != LOGMODE_SYSLOG) {
329 for (i = 0; i < modvalue; ++i)
330 fprintf(stderr, "%d", (unsigned char)ary[i]);
331 bb_putchar_stderr('\n');
335 static void FixDayDow(CronLine *line)
341 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
342 if (line->cl_Dow[i] == 0) {
347 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
348 if (line->cl_Days[i] == 0) {
353 if (weekUsed != daysUsed) {
355 memset(line->cl_Days, 0, sizeof(line->cl_Days));
357 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
362 * delete_cronfile() - delete user database
364 * Note: multiple entries for same user may exist if we were unable to
365 * completely delete a database due to running processes.
367 //FIXME: we will start a new job even if the old job is running
368 //if crontab was reloaded: crond thinks that "new" job is different from "old"
369 //even if they are in fact completely the same. Example
372 // 0-59 * * * * long_running_job2
373 //User edits crontab to:
374 // 0-59 * * * * job1_updated
375 // 0-59 * * * * long_running_job2
376 //Bug: crond can now start another long_running_job2 even if old one
378 //OTOH most other versions of cron do not wait for job termination anyway,
379 //they end up with multiple copies of jobs if they don't terminate soon enough.
380 static void delete_cronfile(const char *userName)
382 CronFile **pfile = &G.cron_files;
385 while ((file = *pfile) != NULL) {
386 if (strcmp(userName, file->cf_username) == 0) {
387 CronLine **pline = &file->cf_lines;
390 file->cf_has_running = 0;
391 file->cf_deleted = 1;
393 while ((line = *pline) != NULL) {
394 if (line->cl_pid > 0) {
395 file->cf_has_running = 1;
396 pline = &line->cl_next;
398 *pline = line->cl_next;
403 if (file->cf_has_running == 0) {
404 *pfile = file->cf_next;
405 free(file->cf_username);
410 pfile = &file->cf_next;
414 static void load_crontab(const char *fileName)
416 struct parser_t *parser;
420 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
425 delete_cronfile(fileName);
427 if (!getpwnam(fileName)) {
428 log7("ignoring file '%s' (no such user)", fileName);
432 parser = config_open(fileName);
436 maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
438 if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DAEMON_UID) {
439 CronFile *file = xzalloc(sizeof(CronFile));
443 file->cf_username = xstrdup(fileName);
444 pline = &file->cf_lines;
450 bb_error_msg("user %s: too many lines", fileName);
454 n = config_read(parser, tokens, 6, 1, "# \t", PARSE_NORMAL | PARSE_KEEP_COPY);
458 log5("user:%s entry:%s", fileName, parser->data);
460 /* check if line is setting MAILTO= */
461 if (is_prefixed_with(tokens[0], "MAILTO=")) {
462 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
464 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
465 #endif /* otherwise just ignore such lines */
468 if (is_prefixed_with(tokens[0], "SHELL=")) {
470 shell = xstrdup(&tokens[0][6]);
473 //TODO: handle HOME= too? "man crontab" says:
476 //where the spaces around the equal-sign (=) are optional, and any subsequent
477 //non-leading spaces in value will be part of the value assigned to name.
478 //The value string may be placed in quotes (single or double, but matching)
479 //to preserve leading or trailing blanks.
481 //Several environment variables are set up automatically by the cron(8) daemon.
482 //SHELL is set to /bin/sh, and LOGNAME and HOME are set from the /etc/passwd
483 //line of the crontab's owner. HOME and SHELL may be overridden by settings
484 //in the crontab; LOGNAME may not.
486 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
487 if (tokens[0][0] == '@') {
489 * "@daily /a/script/to/run PARAM1 PARAM2..."
491 typedef struct SpecialEntry {
493 const char tokens[8];
495 static const SpecialEntry SpecAry[] = {
496 /* hour day month weekday */
497 { "yearly", "0\0" "1\0" "1\0" "*" },
498 { "annually", "0\0" "1\0" "1\0" "*" },
499 { "monthly", "0\0" "1\0" "*\0" "*" },
500 { "weekly", "0\0" "*\0" "*\0" "0" },
501 { "daily", "0\0" "*\0" "*\0" "*" },
502 { "midnight", "0\0" "*\0" "*\0" "*" },
503 { "hourly", "*\0" "*\0" "*\0" "*" },
506 const SpecialEntry *e = SpecAry;
511 if (strcmp(e->name, tokens[0] + 1) == 0) {
513 * tokens[1] is only the first word of command,
515 * find the entire command in unmodified string:
517 tokens[5] = skip_whitespace(
519 skip_whitespace(parser->data)));
521 char *et = (char*)e->tokens;
522 /* minute is "0" for all specials */
523 tokens[0] = (char*)"0";
535 continue; /* bad line (unrecognized '@foo') */
538 /* check if a minimum of tokens is specified */
541 IF_FEATURE_CROND_SPECIAL_TIMES(
544 *pline = line = xzalloc(sizeof(*line));
545 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
546 if (tokens[0][0] == '@') { /* "@reboot" line */
547 file->cf_wants_starting = 1;
548 line->cl_pid = START_ME_REBOOT; /* wants to start */
549 /* line->cl_Mins/Hrs/etc stay zero: never match any time */
553 /* parse date ranges */
554 ParseField(file->cf_username, line->cl_Mins, 60, 0, NULL, tokens[0]);
555 ParseField(file->cf_username, line->cl_Hrs, 24, 0, NULL, tokens[1]);
556 ParseField(file->cf_username, line->cl_Days, 32, 0, NULL, tokens[2]);
557 ParseField(file->cf_username, line->cl_Mons, 12, -1, MonAry, tokens[3]);
558 ParseField(file->cf_username, line->cl_Dow, 7, 0, DowAry, tokens[4]);
560 * fix days and dow - if one is not "*" and the other
561 * is "*", the other is set to 0, and vise-versa
565 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
566 /* copy mailto (can be NULL) */
567 line->cl_mailto = xstrdup(mailTo);
569 line->cl_shell = xstrdup(shell);
571 line->cl_cmd = xstrdup(tokens[5]);
572 pline = &line->cl_next;
573 //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]);
577 file->cf_next = G.cron_files;
580 config_close(parser);
581 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
587 static void process_cron_update_file(void)
592 fi = fopen_for_read(CRONUPDATE);
595 while (fgets(buf, sizeof(buf), fi) != NULL) {
596 /* use first word only */
597 skip_non_whitespace(buf)[0] = '\0';
604 static void rescan_crontab_dir(void)
608 /* Delete all files until we only have ones with running jobs (or none) */
610 for (file = G.cron_files; file; file = file->cf_next) {
611 if (!file->cf_deleted) {
612 delete_cronfile(file->cf_username);
617 /* Remove cron update file */
619 /* Re-chdir, in case directory was renamed & deleted */
620 xchdir(G.crontab_dir_name);
622 /* Scan directory and add associated users */
624 DIR *dir = opendir(".");
627 /* xopendir exists, but "can't open '.'" is not informative */
629 bb_error_msg_and_die("can't open '%s'", G.crontab_dir_name);
630 while ((den = readdir(dir)) != NULL) {
631 if (strchr(den->d_name, '.') != NULL) {
634 load_crontab(den->d_name);
641 /* We set environment *before* vfork (because we want to use vfork),
642 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
643 * Using putenv(), and freeing memory after unsetenv() won't leak */
644 static void safe_setenv(char **pvar_val, const char *var, const char *val)
646 char *var_val = *pvar_val;
649 bb_unsetenv_and_free(var_val);
651 *pvar_val = xasprintf("%s=%s", var, val);
656 static void set_env_vars(struct passwd *pas, const char *shell)
658 /* POSIX requires crond to set up at least HOME, LOGNAME, PATH, SHELL.
659 * We assume crond inherited suitable PATH.
662 safe_setenv(&G.env_var_logname, "LOGNAME", pas->pw_name);
663 safe_setenv(&G.env_var_user, "USER", pas->pw_name);
664 safe_setenv(&G.env_var_home, "HOME", pas->pw_dir);
665 safe_setenv(&G.env_var_shell, "SHELL", shell);
667 xsetenv("LOGNAME", pas->pw_name);
668 xsetenv("USER", pas->pw_name);
669 xsetenv("HOME", pas->pw_dir);
670 xsetenv("SHELL", shell);
674 static void change_user(struct passwd *pas)
676 /* careful: we're after vfork! */
677 change_identity(pas); /* - initgroups, setgid, setuid */
678 if (chdir(pas->pw_dir) < 0) {
679 bb_error_msg("can't change directory to '%s'", pas->pw_dir);
684 // TODO: sendmail should be _run-time_ option, not compile-time!
685 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
688 fork_job(const char *user, int mailFd, CronLine *line, bool run_sendmail)
691 const char *shell, *prog;
695 /* prepare things before vfork */
696 pas = getpwnam(user);
698 bb_error_msg("can't get uid for %s", user);
702 shell = line->cl_shell ? line->cl_shell : G.default_shell;
703 prog = run_sendmail ? SENDMAIL : shell;
705 set_env_vars(pas, shell);
707 sv_logmode = logmode;
711 /* initgroups, setgid, setuid, and chdir to home or CRON_DIR */
713 log5("child running %s", prog);
715 xmove_fd(mailFd, run_sendmail ? 0 : 1);
718 /* crond 3.0pl1-100 puts tasks in separate process groups */
721 execlp(prog, prog, "-c", line->cl_cmd, (char *) NULL);
723 execlp(prog, prog, SENDMAIL_ARGS, (char *) NULL);
725 * I want this error message on stderr too,
726 * even if other messages go only to syslog:
728 logmode |= LOGMODE_STDIO;
729 bb_error_msg_and_die("can't execute '%s' for user %s", prog, user);
731 logmode = sv_logmode;
734 bb_perror_msg("vfork");
737 } /* else: PARENT, FORK SUCCESS */
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
749 static pid_t start_one_job(const char *user, CronLine *line)
755 line->cl_empty_mail_size = 0;
757 if (line->cl_mailto) {
758 /* Open mail file (owner is root so nobody can screw with it) */
759 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", CRON_DIR, user, getpid());
760 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
763 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_mailto,
765 line->cl_empty_mail_size = lseek(mailFd, 0, SEEK_CUR);
767 bb_error_msg("can't create mail file %s for user %s, "
768 "discarding output", mailFile, user);
772 line->cl_pid = fork_job(user, mailFd, line, /*sendmail?*/ 0);
774 if (line->cl_pid <= 0) {
777 /* rename mail-file based on pid of process */
778 char *mailFile2 = xasprintf("%s/cron.%s.%d", CRON_DIR, user, (int)line->cl_pid);
779 rename(mailFile, mailFile2); // TODO: xrename?
788 * process_finished_job - called when job terminates and when mail terminates
790 static void process_finished_job(const char *user, CronLine *line)
803 if (line->cl_empty_mail_size <= 0) {
804 /* End of job and no mail file, or end of sendmail job */
809 * End of primary job - check for mail file.
810 * If size has changed and the file is still valid, we send it.
812 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", CRON_DIR, user, (int)pid);
813 mailFd = open(mailFile, O_RDONLY);
819 if (fstat(mailFd, &sbuf) < 0
820 || sbuf.st_uid != DAEMON_UID
821 || sbuf.st_nlink != 0
822 || sbuf.st_size == line->cl_empty_mail_size
823 || !S_ISREG(sbuf.st_mode)
828 line->cl_empty_mail_size = 0;
829 /* if (line->cl_mailto) - always true if cl_empty_mail_size was nonzero */
830 line->cl_pid = fork_job(user, mailFd, line, /*sendmail?*/ 1);
833 #else /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
835 static pid_t start_one_job(const char *user, CronLine *line)
841 pas = getpwnam(user);
843 bb_error_msg("can't get uid for %s", user);
847 /* Prepare things before vfork */
848 shell = line->cl_shell ? line->cl_shell : G.default_shell;
849 set_env_vars(pas, shell);
851 /* Fork as the user in question and run program */
855 /* initgroups, setgid, setuid, and chdir to home or CRON_DIR */
857 log5("child running %s", shell);
858 /* crond 3.0pl1-100 puts tasks in separate process groups */
860 execl(shell, shell, "-c", line->cl_cmd, (char *) NULL);
861 bb_error_msg_and_die("can't execute '%s' for user %s", shell, user);
864 bb_perror_msg("vfork");
872 #define process_finished_job(user, line) ((line)->cl_pid = 0)
874 #endif /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
877 * Determine which jobs need to be run. Under normal conditions, the
878 * period is about a minute (one scan). Worst case it will be one
881 static void flag_starting_jobs(time_t t1, time_t t2)
885 /* Find jobs > t1 and <= t2 */
887 for (t = t1 - t1 % 60; t <= t2; t += 60) {
896 for (file = G.cron_files; file; file = file->cf_next) {
897 log5("file %s:", file->cf_username);
898 if (file->cf_deleted)
900 for (line = file->cf_lines; line; line = line->cl_next) {
901 log5(" line %s", line->cl_cmd);
902 if (line->cl_Mins[ptm->tm_min]
903 && line->cl_Hrs[ptm->tm_hour]
904 && (line->cl_Days[ptm->tm_mday] || line->cl_Dow[ptm->tm_wday])
905 && line->cl_Mons[ptm->tm_mon]
908 (int)line->cl_pid, line->cl_cmd);
909 if (line->cl_pid > 0) {
910 log8("user %s: process already running: %s",
911 file->cf_username, line->cl_cmd);
912 } else if (line->cl_pid == 0) {
913 line->cl_pid = START_ME_NORMAL;
914 file->cf_wants_starting = 1;
922 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
923 static int touch_reboot_file(void)
925 int fd = open(CRON_REBOOT, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, 0000);
930 /* File (presumably) exists - this is not the first run after reboot */
935 static void start_jobs(int wants_start)
940 for (file = G.cron_files; file; file = file->cf_next) {
941 if (!file->cf_wants_starting)
944 file->cf_wants_starting = 0;
945 for (line = file->cf_lines; line; line = line->cl_next) {
947 if (line->cl_pid != wants_start)
950 pid = start_one_job(file->cf_username, line);
951 log8("USER %s pid %3d cmd %s",
952 file->cf_username, (int)pid, line->cl_cmd);
954 file->cf_wants_starting = 1;
957 file->cf_has_running = 1;
964 * Check for job completion, return number of jobs still running after
967 static int check_completions(void)
971 int num_still_running = 0;
973 for (file = G.cron_files; file; file = file->cf_next) {
974 if (!file->cf_has_running)
977 file->cf_has_running = 0;
978 for (line = file->cf_lines; line; line = line->cl_next) {
981 if (line->cl_pid <= 0)
984 r = waitpid(line->cl_pid, NULL, WNOHANG);
985 if (r < 0 || r == line->cl_pid) {
986 process_finished_job(file->cf_username, line);
987 if (line->cl_pid == 0) {
988 /* sendmail was not started for it */
991 /* else: sendmail was started, job is still running, fall thru */
993 /* else: r == 0: "process is still running" */
994 file->cf_has_running = 1;
996 //FIXME: if !file->cf_has_running && file->deleted: delete it!
997 //otherwise deleted entries will stay forever, right?
998 num_still_running += file->cf_has_running;
1000 return num_still_running;
1003 static void reopen_logfile_to_stderr(void)
1005 if (G.log_filename) {
1006 int logfd = open_or_warn(G.log_filename, O_WRONLY | O_CREAT | O_APPEND);
1008 xmove_fd(logfd, STDERR_FILENO);
1012 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1013 int crond_main(int argc UNUSED_PARAM, char **argv)
1017 unsigned sleep_time;
1022 opts = getopt32(argv, "^"
1023 "l:L:fbSc:" IF_FEATURE_CROND_D("d:")
1025 /* "-b after -f is ignored", and so on for every pair a-b */
1026 "f-b:b-f:S-L:L-S" IF_FEATURE_CROND_D(":d-l")
1027 /* -l and -d have numeric param */
1028 ":l+" IF_FEATURE_CROND_D(":d+")
1030 &G.log_level, &G.log_filename, &G.crontab_dir_name
1031 IF_FEATURE_CROND_D(,&G.log_level)
1033 /* both -d N and -l N set the same variable: G.log_level */
1035 if (!(opts & OPT_f)) {
1036 /* close stdin, stdout, stderr.
1037 * close unused descriptors - don't need them. */
1038 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
1041 if (!(opts & OPT_d) && G.log_filename == NULL) {
1042 /* logging to syslog */
1043 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
1044 logmode = LOGMODE_SYSLOG;
1047 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
1049 reopen_logfile_to_stderr();
1050 xchdir(G.crontab_dir_name);
1051 /* $SHELL, or current UID's shell, or DEFAULT_SHELL */
1052 /* Useful on Android where DEFAULT_SHELL /bin/sh may not exist */
1053 G.default_shell = xstrdup(get_shell_name());
1055 log8("crond (busybox "BB_VER") started, log level %d", G.log_level);
1056 rescan_crontab_dir();
1057 write_pidfile_std_path_and_ext("crond");
1058 #if ENABLE_FEATURE_CROND_SPECIAL_TIMES
1059 if (touch_reboot_file())
1060 start_jobs(START_ME_REBOOT); /* start @reboot entries, if any */
1072 /* Synchronize to 1 minute, minimum 1 second */
1074 sleep(sleep_time - (time(NULL) % sleep_time));
1076 dt = (long)t2 - (long)t1;
1078 reopen_logfile_to_stderr();
1081 * The file 'cron.update' is checked to determine new cron
1082 * jobs. The directory is rescanned once an hour to deal
1083 * with any screwups.
1085 * Check for time jump. Disparities over an hour either way
1086 * result in resynchronization. A negative disparity
1087 * less than an hour causes us to effectively sleep until we
1088 * match the original time (i.e. no re-execution of jobs that
1089 * have just been run). A positive disparity less than
1090 * an hour causes intermediate jobs to be run, but only once
1091 * in the worst case.
1093 * When running jobs, the inequality used is greater but not
1094 * equal to t1, and less then or equal to t2.
1096 if (stat(G.crontab_dir_name, &sbuf) != 0)
1097 sbuf.st_mtime = 0; /* force update (once) if dir was deleted */
1098 if (G.crontab_dir_mtime != sbuf.st_mtime) {
1099 G.crontab_dir_mtime = sbuf.st_mtime;
1102 if (--rescan == 0) {
1104 rescan_crontab_dir();
1106 process_cron_update_file();
1107 log5("wakeup dt=%ld", dt);
1108 if (dt < -60 * 60 || dt > 60 * 60) {
1109 bb_info_msg("time disparity of %ld minutes detected", dt / 60);
1110 /* and we do not run any jobs in this case */
1111 } else if (dt > 0) {
1112 /* Usual case: time advances forward, as expected */
1113 flag_starting_jobs(t1, t2);
1114 start_jobs(START_ME_NORMAL);
1116 if (check_completions() > 0) {
1117 /* some jobs are still running */
1121 /* else: time jumped back, do not run any jobs */
1124 return 0; /* not reached */