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 the GPL v2 or later, see the file LICENSE in this tarball.
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", NULL
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_LineBase;
45 char *cf_User; /* username */
46 smallint cf_Ready; /* bool: one or more jobs ready */
47 smallint cf_Running; /* bool: one or more jobs running */
48 smallint cf_Deleted; /* marked for deletion, ignore */
51 typedef struct CronLine {
52 struct CronLine *cl_Next;
53 char *cl_Shell; /* shell command */
54 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
55 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
56 int cl_MailPos; /* 'empty file' size */
57 char *cl_MailTo; /* whom to mail results */
58 smallint cl_MailFlag; /* running pid is for mail */
60 /* ordered by size, not in natural order. makes code smaller: */
61 char cl_Dow[7]; /* 0-6, beginning sunday */
62 char cl_Mons[12]; /* 0-11 */
63 char cl_Hrs[24]; /* 0-23 */
64 char cl_Days[32]; /* 1-31 */
65 char cl_Mins[60]; /* 0-59 */
79 OPT_d = (1 << 6) * ENABLE_FEATURE_CROND_D,
81 #if ENABLE_FEATURE_CROND_D
82 #define DebugOpt (option_mask32 & OPT_d)
89 unsigned LogLevel; /* = 8; */
92 const char *CDir; /* = CRONTABS; */
99 #define G (*(struct globals*)&bb_common_bufsiz1)
100 #define INIT_G() do { \
106 /* 0 is the most verbose, default 8 */
112 /* level >= 20 is "error" */
115 static void crondlog(const char *ctl, ...) __attribute__ ((format (printf, 1, 2)));
116 static void crondlog(const char *ctl, ...)
119 int level = (ctl[0] & 0x1f);
122 if (level >= (int)G.LogLevel) {
123 /* Debug mode: all to (non-redirected) stderr, */
124 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
125 if (!DebugOpt && G.LogFile) {
126 /* Otherwise (log to file): we reopen log file at every write: */
127 int logfd = open3_or_warn(G.LogFile, O_WRONLY | O_CREAT | O_APPEND, 0666);
129 xmove_fd(logfd, STDERR_FILENO);
131 /* When we log to syslog, level > 8 is logged at LOG_ERR
132 * syslog level, level <= 8 is logged at LOG_INFO. */
134 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
137 vasprintf(&msg, ctl + 1, va);
138 bb_info_msg("%s: %s", applet_name, msg);
148 /* We set environment *before* vfork (because we want to use vfork),
149 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
150 * Using putenv(), and freeing memory after unsetenv() won't leak */
151 static void safe_setenv(char **pvar_val, const char *var, const char *val)
153 char *var_val = *pvar_val;
156 bb_unsetenv_and_free(var_val);
158 *pvar_val = xasprintf("%s=%s", var, val);
163 static void SetEnv(struct passwd *pas)
166 safe_setenv(&G.env_var_user, "USER", pas->pw_name);
167 safe_setenv(&G.env_var_home, "HOME", pas->pw_dir);
168 /* if we want to set user's shell instead: */
169 /*safe_setenv(G.env_var_shell, "SHELL", pas->pw_shell);*/
171 xsetenv("USER", pas->pw_name);
172 xsetenv("HOME", pas->pw_dir);
174 /* currently, we use constant one: */
175 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
178 static void ChangeUser(struct passwd *pas)
180 /* careful: we're after vfork! */
181 change_identity(pas); /* - initgroups, setgid, setuid */
182 if (chdir(pas->pw_dir) < 0) {
183 crondlog(WARN9 "chdir(%s)", pas->pw_dir);
184 if (chdir(TMPDIR) < 0) {
185 crondlog(DIE9 "chdir(%s)", TMPDIR); /* exits */
190 static const char DowAry[] ALIGN1 =
191 "sun""mon""tue""wed""thu""fri""sat"
192 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
195 static const char MonAry[] ALIGN1 =
196 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
197 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
200 static void ParseField(char *user, char *ary, int modvalue, int off,
201 const char *names, char *ptr)
202 /* 'names' is a pointer to a set of 3-char abbreviations */
208 // this can't happen due to config_read()
215 /* Handle numeric digit or symbol or '*' */
217 n1 = 0; /* everything will be filled */
221 } else if (isdigit(*ptr)) {
224 n1 = strtol(ptr, &endp, 10) + off;
226 n2 = strtol(ptr, &endp, 10) + off;
228 ptr = endp; /* gcc likes temp var for &endp */
233 for (i = 0; names[i]; i += 3) {
234 /* was using strncmp before... */
235 if (strncasecmp(ptr, &names[i], 3) == 0) {
248 /* handle optional range '-' */
252 if (*ptr == '-' && n2 < 0) {
258 * collapse single-value ranges, handle skipmark, and fill
259 * in the character array appropriately.
266 skip = strtol(ptr + 1, &endp, 10);
267 ptr = endp; /* gcc likes temp var for &endp */
271 * fill array, using a failsafe is the easiest way to prevent
280 n1 = (n1 + 1) % modvalue;
283 ary[n1 % modvalue] = 1;
286 if (--failsafe == 0) {
302 crondlog(WARN9 "user %s: parse error at %s", user, base);
306 if (DebugOpt && (G.LogLevel <= 5)) { /* like LVL5 */
307 /* can't use crondlog, it inserts '\n' */
309 for (i = 0; i < modvalue; ++i)
310 fprintf(stderr, "%d", (unsigned char)ary[i]);
311 bb_putchar_stderr('\n');
315 static void FixDayDow(CronLine *line)
321 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
322 if (line->cl_Dow[i] == 0) {
327 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
328 if (line->cl_Days[i] == 0) {
333 if (weekUsed != daysUsed) {
335 memset(line->cl_Days, 0, sizeof(line->cl_Days));
337 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
342 * DeleteFile() - delete user database
344 * Note: multiple entries for same user may exist if we were unable to
345 * completely delete a database due to running processes.
347 static void DeleteFile(const char *userName)
349 CronFile **pfile = &G.FileBase;
352 while ((file = *pfile) != NULL) {
353 if (strcmp(userName, file->cf_User) == 0) {
354 CronLine **pline = &file->cf_LineBase;
357 file->cf_Running = 0;
358 file->cf_Deleted = 1;
360 while ((line = *pline) != NULL) {
361 if (line->cl_Pid > 0) {
362 file->cf_Running = 1;
363 pline = &line->cl_Next;
365 *pline = line->cl_Next;
366 free(line->cl_Shell);
370 if (file->cf_Running == 0) {
371 *pfile = file->cf_Next;
375 pfile = &file->cf_Next;
378 pfile = &file->cf_Next;
383 static void SynchronizeFile(const char *fileName)
385 struct parser_t *parser;
389 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
396 DeleteFile(fileName);
397 parser = config_open(fileName);
401 maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
403 if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
404 CronFile *file = xzalloc(sizeof(CronFile));
408 file->cf_User = xstrdup(fileName);
409 pline = &file->cf_LineBase;
416 n = config_read(parser, tokens, 6, 1, "# \t", PARSE_NORMAL | PARSE_KEEP_COPY);
421 crondlog(LVL5 "user:%s entry:%s", fileName, parser->data);
423 /* check if line is setting MAILTO= */
424 if (0 == strncmp(tokens[0], "MAILTO=", 7)) {
425 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
427 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
428 #endif /* otherwise just ignore such lines */
431 /* check if a minimum of tokens is specified */
434 *pline = line = xzalloc(sizeof(*line));
435 /* parse date ranges */
436 ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, tokens[0]);
437 ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, tokens[1]);
438 ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, tokens[2]);
439 ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, tokens[3]);
440 ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, tokens[4]);
442 * fix days and dow - if one is not "*" and the other
443 * is "*", the other is set to 0, and vise-versa
446 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
447 /* copy mailto (can be NULL) */
448 line->cl_MailTo = xstrdup(mailTo);
451 line->cl_Shell = xstrdup(tokens[5]);
453 crondlog(LVL5 " command:%s", tokens[5]);
455 pline = &line->cl_Next;
456 //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]);
460 file->cf_Next = G.FileBase;
464 crondlog(WARN9 "user %s: too many lines", fileName);
467 config_close(parser);
470 static void CheckUpdates(void)
475 fi = fopen_for_read(CRONUPDATE);
478 while (fgets(buf, sizeof(buf), fi) != NULL) {
479 /* use first word only */
480 SynchronizeFile(strtok(buf, " \t\r\n"));
486 static void SynchronizeDir(void)
489 /* Attempt to delete the database. */
491 for (file = G.FileBase; file; file = file->cf_Next) {
492 if (!file->cf_Deleted) {
493 DeleteFile(file->cf_User);
499 * Remove cron update file
501 * Re-chdir, in case directory was renamed & deleted, or otherwise
504 * scan directory and add associated users
507 if (chdir(G.CDir) < 0) {
508 crondlog(DIE9 "chdir(%s)", G.CDir);
511 DIR *dir = opendir(".");
515 crondlog(DIE9 "chdir(%s)", "."); /* exits */
516 while ((den = readdir(dir)) != NULL) {
517 if (strchr(den->d_name, '.') != NULL) {
520 if (getpwnam(den->d_name)) {
521 SynchronizeFile(den->d_name);
523 crondlog(LVL7 "ignoring %s", den->d_name);
531 * Determine which jobs need to be run. Under normal conditions, the
532 * period is about a minute (one scan). Worst case it will be one
535 static void TestJobs(time_t t1, time_t t2)
539 /* Find jobs > t1 and <= t2 */
541 for (t = t1 - t1 % 60; t <= t2; t += 60) {
550 for (file = G.FileBase; file; file = file->cf_Next) {
552 crondlog(LVL5 "file %s:", file->cf_User);
553 if (file->cf_Deleted)
555 for (line = file->cf_LineBase; line; line = line->cl_Next) {
557 crondlog(LVL5 " line %s", line->cl_Shell);
558 if (line->cl_Mins[ptm->tm_min] && line->cl_Hrs[ptm->tm_hour]
559 && (line->cl_Days[ptm->tm_mday] || line->cl_Dow[ptm->tm_wday])
560 && line->cl_Mons[ptm->tm_mon]
563 crondlog(LVL5 " job: %d %s",
564 (int)line->cl_Pid, line->cl_Shell);
566 if (line->cl_Pid > 0) {
567 crondlog(LVL8 "user %s: process already running: %s",
568 file->cf_User, line->cl_Shell);
569 } else if (line->cl_Pid == 0) {
579 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
581 ForkJob(const char *user, CronLine *line, int mailFd,
582 const char *prog, const char *cmd, const char *arg,
583 const char *mail_filename);
585 * EndJob - called when job terminates and when mail terminates
587 static void EndJob(const char *user, CronLine *line)
594 if (line->cl_Pid <= 0) {
600 * End of job and no mail file
601 * End of sendmail job
603 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, line->cl_Pid);
606 if (line->cl_MailFlag == 0) {
609 line->cl_MailFlag = 0;
612 * End of primary job - check for mail file. If size has increased and
613 * the file is still valid, we sendmail it.
615 mailFd = open(mailFile, O_RDONLY);
621 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
622 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
623 || !S_ISREG(sbuf.st_mode)
629 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
632 # define EndJob(user, line) ((line)->cl_Pid = 0)
636 * Check for job completion, return number of jobs still running after
639 static int CheckJobs(void)
643 int nStillRunning = 0;
645 for (file = G.FileBase; file; file = file->cf_Next) {
646 if (file->cf_Running) {
647 file->cf_Running = 0;
649 for (line = file->cf_LineBase; line; line = line->cl_Next) {
651 if (line->cl_Pid <= 0)
654 r = waitpid(line->cl_Pid, &status, WNOHANG);
655 if (r < 0 || r == line->cl_Pid) {
656 EndJob(file->cf_User, line);
658 file->cf_Running = 1;
661 file->cf_Running = 1;
665 nStillRunning += file->cf_Running;
667 return nStillRunning;
670 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
672 // TODO: sendmail should be _run-time_ option, not compile-time!
675 ForkJob(const char *user, CronLine *line, int mailFd,
676 const char *prog, const char *cmd, const char *arg,
677 const char *mail_filename)
682 /* prepare things before vfork */
683 pas = getpwnam(user);
685 crondlog(WARN9 "can't get uid for %s", user);
693 /* change running state to the user in question */
696 crondlog(LVL5 "child running %s", prog);
699 xmove_fd(mailFd, mail_filename ? 1 : 0);
702 /* crond 3.0pl1-100 puts tasks in separate process groups */
704 execlp(prog, prog, cmd, arg, (char *) NULL);
705 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user, prog, cmd, arg);
707 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
715 crondlog(ERR20 "can't vfork");
719 unlink(mail_filename);
722 /* PARENT, FORK SUCCESS */
724 /* rename mail-file based on pid of process */
725 char *mailFile2 = xasprintf("%s/cron.%s.%d", TMPDIR, user, (int)pid);
726 rename(mail_filename, mailFile2); // TODO: xrename?
732 * Close the mail file descriptor.. we can't just leave it open in
733 * a structure, closing it later, because we might run out of descriptors
740 static void RunJob(const char *user, CronLine *line)
746 line->cl_MailFlag = 0;
748 if (line->cl_MailTo) {
749 /* open mail file - owner root so nobody can screw with it. */
750 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
751 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
754 line->cl_MailFlag = 1;
755 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_MailTo,
757 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
759 crondlog(ERR20 "can't create mail file %s for user %s, "
760 "discarding output", mailFile, user);
764 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
767 #else /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
769 static void RunJob(const char *user, CronLine *line)
774 /* prepare things before vfork */
775 pas = getpwnam(user);
777 crondlog(WARN9 "can't get uid for %s", user);
782 /* fork as the user in question and run program */
786 /* change running state to the user in question */
789 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
791 /* crond 3.0pl1-100 puts tasks in separate process groups */
793 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, (char *) NULL);
794 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
795 DEFAULT_SHELL, "-c", line->cl_Shell);
800 crondlog(ERR20 "can't vfork");
807 #endif /* !ENABLE_FEATURE_CROND_CALL_SENDMAIL */
809 static void RunJobs(void)
814 for (file = G.FileBase; file; file = file->cf_Next) {
819 for (line = file->cf_LineBase; line; line = line->cl_Next) {
820 if (line->cl_Pid >= 0)
823 RunJob(file->cf_User, line);
824 crondlog(LVL8 "USER %s pid %3d cmd %s",
825 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
826 if (line->cl_Pid < 0) {
828 } else if (line->cl_Pid > 0) {
829 file->cf_Running = 1;
835 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
836 int crond_main(int argc UNUSED_PARAM, char **argv)
845 /* "-b after -f is ignored", and so on for every pair a-b */
846 opt_complementary = "f-b:b-f:S-L:L-S" IF_FEATURE_CROND_D(":d-l")
847 ":l+:d+"; /* -l and -d have numeric param */
848 opts = getopt32(argv, "l:L:fbSc:" IF_FEATURE_CROND_D("d:"),
849 &G.LogLevel, &G.LogFile, &G.CDir
850 IF_FEATURE_CROND_D(,&G.LogLevel));
851 /* both -d N and -l N set the same variable: G.LogLevel */
853 if (!(opts & OPT_f)) {
854 /* close stdin, stdout, stderr.
855 * close unused descriptors - don't need them. */
856 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
859 if (!(opts & OPT_d) && G.LogFile == NULL) {
860 /* logging to syslog */
861 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
862 logmode = LOGMODE_SYSLOG;
866 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
867 xsetenv("SHELL", DEFAULT_SHELL); /* once, for all future children */
868 crondlog(LVL8 "crond (busybox "BB_VER") started, log level %d", G.LogLevel);
870 write_pidfile("/var/run/crond.pid");
883 /* Synchronize to 1 minute, minimum 1 second */
884 sleep(sleep_time - (time(NULL) % sleep_time) + 1);
887 dt = (long)t2 - (long)t1;
890 * The file 'cron.update' is checked to determine new cron
891 * jobs. The directory is rescanned once an hour to deal
894 * Check for time jump. Disparities over an hour either way
895 * result in resynchronization. A negative disparity
896 * less than an hour causes us to effectively sleep until we
897 * match the original time (i.e. no re-execution of jobs that
898 * have just been run). A positive disparity less than
899 * an hour causes intermediate jobs to be run, but only once
902 * When running jobs, the inequality used is greater but not
903 * equal to t1, and less then or equal to t2.
905 if (stat(G.CDir, &sbuf) == 0 && G.CDir_mtime != sbuf.st_mtime) {
906 G.CDir_mtime = sbuf.st_mtime;
915 crondlog(LVL5 "wakeup dt=%ld", dt);
916 if (dt < -60 * 60 || dt > 60 * 60) {
917 crondlog(WARN9 "time disparity of %ld minutes detected", dt / 60);
918 /* and we do not run any jobs in this case */
920 /* Usual case: time advances forward, as expected */
923 if (CheckJobs() > 0) {
929 /* else: time jumped back, do not run any jobs */
932 return 0; /* not reached */