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
27 #define CRONTABS "/var/spool/cron/crontabs"
30 #define TMPDIR "/var/spool/cron"
33 #define SENDMAIL "sendmail"
37 # define SENDMAIL_ARGS "localhost", line->cl_MailTo
39 # define SENDMAIL_ARGS "-ti", "oem"
43 #define CRONUPDATE "cron.update"
46 #define MAXLINES 256 /* max lines in non-root crontabs */
50 typedef struct CronFile {
51 struct CronFile *cf_Next;
52 struct CronLine *cf_LineBase;
53 char *cf_User; /* username */
54 smallint cf_Ready; /* bool: one or more jobs ready */
55 smallint cf_Running; /* bool: one or more jobs running */
56 smallint cf_Deleted; /* marked for deletion, ignore */
59 typedef struct CronLine {
60 struct CronLine *cl_Next;
61 char *cl_Shell; /* shell command */
62 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
63 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
64 int cl_MailPos; /* 'empty file' size */
65 smallint cl_MailFlag; /* running pid is for mail */
66 char *cl_MailTo; /* whom to mail results */
68 /* ordered by size, not in natural order. makes code smaller: */
69 char cl_Dow[7]; /* 0-6, beginning sunday */
70 char cl_Mons[12]; /* 0-11 */
71 char cl_Hrs[24]; /* 0-23 */
72 char cl_Days[32]; /* 1-31 */
73 char cl_Mins[60]; /* 0-59 */
87 OPT_d = (1 << 6) * ENABLE_DEBUG_CROND_OPTION,
89 #if ENABLE_DEBUG_CROND_OPTION
90 #define DebugOpt (option_mask32 & OPT_d)
97 unsigned LogLevel; /* = 8; */
99 const char *CDir; /* = CRONTABS; */
106 #define G (*(struct globals*)&bb_common_bufsiz1)
107 #define LogLevel (G.LogLevel )
108 #define LogFile (G.LogFile )
109 #define CDir (G.CDir )
110 #define FileBase (G.FileBase )
111 #define env_var_user (G.env_var_user )
112 #define env_var_home (G.env_var_home )
113 #define INIT_G() do { \
119 static void CheckUpdates(void);
120 static void SynchronizeDir(void);
121 static int TestJobs(time_t t1, time_t t2);
122 static void RunJobs(void);
123 static int CheckJobs(void);
124 static void RunJob(const char *user, CronLine *line);
125 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
126 static void EndJob(const char *user, CronLine *line);
128 #define EndJob(user, line) ((line)->cl_Pid = 0)
130 static void DeleteFile(const char *userName);
139 /* level >= 20 is "error" */
142 static void crondlog(const char *ctl, ...)
145 int level = (ctl[0] & 0x1f);
148 if (level >= (int)LogLevel) {
149 /* Debug mode: all to (non-redirected) stderr, */
150 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
151 if (!DebugOpt && LogFile) {
152 /* Otherwise (log to file): we reopen log file at every write: */
153 int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
155 xmove_fd(logfd, STDERR_FILENO);
157 // TODO: ERR -> error, WARN -> warning, LVL -> info
158 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
165 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
166 int crond_main(int argc ATTRIBUTE_UNUSED, char **argv)
172 /* "-b after -f is ignored", and so on for every pair a-b */
173 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l")
174 ":l+:d+"; /* -l and -d have numeric param */
175 opt = getopt32(argv, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
176 &LogLevel, &LogFile, &CDir
177 USE_DEBUG_CROND_OPTION(,&LogLevel));
178 /* both -d N and -l N set the same variable: LogLevel */
180 if (!(opt & OPT_f)) {
181 /* close stdin, stdout, stderr.
182 * close unused descriptors - don't need them. */
183 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
186 if (!DebugOpt && LogFile == NULL) {
187 /* logging to syslog */
188 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
189 logmode = LOGMODE_SYSLOG;
193 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
194 setenv("SHELL", DEFAULT_SHELL, 1); /* once, for all future children */
195 crondlog(LVL9 "crond (busybox "BB_VER") started, log level %d", LogLevel);
198 /* main loop - synchronize to 1 second after the minute, minimum sleep
201 time_t t1 = time(NULL);
207 write_pidfile("/var/run/crond.pid");
209 sleep((sleep_time + 1) - (time(NULL) % sleep_time));
212 dt = (long)t2 - (long)t1;
215 * The file 'cron.update' is checked to determine new cron
216 * jobs. The directory is rescanned once an hour to deal
219 * check for disparity. Disparities over an hour either way
220 * result in resynchronization. A reverse-indexed disparity
221 * less then an hour causes us to effectively sleep until we
222 * match the original time (i.e. no re-execution of jobs that
223 * have just been run). A forward-indexed disparity less then
224 * an hour causes intermediate jobs to be run, but only once
227 * when running jobs, the inequality used is greater but not
228 * equal to t1, and less then or equal to t2.
236 crondlog(LVL5 "wakeup dt=%ld", dt);
237 if (dt < -60 * 60 || dt > 60 * 60) {
238 crondlog(WARN9 "time disparity of %d minutes detected", dt / 60);
243 if (CheckJobs() > 0) {
252 return 0; /* not reached */
256 /* We set environment *before* vfork (because we want to use vfork),
257 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
258 * Using putenv(), and freeing memory after unsetenv() won't leak */
259 static void safe_setenv4(char **pvar_val, const char *var, const char *val /*, int len*/)
261 const int len = 4; /* both var names are 4 char long */
262 char *var_val = *pvar_val;
265 var_val[len] = '\0'; /* nuke '=' */
269 *pvar_val = xasprintf("%s=%s", var, val);
274 static void SetEnv(struct passwd *pas)
277 safe_setenv4(&env_var_user, "USER", pas->pw_name);
278 safe_setenv4(&env_var_home, "HOME", pas->pw_dir);
279 /* if we want to set user's shell instead: */
280 /*safe_setenv(env_var_user, "SHELL", pas->pw_shell, 5);*/
282 setenv("USER", pas->pw_name, 1);
283 setenv("HOME", pas->pw_dir, 1);
285 /* currently, we use constant one: */
286 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
289 static void ChangeUser(struct passwd *pas)
291 /* careful: we're after vfork! */
292 change_identity(pas); /* - initgroups, setgid, setuid */
293 if (chdir(pas->pw_dir) < 0) {
294 crondlog(LVL9 "can't chdir(%s)", pas->pw_dir);
295 if (chdir(TMPDIR) < 0) {
296 crondlog(DIE9 "can't chdir(%s)", TMPDIR); /* exits */
301 static const char DowAry[] ALIGN1 =
302 "sun""mon""tue""wed""thu""fri""sat"
303 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
306 static const char MonAry[] ALIGN1 =
307 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
308 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
311 static char *ParseField(char *user, char *ary, int modvalue, int off,
312 const char *names, char *ptr)
313 /* 'names' is a pointer to a set of 3-char abbreviations */
323 while (!isspace(*ptr)) {
326 /* Handle numeric digit or symbol or '*' */
328 n1 = 0; /* everything will be filled */
332 } else if (isdigit(*ptr)) {
334 n1 = strtol(ptr, &ptr, 10) + off;
336 n2 = strtol(ptr, &ptr, 10) + off;
342 for (i = 0; names[i]; i += 3) {
343 /* was using strncmp before... */
344 if (strncasecmp(ptr, &names[i], 3) == 0) {
357 /* handle optional range '-' */
359 crondlog(WARN9 "user %s: parse error at %s", user, base);
362 if (*ptr == '-' && n2 < 0) {
368 * collapse single-value ranges, handle skipmark, and fill
369 * in the character array appropriately.
375 skip = strtol(ptr + 1, &ptr, 10);
379 * fill array, using a failsafe is the easiest way to prevent
388 n1 = (n1 + 1) % modvalue;
391 ary[n1 % modvalue] = 1;
394 if (--failsafe == 0) {
395 crondlog(WARN9 "user %s: parse error at %s", user, base);
409 if (!isspace(*ptr)) {
410 crondlog(WARN9 "user %s: parse error at %s", user, base);
414 if (DebugOpt && (LogLevel <= 5)) { /* like LVL5 */
415 /* can't use crondlog, it inserts '\n' */
417 for (i = 0; i < modvalue; ++i)
418 fprintf(stderr, "%d", (unsigned char)ary[i]);
421 return skip_whitespace(ptr);
424 static void FixDayDow(CronLine *line)
430 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
431 if (line->cl_Dow[i] == 0) {
436 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
437 if (line->cl_Days[i] == 0) {
442 if (weekUsed != daysUsed) {
444 memset(line->cl_Days, 0, sizeof(line->cl_Days));
446 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
450 static void SynchronizeFile(const char *fileName)
457 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
464 DeleteFile(fileName);
465 fi = fopen(fileName, "r");
469 maxEntries = MAXLINES;
470 if (strcmp(fileName, "root") == 0) {
473 maxLines = maxEntries * 10;
475 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
476 CronFile *file = xzalloc(sizeof(CronFile));
479 file->cf_User = xstrdup(fileName);
480 pline = &file->cf_LineBase;
482 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
487 if (buf[0] == '\0' || buf[0] == '#') {
490 if (--maxEntries == 0) {
494 crondlog(LVL5 "user:%s entry:%s", fileName, buf);
496 /* check if line is setting MAILTO= */
497 if (0 == strncmp("MAILTO=", buf, 7)) {
498 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
500 mailTo = (buf[7]) ? xstrdup(buf+7) : NULL;
501 #endif /* otherwise just ignore such lines */
504 *pline = line = xzalloc(sizeof(CronLine));
505 /* parse date ranges */
506 ptr = ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, buf);
507 ptr = ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, ptr);
508 ptr = ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, ptr);
509 ptr = ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, ptr);
510 ptr = ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, ptr);
517 * fix days and dow - if one is not "*" and the other
518 * is "*", the other is set to 0, and vise-versa
521 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
522 /* copy mailto (can be NULL) */
523 line->cl_MailTo = xstrdup(mailTo);
526 line->cl_Shell = xstrdup(ptr);
528 crondlog(LVL5 " command:%s", ptr);
530 pline = &line->cl_Next;
534 file->cf_Next = FileBase;
537 if (maxLines == 0 || maxEntries == 0) {
538 crondlog(WARN9 "user %s: too many lines", fileName);
544 static void CheckUpdates(void)
549 fi = fopen(CRONUPDATE, "r");
552 while (fgets(buf, sizeof(buf), fi) != NULL) {
553 /* use first word only */
554 SynchronizeFile(strtok(buf, " \t\r\n"));
560 static void SynchronizeDir(void)
563 /* Attempt to delete the database. */
565 for (file = FileBase; file; file = file->cf_Next) {
566 if (!file->cf_Deleted) {
567 DeleteFile(file->cf_User);
573 * Remove cron update file
575 * Re-chdir, in case directory was renamed & deleted, or otherwise
578 * scan directory and add associated users
581 if (chdir(CDir) < 0) {
582 crondlog(DIE9 "can't chdir(%s)", CDir);
585 DIR *dir = opendir(".");
589 crondlog(DIE9 "can't chdir(%s)", "."); /* exits */
590 while ((den = readdir(dir)) != NULL) {
591 if (strchr(den->d_name, '.') != NULL) {
594 if (getpwnam(den->d_name)) {
595 SynchronizeFile(den->d_name);
597 crondlog(LVL7 "ignoring %s", den->d_name);
605 * DeleteFile() - delete user database
607 * Note: multiple entries for same user may exist if we were unable to
608 * completely delete a database due to running processes.
610 static void DeleteFile(const char *userName)
612 CronFile **pfile = &FileBase;
615 while ((file = *pfile) != NULL) {
616 if (strcmp(userName, file->cf_User) == 0) {
617 CronLine **pline = &file->cf_LineBase;
620 file->cf_Running = 0;
621 file->cf_Deleted = 1;
623 while ((line = *pline) != NULL) {
624 if (line->cl_Pid > 0) {
625 file->cf_Running = 1;
626 pline = &line->cl_Next;
628 *pline = line->cl_Next;
629 free(line->cl_Shell);
633 if (file->cf_Running == 0) {
634 *pfile = file->cf_Next;
638 pfile = &file->cf_Next;
641 pfile = &file->cf_Next;
649 * determine which jobs need to be run. Under normal conditions, the
650 * period is about a minute (one scan). Worst case it will be one
653 static int TestJobs(time_t t1, time_t t2)
658 /* Find jobs > t1 and <= t2 */
660 for (t = t1 - t1 % 60; t <= t2; t += 60) {
669 for (file = FileBase; file; file = file->cf_Next) {
671 crondlog(LVL5 "file %s:", file->cf_User);
672 if (file->cf_Deleted)
674 for (line = file->cf_LineBase; line; line = line->cl_Next) {
676 crondlog(LVL5 " line %s", line->cl_Shell);
677 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour]
678 && (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
679 && line->cl_Mons[tp->tm_mon]
682 crondlog(LVL5 " job: %d %s",
683 (int)line->cl_Pid, line->cl_Shell);
685 if (line->cl_Pid > 0) {
686 crondlog(LVL8 "user %s: process already running: %s",
687 file->cf_User, line->cl_Shell);
688 } else if (line->cl_Pid == 0) {
700 static void RunJobs(void)
705 for (file = FileBase; file; file = file->cf_Next) {
710 for (line = file->cf_LineBase; line; line = line->cl_Next) {
711 if (line->cl_Pid >= 0)
714 RunJob(file->cf_User, line);
715 crondlog(LVL8 "USER %s pid %3d cmd %s",
716 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
717 if (line->cl_Pid < 0) {
719 } else if (line->cl_Pid > 0) {
720 file->cf_Running = 1;
727 * CheckJobs() - check for job completion
729 * Check for job completion, return number of jobs still running after
732 static int CheckJobs(void)
736 int nStillRunning = 0;
738 for (file = FileBase; file; file = file->cf_Next) {
739 if (file->cf_Running) {
740 file->cf_Running = 0;
742 for (line = file->cf_LineBase; line; line = line->cl_Next) {
744 if (line->cl_Pid <= 0)
747 r = waitpid(line->cl_Pid, &status, WNOHANG);
748 if (r < 0 || r == line->cl_Pid) {
749 EndJob(file->cf_User, line);
751 file->cf_Running = 1;
754 file->cf_Running = 1;
758 nStillRunning += file->cf_Running;
760 return nStillRunning;
763 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
765 // TODO: sendmail should be _run-time_ option, not compile-time!
768 ForkJob(const char *user, CronLine *line, int mailFd,
769 const char *prog, const char *cmd, const char *arg,
770 const char *mail_filename)
775 /* prepare things before vfork */
776 pas = getpwnam(user);
778 crondlog(LVL9 "can't get uid for %s", user);
786 /* change running state to the user in question */
789 crondlog(LVL5 "child running %s", prog);
792 xmove_fd(mailFd, mail_filename ? 1 : 0);
795 execl(prog, prog, cmd, arg, NULL);
796 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user, prog, cmd, arg);
798 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
806 crondlog(ERR20 "can't vfork");
810 unlink(mail_filename);
812 } else if (mail_filename) {
813 /* PARENT, FORK SUCCESS
814 * rename mail-file based on pid of process
818 snprintf(mailFile2, sizeof(mailFile2), "%s/cron.%s.%d", TMPDIR, user, pid);
819 rename(mail_filename, mailFile2); // TODO: xrename?
823 * Close the mail file descriptor.. we can't just leave it open in
824 * a structure, closing it later, because we might run out of descriptors
831 static void RunJob(const char *user, CronLine *line)
837 line->cl_MailFlag = 0;
839 if (line->cl_MailTo) {
840 /* open mail file - owner root so nobody can screw with it. */
841 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
842 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
845 line->cl_MailFlag = 1;
846 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
848 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
850 crondlog(ERR20 "cannot create mail file %s for user %s, "
851 "discarding output", mailFile, user);
855 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
859 * EndJob - called when job terminates and when mail terminates
861 static void EndJob(const char *user, CronLine *line)
868 if (line->cl_Pid <= 0) {
874 * End of job and no mail file
875 * End of sendmail job
877 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, line->cl_Pid);
880 if (line->cl_MailFlag == 0) {
883 line->cl_MailFlag = 0;
886 * End of primary job - check for mail file. If size has increased and
887 * the file is still valid, we sendmail it.
889 mailFd = open(mailFile, O_RDONLY);
895 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
896 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
897 || !S_ISREG(sbuf.st_mode)
903 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
906 #else /* crond without sendmail */
908 static void RunJob(const char *user, CronLine *line)
913 /* prepare things before vfork */
914 pas = getpwnam(user);
916 crondlog(LVL9 "can't get uid for %s", user);
921 /* fork as the user in question and run program */
925 /* change running state to the user in question */
928 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
930 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, 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 */