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 smallint cl_MailFlag; /* running pid is for mail */
58 char *cl_MailTo; /* whom to mail results */
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; */
91 const char *CDir; /* = CRONTABS; */
98 #define G (*(struct globals*)&bb_common_bufsiz1)
99 #define LogLevel (G.LogLevel )
100 #define LogFile (G.LogFile )
101 #define CDir (G.CDir )
102 #define FileBase (G.FileBase )
103 #define env_var_user (G.env_var_user )
104 #define env_var_home (G.env_var_home )
105 #define INIT_G() do { \
111 static void CheckUpdates(void);
112 static void SynchronizeDir(void);
113 static int TestJobs(time_t t1, time_t t2);
114 static void RunJobs(void);
115 static int CheckJobs(void);
116 static void RunJob(const char *user, CronLine *line);
117 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
118 static void EndJob(const char *user, CronLine *line);
120 #define EndJob(user, line) ((line)->cl_Pid = 0)
122 static void DeleteFile(const char *userName);
125 /* 0 is the most verbose, default 8 */
131 /* level >= 20 is "error" */
134 static void crondlog(const char *ctl, ...) __attribute__ ((format (printf, 1, 2)));
135 static void crondlog(const char *ctl, ...)
138 int level = (ctl[0] & 0x1f);
141 if (level >= (int)LogLevel) {
142 /* Debug mode: all to (non-redirected) stderr, */
143 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
144 if (!DebugOpt && LogFile) {
145 /* Otherwise (log to file): we reopen log file at every write: */
146 int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0666);
148 xmove_fd(logfd, STDERR_FILENO);
150 /* When we log to syslog, level > 8 is logged at LOG_ERR
151 * syslog level, level <= 8 is logged at LOG_INFO. */
153 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
156 vasprintf(&msg, ctl + 1, va);
157 bb_info_msg("%s: %s", applet_name, msg);
166 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
167 int crond_main(int argc UNUSED_PARAM, char **argv)
173 /* "-b after -f is ignored", and so on for every pair a-b */
174 opt_complementary = "f-b:b-f:S-L:L-S" IF_FEATURE_CROND_D(":d-l")
175 ":l+:d+"; /* -l and -d have numeric param */
176 opts = getopt32(argv, "l:L:fbSc:" IF_FEATURE_CROND_D("d:"),
177 &LogLevel, &LogFile, &CDir
178 IF_FEATURE_CROND_D(,&LogLevel));
179 /* both -d N and -l N set the same variable: LogLevel */
181 if (!(opts & OPT_f)) {
182 /* close stdin, stdout, stderr.
183 * close unused descriptors - don't need them. */
184 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
187 if (!(opts & OPT_d) && LogFile == NULL) {
188 /* logging to syslog */
189 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
190 logmode = LOGMODE_SYSLOG;
194 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
195 xsetenv("SHELL", DEFAULT_SHELL); /* once, for all future children */
196 crondlog(LVL8 "crond (busybox "BB_VER") started, log level %d", LogLevel);
199 /* main loop - synchronize to 1 second after the minute, minimum sleep
202 time_t t1 = time(NULL);
206 write_pidfile("/var/run/crond.pid");
211 sleep((sleep_time + 1) - (time(NULL) % sleep_time));
214 dt = (long)t2 - (long)t1;
217 * The file 'cron.update' is checked to determine new cron
218 * jobs. The directory is rescanned once an hour to deal
221 * check for disparity. Disparities over an hour either way
222 * result in resynchronization. A reverse-indexed disparity
223 * less then an hour causes us to effectively sleep until we
224 * match the original time (i.e. no re-execution of jobs that
225 * have just been run). A forward-indexed disparity less then
226 * an hour causes intermediate jobs to be run, but only once
229 * when running jobs, the inequality used is greater but not
230 * equal to t1, and less then or equal to t2.
238 crondlog(LVL5 "wakeup dt=%ld", dt);
239 if (dt < -60 * 60 || dt > 60 * 60) {
240 crondlog(WARN9 "time disparity of %ld minutes detected", dt / 60);
245 if (CheckJobs() > 0) {
255 return 0; /* not reached */
259 /* We set environment *before* vfork (because we want to use vfork),
260 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
261 * Using putenv(), and freeing memory after unsetenv() won't leak */
262 static void safe_setenv(char **pvar_val, const char *var, const char *val)
264 char *var_val = *pvar_val;
267 bb_unsetenv(var_val);
270 *pvar_val = xasprintf("%s=%s", var, val);
275 static void SetEnv(struct passwd *pas)
278 safe_setenv(&env_var_user, "USER", pas->pw_name);
279 safe_setenv(&env_var_home, "HOME", pas->pw_dir);
280 /* if we want to set user's shell instead: */
281 /*safe_setenv(env_var_user, "SHELL", pas->pw_shell);*/
283 xsetenv("USER", pas->pw_name);
284 xsetenv("HOME", pas->pw_dir);
286 /* currently, we use constant one: */
287 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
290 static void ChangeUser(struct passwd *pas)
292 /* careful: we're after vfork! */
293 change_identity(pas); /* - initgroups, setgid, setuid */
294 if (chdir(pas->pw_dir) < 0) {
295 crondlog(WARN9 "chdir(%s)", pas->pw_dir);
296 if (chdir(TMPDIR) < 0) {
297 crondlog(DIE9 "chdir(%s)", TMPDIR); /* exits */
302 static const char DowAry[] ALIGN1 =
303 "sun""mon""tue""wed""thu""fri""sat"
304 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
307 static const char MonAry[] ALIGN1 =
308 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
309 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
312 static void ParseField(char *user, char *ary, int modvalue, int off,
313 const char *names, char *ptr)
314 /* 'names' is a pointer to a set of 3-char abbreviations */
320 // this can't happen due to config_read()
327 /* Handle numeric digit or symbol or '*' */
329 n1 = 0; /* everything will be filled */
333 } else if (isdigit(*ptr)) {
336 n1 = strtol(ptr, &endp, 10) + off;
338 n2 = strtol(ptr, &endp, 10) + off;
340 ptr = endp; /* gcc likes temp var for &endp */
345 for (i = 0; names[i]; i += 3) {
346 /* was using strncmp before... */
347 if (strncasecmp(ptr, &names[i], 3) == 0) {
360 /* handle optional range '-' */
364 if (*ptr == '-' && n2 < 0) {
370 * collapse single-value ranges, handle skipmark, and fill
371 * in the character array appropriately.
378 skip = strtol(ptr + 1, &endp, 10);
379 ptr = endp; /* gcc likes temp var for &endp */
383 * fill array, using a failsafe is the easiest way to prevent
392 n1 = (n1 + 1) % modvalue;
395 ary[n1 % modvalue] = 1;
398 if (--failsafe == 0) {
414 crondlog(WARN9 "user %s: parse error at %s", user, base);
418 if (DebugOpt && (LogLevel <= 5)) { /* like LVL5 */
419 /* can't use crondlog, it inserts '\n' */
421 for (i = 0; i < modvalue; ++i)
422 fprintf(stderr, "%d", (unsigned char)ary[i]);
423 bb_putchar_stderr('\n');
427 static void FixDayDow(CronLine *line)
433 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
434 if (line->cl_Dow[i] == 0) {
439 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
440 if (line->cl_Days[i] == 0) {
445 if (weekUsed != daysUsed) {
447 memset(line->cl_Days, 0, sizeof(line->cl_Days));
449 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
453 static void SynchronizeFile(const char *fileName)
455 struct parser_t *parser;
459 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
466 DeleteFile(fileName);
467 parser = config_open(fileName);
471 maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
473 if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
474 CronFile *file = xzalloc(sizeof(CronFile));
478 file->cf_User = xstrdup(fileName);
479 pline = &file->cf_LineBase;
486 n = config_read(parser, tokens, 6, 1, "# \t", PARSE_NORMAL | PARSE_KEEP_COPY);
491 crondlog(LVL5 "user:%s entry:%s", fileName, parser->data);
493 /* check if line is setting MAILTO= */
494 if (0 == strncmp(tokens[0], "MAILTO=", 7)) {
495 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
497 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
498 #endif /* otherwise just ignore such lines */
501 /* check if a minimum of tokens is specified */
504 *pline = line = xzalloc(sizeof(*line));
505 /* parse date ranges */
506 ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, tokens[0]);
507 ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, tokens[1]);
508 ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, tokens[2]);
509 ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, tokens[3]);
510 ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, tokens[4]);
512 * fix days and dow - if one is not "*" and the other
513 * is "*", the other is set to 0, and vise-versa
516 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
517 /* copy mailto (can be NULL) */
518 line->cl_MailTo = xstrdup(mailTo);
521 line->cl_Shell = xstrdup(tokens[5]);
523 crondlog(LVL5 " command:%s", tokens[5]);
525 pline = &line->cl_Next;
526 //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]);
530 file->cf_Next = FileBase;
534 crondlog(WARN9 "user %s: too many lines", fileName);
537 config_close(parser);
540 static void CheckUpdates(void)
545 fi = fopen_for_read(CRONUPDATE);
548 while (fgets(buf, sizeof(buf), fi) != NULL) {
549 /* use first word only */
550 SynchronizeFile(strtok(buf, " \t\r\n"));
556 static void SynchronizeDir(void)
559 /* Attempt to delete the database. */
561 for (file = FileBase; file; file = file->cf_Next) {
562 if (!file->cf_Deleted) {
563 DeleteFile(file->cf_User);
569 * Remove cron update file
571 * Re-chdir, in case directory was renamed & deleted, or otherwise
574 * scan directory and add associated users
577 if (chdir(CDir) < 0) {
578 crondlog(DIE9 "chdir(%s)", CDir);
581 DIR *dir = opendir(".");
585 crondlog(DIE9 "chdir(%s)", "."); /* exits */
586 while ((den = readdir(dir)) != NULL) {
587 if (strchr(den->d_name, '.') != NULL) {
590 if (getpwnam(den->d_name)) {
591 SynchronizeFile(den->d_name);
593 crondlog(LVL7 "ignoring %s", den->d_name);
601 * DeleteFile() - delete user database
603 * Note: multiple entries for same user may exist if we were unable to
604 * completely delete a database due to running processes.
606 static void DeleteFile(const char *userName)
608 CronFile **pfile = &FileBase;
611 while ((file = *pfile) != NULL) {
612 if (strcmp(userName, file->cf_User) == 0) {
613 CronLine **pline = &file->cf_LineBase;
616 file->cf_Running = 0;
617 file->cf_Deleted = 1;
619 while ((line = *pline) != NULL) {
620 if (line->cl_Pid > 0) {
621 file->cf_Running = 1;
622 pline = &line->cl_Next;
624 *pline = line->cl_Next;
625 free(line->cl_Shell);
629 if (file->cf_Running == 0) {
630 *pfile = file->cf_Next;
634 pfile = &file->cf_Next;
637 pfile = &file->cf_Next;
645 * determine which jobs need to be run. Under normal conditions, the
646 * period is about a minute (one scan). Worst case it will be one
649 static int TestJobs(time_t t1, time_t t2)
654 /* Find jobs > t1 and <= t2 */
656 for (t = t1 - t1 % 60; t <= t2; t += 60) {
665 for (file = FileBase; file; file = file->cf_Next) {
667 crondlog(LVL5 "file %s:", file->cf_User);
668 if (file->cf_Deleted)
670 for (line = file->cf_LineBase; line; line = line->cl_Next) {
672 crondlog(LVL5 " line %s", line->cl_Shell);
673 if (line->cl_Mins[ptm->tm_min] && line->cl_Hrs[ptm->tm_hour]
674 && (line->cl_Days[ptm->tm_mday] || line->cl_Dow[ptm->tm_wday])
675 && line->cl_Mons[ptm->tm_mon]
678 crondlog(LVL5 " job: %d %s",
679 (int)line->cl_Pid, line->cl_Shell);
681 if (line->cl_Pid > 0) {
682 crondlog(LVL8 "user %s: process already running: %s",
683 file->cf_User, line->cl_Shell);
684 } else if (line->cl_Pid == 0) {
696 static void RunJobs(void)
701 for (file = FileBase; file; file = file->cf_Next) {
706 for (line = file->cf_LineBase; line; line = line->cl_Next) {
707 if (line->cl_Pid >= 0)
710 RunJob(file->cf_User, line);
711 crondlog(LVL8 "USER %s pid %3d cmd %s",
712 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
713 if (line->cl_Pid < 0) {
715 } else if (line->cl_Pid > 0) {
716 file->cf_Running = 1;
723 * CheckJobs() - check for job completion
725 * Check for job completion, return number of jobs still running after
728 static int CheckJobs(void)
732 int nStillRunning = 0;
734 for (file = FileBase; file; file = file->cf_Next) {
735 if (file->cf_Running) {
736 file->cf_Running = 0;
738 for (line = file->cf_LineBase; line; line = line->cl_Next) {
740 if (line->cl_Pid <= 0)
743 r = waitpid(line->cl_Pid, &status, WNOHANG);
744 if (r < 0 || r == line->cl_Pid) {
745 EndJob(file->cf_User, line);
747 file->cf_Running = 1;
750 file->cf_Running = 1;
754 nStillRunning += file->cf_Running;
756 return nStillRunning;
759 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
761 // TODO: sendmail should be _run-time_ option, not compile-time!
764 ForkJob(const char *user, CronLine *line, int mailFd,
765 const char *prog, const char *cmd, const char *arg,
766 const char *mail_filename)
771 /* prepare things before vfork */
772 pas = getpwnam(user);
774 crondlog(WARN9 "can't get uid for %s", user);
782 /* change running state to the user in question */
785 crondlog(LVL5 "child running %s", prog);
788 xmove_fd(mailFd, mail_filename ? 1 : 0);
791 /* crond 3.0pl1-100 puts tasks in separate process groups */
793 execlp(prog, prog, cmd, arg, (char *) NULL);
794 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user, prog, cmd, arg);
796 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
804 crondlog(ERR20 "can't vfork");
808 unlink(mail_filename);
810 } else if (mail_filename) {
811 /* PARENT, FORK SUCCESS
812 * rename mail-file based on pid of process
816 snprintf(mailFile2, sizeof(mailFile2), "%s/cron.%s.%d", TMPDIR, user, pid);
817 rename(mail_filename, mailFile2); // TODO: xrename?
821 * Close the mail file descriptor.. we can't just leave it open in
822 * a structure, closing it later, because we might run out of descriptors
829 static void RunJob(const char *user, CronLine *line)
835 line->cl_MailFlag = 0;
837 if (line->cl_MailTo) {
838 /* open mail file - owner root so nobody can screw with it. */
839 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
840 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
843 line->cl_MailFlag = 1;
844 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_MailTo,
846 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
848 crondlog(ERR20 "can't create mail file %s for user %s, "
849 "discarding output", mailFile, user);
853 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
857 * EndJob - called when job terminates and when mail terminates
859 static void EndJob(const char *user, CronLine *line)
866 if (line->cl_Pid <= 0) {
872 * End of job and no mail file
873 * End of sendmail job
875 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, line->cl_Pid);
878 if (line->cl_MailFlag == 0) {
881 line->cl_MailFlag = 0;
884 * End of primary job - check for mail file. If size has increased and
885 * the file is still valid, we sendmail it.
887 mailFd = open(mailFile, O_RDONLY);
893 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
894 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
895 || !S_ISREG(sbuf.st_mode)
901 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
904 #else /* crond without sendmail */
906 static void RunJob(const char *user, CronLine *line)
911 /* prepare things before vfork */
912 pas = getpwnam(user);
914 crondlog(WARN9 "can't get uid for %s", user);
919 /* fork as the user in question and run program */
923 /* change running state to the user in question */
926 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
928 /* crond 3.0pl1-100 puts tasks in separate process groups */
930 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, (char *) NULL);
931 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
932 DEFAULT_SHELL, "-c", line->cl_Shell);
937 crondlog(ERR20 "can't vfork");
944 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */