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"
36 #define SENDMAIL_ARGS "-ti", "oem"
39 #define CRONUPDATE "cron.update"
42 #define MAXLINES 256 /* max lines in non-root crontabs */
46 typedef struct CronFile {
47 struct CronFile *cf_Next;
48 struct CronLine *cf_LineBase;
49 char *cf_User; /* username */
50 smallint cf_Ready; /* bool: one or more jobs ready */
51 smallint cf_Running; /* bool: one or more jobs running */
52 smallint cf_Deleted; /* marked for deletion, ignore */
55 typedef struct CronLine {
56 struct CronLine *cl_Next;
57 char *cl_Shell; /* shell command */
58 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
59 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
60 int cl_MailPos; /* 'empty file' size */
61 smallint cl_MailFlag; /* running pid is for mail */
63 /* ordered by size, not in natural order. makes code smaller: */
64 char cl_Dow[7]; /* 0-6, beginning sunday */
65 char cl_Mons[12]; /* 0-11 */
66 char cl_Hrs[24]; /* 0-23 */
67 char cl_Days[32]; /* 1-31 */
68 char cl_Mins[60]; /* 0-59 */
82 OPT_d = (1 << 6) * ENABLE_DEBUG_CROND_OPTION,
84 #if ENABLE_DEBUG_CROND_OPTION
85 #define DebugOpt (option_mask32 & OPT_d)
92 unsigned LogLevel; /* = 8; */
94 const char *CDir; /* = CRONTABS; */
101 #define G (*(struct globals*)&bb_common_bufsiz1)
102 #define LogLevel (G.LogLevel )
103 #define LogFile (G.LogFile )
104 #define CDir (G.CDir )
105 #define FileBase (G.FileBase )
106 #define env_var_user (G.env_var_user )
107 #define env_var_home (G.env_var_home )
108 #define INIT_G() do { \
114 static void CheckUpdates(void);
115 static void SynchronizeDir(void);
116 static int TestJobs(time_t t1, time_t t2);
117 static void RunJobs(void);
118 static int CheckJobs(void);
119 static void RunJob(const char *user, CronLine *line);
120 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
121 static void EndJob(const char *user, CronLine *line);
123 #define EndJob(user, line) ((line)->cl_Pid = 0)
125 static void DeleteFile(const char *userName);
134 /* level >= 20 is "error" */
137 static void crondlog(const char *ctl, ...)
140 int level = (ctl[0] & 0x1f);
143 if (level >= LogLevel) {
144 /* Debug mode: all to (non-redirected) stderr, */
145 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
146 if (!DebugOpt && LogFile) {
147 /* Otherwise (log to file): we reopen log file at every write: */
148 int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
150 xmove_fd(logfd, STDERR_FILENO);
152 // TODO: ERR -> error, WARN -> warning, LVL -> info
153 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
160 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
161 int crond_main(int argc ATTRIBUTE_UNUSED, char **argv)
167 /* "-b after -f is ignored", and so on for every pair a-b */
168 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l")
169 ":l+:d+"; /* -l and -d have numeric param */
170 opt = getopt32(argv, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
171 &LogLevel, &LogFile, &CDir
172 USE_DEBUG_CROND_OPTION(,&LogLevel));
173 /* both -d N and -l N set the same variable: LogLevel */
175 if (!(opt & OPT_f)) {
176 /* close stdin, stdout, stderr.
177 * close unused descriptors - don't need them. */
178 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, av);
181 if (!DebugOpt && LogFile == NULL) {
182 /* logging to syslog */
183 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
184 logmode = LOGMODE_SYSLOG;
188 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
189 setenv("SHELL", DEFAULT_SHELL, 1); /* once, for all future children */
190 crondlog(LVL9 "crond (busybox "BB_VER") started, log level %d", LogLevel);
193 /* main loop - synchronize to 1 second after the minute, minimum sleep
196 time_t t1 = time(NULL);
202 write_pidfile("/var/run/crond.pid");
204 sleep((sleep_time + 1) - (time(NULL) % sleep_time));
207 dt = (long)t2 - (long)t1;
210 * The file 'cron.update' is checked to determine new cron
211 * jobs. The directory is rescanned once an hour to deal
214 * check for disparity. Disparities over an hour either way
215 * result in resynchronization. A reverse-indexed disparity
216 * less then an hour causes us to effectively sleep until we
217 * match the original time (i.e. no re-execution of jobs that
218 * have just been run). A forward-indexed disparity less then
219 * an hour causes intermediate jobs to be run, but only once
222 * when running jobs, the inequality used is greater but not
223 * equal to t1, and less then or equal to t2.
231 crondlog(LVL5 "wakeup dt=%ld", dt);
232 if (dt < -60 * 60 || dt > 60 * 60) {
233 crondlog(WARN9 "time disparity of %d minutes detected", dt / 60);
238 if (CheckJobs() > 0) {
247 return 0; /* not reached */
251 /* We set environment *before* vfork (because we want to use vfork),
252 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
253 * Using putenv(), and freeing memory after unsetenv() won't leak */
254 static void safe_setenv4(char **pvar_val, const char *var, const char *val /*, int len*/)
256 const int len = 4; /* both var names are 4 char long */
257 char *var_val = *pvar_val;
260 var_val[len] = '\0'; /* nuke '=' */
264 *pvar_val = xasprintf("%s=%s", var, val);
269 static void SetEnv(struct passwd *pas)
272 safe_setenv4(&env_var_user, "USER", pas->pw_name);
273 safe_setenv4(&env_var_home, "HOME", pas->pw_dir);
274 /* if we want to set user's shell instead: */
275 /*safe_setenv(env_var_user, "SHELL", pas->pw_shell, 5);*/
277 setenv("USER", pas->pw_name, 1);
278 setenv("HOME", pas->pw_dir, 1);
280 /* currently, we use constant one: */
281 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
284 static void ChangeUser(struct passwd *pas)
286 /* careful: we're after vfork! */
287 change_identity(pas); /* - initgroups, setgid, setuid */
288 if (chdir(pas->pw_dir) < 0) {
289 crondlog(LVL9 "can't chdir(%s)", pas->pw_dir);
290 if (chdir(TMPDIR) < 0) {
291 crondlog(DIE9 "can't chdir(%s)", TMPDIR); /* exits */
296 static const char DowAry[] ALIGN1 =
297 "sun""mon""tue""wed""thu""fri""sat"
298 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
301 static const char MonAry[] ALIGN1 =
302 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
303 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
306 static char *ParseField(char *user, char *ary, int modvalue, int off,
307 const char *names, char *ptr)
308 /* 'names' is a pointer to a set of 3-char abbreviations */
318 while (!isspace(*ptr)) {
321 /* Handle numeric digit or symbol or '*' */
323 n1 = 0; /* everything will be filled */
327 } else if (isdigit(*ptr)) {
329 n1 = strtol(ptr, &ptr, 10) + off;
331 n2 = strtol(ptr, &ptr, 10) + off;
337 for (i = 0; names[i]; i += 3) {
338 /* was using strncmp before... */
339 if (strncasecmp(ptr, &names[i], 3) == 0) {
352 /* handle optional range '-' */
354 crondlog(WARN9 "user %s: parse error at %s", user, base);
357 if (*ptr == '-' && n2 < 0) {
363 * collapse single-value ranges, handle skipmark, and fill
364 * in the character array appropriately.
370 skip = strtol(ptr + 1, &ptr, 10);
374 * fill array, using a failsafe is the easiest way to prevent
383 n1 = (n1 + 1) % modvalue;
386 ary[n1 % modvalue] = 1;
389 if (--failsafe == 0) {
390 crondlog(WARN9 "user %s: parse error at %s", user, base);
404 if (!isspace(*ptr)) {
405 crondlog(WARN9 "user %s: parse error at %s", user, base);
409 if (DebugOpt && (LogLevel <= 5)) { /* like LVL5 */
410 /* can't use crondlog, it inserts '\n' */
412 for (i = 0; i < modvalue; ++i)
413 fprintf(stderr, "%d", (unsigned char)ary[i]);
416 return skip_whitespace(ptr);
419 static void FixDayDow(CronLine *line)
425 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
426 if (line->cl_Dow[i] == 0) {
431 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
432 if (line->cl_Days[i] == 0) {
437 if (weekUsed != daysUsed) {
439 memset(line->cl_Days, 0, sizeof(line->cl_Days));
441 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
445 static void SynchronizeFile(const char *fileName)
456 DeleteFile(fileName);
457 fi = fopen(fileName, "r");
461 maxEntries = MAXLINES;
462 if (strcmp(fileName, "root") == 0) {
465 maxLines = maxEntries * 10;
467 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
468 CronFile *file = xzalloc(sizeof(CronFile));
471 file->cf_User = xstrdup(fileName);
472 pline = &file->cf_LineBase;
474 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
479 if (buf[0] == '\0' || buf[0] == '#') {
482 if (--maxEntries == 0) {
486 crondlog(LVL5 "user:%s entry:%s", fileName, buf);
488 *pline = line = xzalloc(sizeof(CronLine));
489 /* parse date ranges */
490 ptr = ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, buf);
491 ptr = ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, ptr);
492 ptr = ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, ptr);
493 ptr = ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, ptr);
494 ptr = ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, ptr);
501 * fix days and dow - if one is not * and the other
502 * is *, the other is set to 0, and vise-versa
506 line->cl_Shell = xstrdup(ptr);
508 crondlog(LVL5 " command:%s", ptr);
510 pline = &line->cl_Next;
514 file->cf_Next = FileBase;
517 if (maxLines == 0 || maxEntries == 0) {
518 crondlog(WARN9 "maximum number of lines reached for user %s", fileName);
524 static void CheckUpdates(void)
529 fi = fopen(CRONUPDATE, "r");
532 while (fgets(buf, sizeof(buf), fi) != NULL) {
533 /* use first word only */
534 SynchronizeFile(strtok(buf, " \t\r\n"));
540 static void SynchronizeDir(void)
543 /* Attempt to delete the database. */
545 for (file = FileBase; file; file = file->cf_Next) {
546 if (!file->cf_Deleted) {
547 DeleteFile(file->cf_User);
553 * Remove cron update file
555 * Re-chdir, in case directory was renamed & deleted, or otherwise
558 * scan directory and add associated users
561 if (chdir(CDir) < 0) {
562 crondlog(DIE9 "can't chdir(%s)", CDir);
565 DIR *dir = opendir(".");
569 crondlog(DIE9 "can't chdir(%s)", "."); /* exits */
570 while ((den = readdir(dir))) {
571 if (strchr(den->d_name, '.') != NULL) {
574 if (getpwnam(den->d_name)) {
575 SynchronizeFile(den->d_name);
577 crondlog(LVL7 "ignoring %s", den->d_name);
585 * DeleteFile() - delete user database
587 * Note: multiple entries for same user may exist if we were unable to
588 * completely delete a database due to running processes.
590 static void DeleteFile(const char *userName)
592 CronFile **pfile = &FileBase;
595 while ((file = *pfile) != NULL) {
596 if (strcmp(userName, file->cf_User) == 0) {
597 CronLine **pline = &file->cf_LineBase;
600 file->cf_Running = 0;
601 file->cf_Deleted = 1;
603 while ((line = *pline) != NULL) {
604 if (line->cl_Pid > 0) {
605 file->cf_Running = 1;
606 pline = &line->cl_Next;
608 *pline = line->cl_Next;
609 free(line->cl_Shell);
613 if (file->cf_Running == 0) {
614 *pfile = file->cf_Next;
618 pfile = &file->cf_Next;
621 pfile = &file->cf_Next;
629 * determine which jobs need to be run. Under normal conditions, the
630 * period is about a minute (one scan). Worst case it will be one
633 static int TestJobs(time_t t1, time_t t2)
638 /* Find jobs > t1 and <= t2 */
640 for (t = t1 - t1 % 60; t <= t2; t += 60) {
649 for (file = FileBase; file; file = file->cf_Next) {
651 crondlog(LVL5 "file %s:", file->cf_User);
652 if (file->cf_Deleted)
654 for (line = file->cf_LineBase; line; line = line->cl_Next) {
656 crondlog(LVL5 " line %s", line->cl_Shell);
657 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour]
658 && (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
659 && line->cl_Mons[tp->tm_mon]
662 crondlog(LVL5 " job: %d %s",
663 (int)line->cl_Pid, line->cl_Shell);
665 if (line->cl_Pid > 0) {
666 crondlog(LVL8 "user %s: process already running: %s",
667 file->cf_User, line->cl_Shell);
668 } else if (line->cl_Pid == 0) {
680 static void RunJobs(void)
685 for (file = FileBase; file; file = file->cf_Next) {
690 for (line = file->cf_LineBase; line; line = line->cl_Next) {
691 if (line->cl_Pid >= 0)
694 RunJob(file->cf_User, line);
695 crondlog(LVL8 "USER %s pid %3d cmd %s",
696 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
697 if (line->cl_Pid < 0) {
699 } else if (line->cl_Pid > 0) {
700 file->cf_Running = 1;
707 * CheckJobs() - check for job completion
709 * Check for job completion, return number of jobs still running after
712 static int CheckJobs(void)
716 int nStillRunning = 0;
718 for (file = FileBase; file; file = file->cf_Next) {
719 if (file->cf_Running) {
720 file->cf_Running = 0;
722 for (line = file->cf_LineBase; line; line = line->cl_Next) {
724 if (line->cl_Pid <= 0)
727 r = waitpid(line->cl_Pid, &status, WNOHANG);
728 if (r < 0 || r == line->cl_Pid) {
729 EndJob(file->cf_User, line);
731 file->cf_Running = 1;
734 file->cf_Running = 1;
738 nStillRunning += file->cf_Running;
740 return nStillRunning;
743 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
745 // TODO: sendmail should be _run-time_ option, not compile-time!
748 ForkJob(const char *user, CronLine *line, int mailFd,
749 const char *prog, const char *cmd, const char *arg,
750 const char *mail_filename)
755 /* prepare things before vfork */
756 pas = getpwnam(user);
758 crondlog(LVL9 "can't get uid for %s", user);
766 /* change running state to the user in question */
769 crondlog(LVL5 "child running %s", prog);
772 xmove_fd(mailFd, mail_filename ? 1 : 0);
775 execl(prog, prog, cmd, arg, NULL);
776 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user, prog, cmd, arg);
778 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
786 crondlog(ERR20 "can't vfork");
790 unlink(mail_filename);
792 } else if (mail_filename) {
793 /* PARENT, FORK SUCCESS
794 * rename mail-file based on pid of process
798 snprintf(mailFile2, sizeof(mailFile2), "%s/cron.%s.%d", TMPDIR, user, pid);
799 rename(mail_filename, mailFile2); // TODO: xrename?
803 * Close the mail file descriptor.. we can't just leave it open in
804 * a structure, closing it later, because we might run out of descriptors
811 static void RunJob(const char *user, CronLine *line)
817 line->cl_MailFlag = 0;
819 /* open mail file - owner root so nobody can screw with it. */
820 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
821 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
824 line->cl_MailFlag = 1;
825 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
827 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
829 crondlog(ERR20 "cannot create mail file %s for user %s, "
830 "discarding output", mailFile, user);
833 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
837 * EndJob - called when job terminates and when mail terminates
839 static void EndJob(const char *user, CronLine *line)
846 if (line->cl_Pid <= 0) {
852 * End of job and no mail file
853 * End of sendmail job
855 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, line->cl_Pid);
858 if (line->cl_MailFlag == 0) {
861 line->cl_MailFlag = 0;
864 * End of primary job - check for mail file. If size has increased and
865 * the file is still valid, we sendmail it.
867 mailFd = open(mailFile, O_RDONLY);
873 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
874 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
875 || !S_ISREG(sbuf.st_mode)
880 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
883 #else /* crond without sendmail */
885 static void RunJob(const char *user, CronLine *line)
890 /* prepare things before vfork */
891 pas = getpwnam(user);
893 crondlog(LVL9 "can't get uid for %s", user);
898 /* fork as the user in question and run program */
902 /* change running state to the user in question */
905 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
907 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
908 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
909 DEFAULT_SHELL, "-c", line->cl_Shell);
914 crondlog(ERR20 "can't vfork");
921 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */