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 */
62 char *cl_MailTo; /* whom to mail results */
64 /* ordered by size, not in natural order. makes code smaller: */
65 char cl_Dow[7]; /* 0-6, beginning sunday */
66 char cl_Mons[12]; /* 0-11 */
67 char cl_Hrs[24]; /* 0-23 */
68 char cl_Days[32]; /* 1-31 */
69 char cl_Mins[60]; /* 0-59 */
83 OPT_d = (1 << 6) * ENABLE_DEBUG_CROND_OPTION,
85 #if ENABLE_DEBUG_CROND_OPTION
86 #define DebugOpt (option_mask32 & OPT_d)
93 unsigned LogLevel; /* = 8; */
95 const char *CDir; /* = CRONTABS; */
102 #define G (*(struct globals*)&bb_common_bufsiz1)
103 #define LogLevel (G.LogLevel )
104 #define LogFile (G.LogFile )
105 #define CDir (G.CDir )
106 #define FileBase (G.FileBase )
107 #define env_var_user (G.env_var_user )
108 #define env_var_home (G.env_var_home )
109 #define INIT_G() do { \
115 static void CheckUpdates(void);
116 static void SynchronizeDir(void);
117 static int TestJobs(time_t t1, time_t t2);
118 static void RunJobs(void);
119 static int CheckJobs(void);
120 static void RunJob(const char *user, CronLine *line);
121 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
122 static void EndJob(const char *user, CronLine *line);
124 #define EndJob(user, line) ((line)->cl_Pid = 0)
126 static void DeleteFile(const char *userName);
135 /* level >= 20 is "error" */
138 static void crondlog(const char *ctl, ...)
141 int level = (ctl[0] & 0x1f);
144 if (level >= (int)LogLevel) {
145 /* Debug mode: all to (non-redirected) stderr, */
146 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
147 if (!DebugOpt && LogFile) {
148 /* Otherwise (log to file): we reopen log file at every write: */
149 int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
151 xmove_fd(logfd, STDERR_FILENO);
153 // TODO: ERR -> error, WARN -> warning, LVL -> info
154 bb_verror_msg(ctl + 1, va, /* strerr: */ NULL);
161 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
162 int crond_main(int argc UNUSED_PARAM, char **argv)
168 /* "-b after -f is ignored", and so on for every pair a-b */
169 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l")
170 ":l+:d+"; /* -l and -d have numeric param */
171 opt = getopt32(argv, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
172 &LogLevel, &LogFile, &CDir
173 USE_DEBUG_CROND_OPTION(,&LogLevel));
174 /* both -d N and -l N set the same variable: LogLevel */
176 if (!(opt & OPT_f)) {
177 /* close stdin, stdout, stderr.
178 * close unused descriptors - don't need them. */
179 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
182 if (!DebugOpt && LogFile == NULL) {
183 /* logging to syslog */
184 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
185 logmode = LOGMODE_SYSLOG;
189 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
190 setenv("SHELL", DEFAULT_SHELL, 1); /* once, for all future children */
191 crondlog(LVL9 "crond (busybox "BB_VER") started, log level %d", LogLevel);
194 /* main loop - synchronize to 1 second after the minute, minimum sleep
197 time_t t1 = time(NULL);
203 write_pidfile("/var/run/crond.pid");
205 sleep((sleep_time + 1) - (time(NULL) % sleep_time));
208 dt = (long)t2 - (long)t1;
211 * The file 'cron.update' is checked to determine new cron
212 * jobs. The directory is rescanned once an hour to deal
215 * check for disparity. Disparities over an hour either way
216 * result in resynchronization. A reverse-indexed disparity
217 * less then an hour causes us to effectively sleep until we
218 * match the original time (i.e. no re-execution of jobs that
219 * have just been run). A forward-indexed disparity less then
220 * an hour causes intermediate jobs to be run, but only once
223 * when running jobs, the inequality used is greater but not
224 * equal to t1, and less then or equal to t2.
232 crondlog(LVL5 "wakeup dt=%ld", dt);
233 if (dt < -60 * 60 || dt > 60 * 60) {
234 crondlog(WARN9 "time disparity of %d minutes detected", dt / 60);
239 if (CheckJobs() > 0) {
248 return 0; /* not reached */
252 /* We set environment *before* vfork (because we want to use vfork),
253 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
254 * Using putenv(), and freeing memory after unsetenv() won't leak */
255 static void safe_setenv4(char **pvar_val, const char *var, const char *val /*, int len*/)
257 const int len = 4; /* both var names are 4 char long */
258 char *var_val = *pvar_val;
261 var_val[len] = '\0'; /* nuke '=' */
265 *pvar_val = xasprintf("%s=%s", var, val);
270 static void SetEnv(struct passwd *pas)
273 safe_setenv4(&env_var_user, "USER", pas->pw_name);
274 safe_setenv4(&env_var_home, "HOME", pas->pw_dir);
275 /* if we want to set user's shell instead: */
276 /*safe_setenv(env_var_user, "SHELL", pas->pw_shell, 5);*/
278 setenv("USER", pas->pw_name, 1);
279 setenv("HOME", pas->pw_dir, 1);
281 /* currently, we use constant one: */
282 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
285 static void ChangeUser(struct passwd *pas)
287 /* careful: we're after vfork! */
288 change_identity(pas); /* - initgroups, setgid, setuid */
289 if (chdir(pas->pw_dir) < 0) {
290 crondlog(LVL9 "can't chdir(%s)", pas->pw_dir);
291 if (chdir(TMPDIR) < 0) {
292 crondlog(DIE9 "can't chdir(%s)", TMPDIR); /* exits */
297 static const char DowAry[] ALIGN1 =
298 "sun""mon""tue""wed""thu""fri""sat"
299 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
302 static const char MonAry[] ALIGN1 =
303 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
304 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
307 static void ParseField(char *user, char *ary, int modvalue, int off,
308 const char *names, char *ptr)
309 /* 'names' is a pointer to a set of 3-char abbreviations */
315 // this can't happen due to config_read()
322 /* Handle numeric digit or symbol or '*' */
324 n1 = 0; /* everything will be filled */
328 } else if (isdigit(*ptr)) {
330 n1 = strtol(ptr, &ptr, 10) + off;
332 n2 = strtol(ptr, &ptr, 10) + off;
338 for (i = 0; names[i]; i += 3) {
339 /* was using strncmp before... */
340 if (strncasecmp(ptr, &names[i], 3) == 0) {
353 /* handle optional range '-' */
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) {
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]);
418 static void FixDayDow(CronLine *line)
424 for (i = 0; i < ARRAY_SIZE(line->cl_Dow); ++i) {
425 if (line->cl_Dow[i] == 0) {
430 for (i = 0; i < ARRAY_SIZE(line->cl_Days); ++i) {
431 if (line->cl_Days[i] == 0) {
436 if (weekUsed != daysUsed) {
438 memset(line->cl_Days, 0, sizeof(line->cl_Days));
440 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
444 static void SynchronizeFile(const char *fileName)
446 struct parser_t *parser;
450 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
457 DeleteFile(fileName);
458 parser = config_open(fileName);
462 maxLines = (strcmp(fileName, "root") == 0) ? 65535 : MAXLINES;
464 if (fstat(fileno(parser->fp), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
465 CronFile *file = xzalloc(sizeof(CronFile));
469 file->cf_User = xstrdup(fileName);
470 pline = &file->cf_LineBase;
472 while (--maxLines && (n=config_read(parser, tokens, 6, 0, " \t", '#')) >= 0) {
476 crondlog(LVL5 "user:%s entry:%s", fileName, parser->data);
479 /* check if line is setting MAILTO= */
480 if (0 == strncmp(tokens[0], "MAILTO=", 7)) {
481 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
483 mailTo = (tokens[0][7]) ? xstrdup(&tokens[0][7]) : NULL;
484 #endif /* otherwise just ignore such lines */
487 /* check if a minimum of tokens is specified */
490 *pline = line = xzalloc(sizeof(CronLine));
491 /* parse date ranges */
492 ParseField(file->cf_User, line->cl_Mins, 60, 0, NULL, tokens[0]);
493 ParseField(file->cf_User, line->cl_Hrs, 24, 0, NULL, tokens[1]);
494 ParseField(file->cf_User, line->cl_Days, 32, 0, NULL, tokens[2]);
495 ParseField(file->cf_User, line->cl_Mons, 12, -1, MonAry, tokens[3]);
496 ParseField(file->cf_User, line->cl_Dow, 7, 0, DowAry, tokens[4]);
498 * fix days and dow - if one is not "*" and the other
499 * is "*", the other is set to 0, and vise-versa
502 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
503 /* copy mailto (can be NULL) */
504 line->cl_MailTo = xstrdup(mailTo);
507 line->cl_Shell = xstrdup(tokens[5]);
509 crondlog(LVL5 " command:%s", tokens[5]);
511 pline = &line->cl_Next;
512 //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]);
516 file->cf_Next = FileBase;
520 crondlog(WARN9 "user %s: too many lines", fileName);
523 config_close(parser);
526 static void CheckUpdates(void)
531 fi = fopen(CRONUPDATE, "r");
534 while (fgets(buf, sizeof(buf), fi) != NULL) {
535 /* use first word only */
536 SynchronizeFile(strtok(buf, " \t\r\n"));
542 static void SynchronizeDir(void)
545 /* Attempt to delete the database. */
547 for (file = FileBase; file; file = file->cf_Next) {
548 if (!file->cf_Deleted) {
549 DeleteFile(file->cf_User);
555 * Remove cron update file
557 * Re-chdir, in case directory was renamed & deleted, or otherwise
560 * scan directory and add associated users
563 if (chdir(CDir) < 0) {
564 crondlog(DIE9 "can't chdir(%s)", CDir);
567 DIR *dir = opendir(".");
571 crondlog(DIE9 "can't chdir(%s)", "."); /* exits */
572 while ((den = readdir(dir)) != NULL) {
573 if (strchr(den->d_name, '.') != NULL) {
576 if (getpwnam(den->d_name)) {
577 SynchronizeFile(den->d_name);
579 crondlog(LVL7 "ignoring %s", den->d_name);
587 * DeleteFile() - delete user database
589 * Note: multiple entries for same user may exist if we were unable to
590 * completely delete a database due to running processes.
592 static void DeleteFile(const char *userName)
594 CronFile **pfile = &FileBase;
597 while ((file = *pfile) != NULL) {
598 if (strcmp(userName, file->cf_User) == 0) {
599 CronLine **pline = &file->cf_LineBase;
602 file->cf_Running = 0;
603 file->cf_Deleted = 1;
605 while ((line = *pline) != NULL) {
606 if (line->cl_Pid > 0) {
607 file->cf_Running = 1;
608 pline = &line->cl_Next;
610 *pline = line->cl_Next;
611 free(line->cl_Shell);
615 if (file->cf_Running == 0) {
616 *pfile = file->cf_Next;
620 pfile = &file->cf_Next;
623 pfile = &file->cf_Next;
631 * determine which jobs need to be run. Under normal conditions, the
632 * period is about a minute (one scan). Worst case it will be one
635 static int TestJobs(time_t t1, time_t t2)
640 /* Find jobs > t1 and <= t2 */
642 for (t = t1 - t1 % 60; t <= t2; t += 60) {
651 for (file = FileBase; file; file = file->cf_Next) {
653 crondlog(LVL5 "file %s:", file->cf_User);
654 if (file->cf_Deleted)
656 for (line = file->cf_LineBase; line; line = line->cl_Next) {
658 crondlog(LVL5 " line %s", line->cl_Shell);
659 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour]
660 && (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
661 && line->cl_Mons[tp->tm_mon]
664 crondlog(LVL5 " job: %d %s",
665 (int)line->cl_Pid, line->cl_Shell);
667 if (line->cl_Pid > 0) {
668 crondlog(LVL8 "user %s: process already running: %s",
669 file->cf_User, line->cl_Shell);
670 } else if (line->cl_Pid == 0) {
682 static void RunJobs(void)
687 for (file = FileBase; file; file = file->cf_Next) {
692 for (line = file->cf_LineBase; line; line = line->cl_Next) {
693 if (line->cl_Pid >= 0)
696 RunJob(file->cf_User, line);
697 crondlog(LVL8 "USER %s pid %3d cmd %s",
698 file->cf_User, (int)line->cl_Pid, line->cl_Shell);
699 if (line->cl_Pid < 0) {
701 } else if (line->cl_Pid > 0) {
702 file->cf_Running = 1;
709 * CheckJobs() - check for job completion
711 * Check for job completion, return number of jobs still running after
714 static int CheckJobs(void)
718 int nStillRunning = 0;
720 for (file = FileBase; file; file = file->cf_Next) {
721 if (file->cf_Running) {
722 file->cf_Running = 0;
724 for (line = file->cf_LineBase; line; line = line->cl_Next) {
726 if (line->cl_Pid <= 0)
729 r = waitpid(line->cl_Pid, &status, WNOHANG);
730 if (r < 0 || r == line->cl_Pid) {
731 EndJob(file->cf_User, line);
733 file->cf_Running = 1;
736 file->cf_Running = 1;
740 nStillRunning += file->cf_Running;
742 return nStillRunning;
745 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
747 // TODO: sendmail should be _run-time_ option, not compile-time!
750 ForkJob(const char *user, CronLine *line, int mailFd,
751 const char *prog, const char *cmd, const char *arg,
752 const char *mail_filename)
757 /* prepare things before vfork */
758 pas = getpwnam(user);
760 crondlog(LVL9 "can't get uid for %s", user);
768 /* change running state to the user in question */
771 crondlog(LVL5 "child running %s", prog);
774 xmove_fd(mailFd, mail_filename ? 1 : 0);
777 execlp(prog, prog, cmd, arg, NULL);
778 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user, prog, cmd, arg);
780 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
788 crondlog(ERR20 "can't vfork");
792 unlink(mail_filename);
794 } else if (mail_filename) {
795 /* PARENT, FORK SUCCESS
796 * rename mail-file based on pid of process
800 snprintf(mailFile2, sizeof(mailFile2), "%s/cron.%s.%d", TMPDIR, user, pid);
801 rename(mail_filename, mailFile2); // TODO: xrename?
805 * Close the mail file descriptor.. we can't just leave it open in
806 * a structure, closing it later, because we might run out of descriptors
813 static void RunJob(const char *user, CronLine *line)
819 line->cl_MailFlag = 0;
821 if (line->cl_MailTo) {
822 /* open mail file - owner root so nobody can screw with it. */
823 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, getpid());
824 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
827 line->cl_MailFlag = 1;
828 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", line->cl_MailTo,
830 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
832 crondlog(ERR20 "cannot create mail file %s for user %s, "
833 "discarding output", mailFile, user);
837 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
841 * EndJob - called when job terminates and when mail terminates
843 static void EndJob(const char *user, CronLine *line)
850 if (line->cl_Pid <= 0) {
856 * End of job and no mail file
857 * End of sendmail job
859 snprintf(mailFile, sizeof(mailFile), "%s/cron.%s.%d", TMPDIR, user, line->cl_Pid);
862 if (line->cl_MailFlag == 0) {
865 line->cl_MailFlag = 0;
868 * End of primary job - check for mail file. If size has increased and
869 * the file is still valid, we sendmail it.
871 mailFd = open(mailFile, O_RDONLY);
877 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
878 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
879 || !S_ISREG(sbuf.st_mode)
885 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
888 #else /* crond without sendmail */
890 static void RunJob(const char *user, CronLine *line)
895 /* prepare things before vfork */
896 pas = getpwnam(user);
898 crondlog(LVL9 "can't get uid for %s", user);
903 /* fork as the user in question and run program */
907 /* change running state to the user in question */
910 crondlog(LVL5 "child running %s", DEFAULT_SHELL);
912 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
913 crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
914 DEFAULT_SHELL, "-c", line->cl_Shell);
919 crondlog(ERR20 "can't vfork");
926 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */