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)
8 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
10 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
13 #define VERSION "2.3.2"
16 #include <sys/syslog.h>
18 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
21 #define CRONTABS "/var/spool/cron/crontabs"
24 #define TMPDIR "/var/spool/cron"
27 #define SENDMAIL "/usr/sbin/sendmail"
30 #define SENDMAIL_ARGS "-ti", "oem"
33 #define CRONUPDATE "cron.update"
36 #define MAXLINES 256 /* max lines in non-root crontabs */
39 typedef struct CronFile {
40 struct CronFile *cf_Next;
41 struct CronLine *cf_LineBase;
42 char *cf_User; /* username */
43 int cf_Ready; /* bool: one or more jobs ready */
44 int cf_Running; /* bool: one or more jobs running */
45 int cf_Deleted; /* marked for deletion, ignore */
48 typedef struct CronLine {
49 struct CronLine *cl_Next;
50 char *cl_Shell; /* shell command */
51 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
52 int cl_MailFlag; /* running pid is for mail */
53 int cl_MailPos; /* 'empty file' size */
54 char cl_Mins[60]; /* 0-59 */
55 char cl_Hrs[24]; /* 0-23 */
56 char cl_Days[32]; /* 1-31 */
57 char cl_Mons[12]; /* 0-11 */
58 char cl_Dow[7]; /* 0-6, beginning sunday */
67 #if ENABLE_DEBUG_CROND_OPTION
68 static unsigned DebugOpt;
71 static unsigned LogLevel = 8;
72 static const char *LogFile;
73 static const char *CDir = CRONTABS;
75 static void startlogger(void);
77 static void CheckUpdates(void);
78 static void SynchronizeDir(void);
79 static int TestJobs(time_t t1, time_t t2);
80 static void RunJobs(void);
81 static int CheckJobs(void);
83 static void RunJob(const char *user, CronLine * line);
85 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
86 static void EndJob(const char *user, CronLine * line);
88 #define EndJob(user, line) line->cl_Pid = 0
91 static void DeleteFile(const char *userName);
93 static CronFile *FileBase;
96 static void crondlog(const char *ctl, ...)
100 int level = (int) (ctl[0] & 0xf);
101 int type = level == 20 ?
102 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
107 if (level >= LogLevel) {
109 #if ENABLE_DEBUG_CROND_OPTION
111 vfprintf(stderr, fmt, va);
115 vsyslog(type, fmt, va);
117 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
119 vdprintf(logfd, fmt, va);
121 #if ENABLE_DEBUG_CROND_OPTION
123 bb_perror_msg("can't open log file");
134 int crond_main(int ac, char **av);
135 int crond_main(int ac, char **av)
138 char *lopt, *Lopt, *copt;
139 USE_DEBUG_CROND_OPTION(char *dopt;)
141 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l");
142 opterr = 0; /* disable getopt 'errors' message. */
143 opt = getopt32(ac, av, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
144 &lopt, &Lopt, &copt USE_DEBUG_CROND_OPTION(, &dopt));
145 if (opt & 1) /* -l */
146 LogLevel = xatou(lopt);
147 if (opt & 2) /* -L */
150 if (opt & 32) /* -c */
153 #if ENABLE_DEBUG_CROND_OPTION
154 if (opt & 64) { /* -d */
155 DebugOpt = xatou(dopt);
160 /* close stdin and stdout, stderr.
161 * close unused descriptors - don't need.
162 * optional detach from controlling terminal
165 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, av);
168 signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
170 startlogger(); /* need if syslog mode selected */
173 * main loop - synchronize to 1 second after the minute, minimum sleep
176 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
177 applet_name, LogLevel);
182 time_t t1 = time(NULL);
186 short sleep_time = 60;
188 write_pidfile("/var/run/crond.pid");
190 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
196 * The file 'cron.update' is checked to determine new cron
197 * jobs. The directory is rescanned once an hour to deal
200 * check for disparity. Disparities over an hour either way
201 * result in resynchronization. A reverse-indexed disparity
202 * less then an hour causes us to effectively sleep until we
203 * match the original time (i.e. no re-execution of jobs that
204 * have just been run). A forward-indexed disparity less then
205 * an hour causes intermediate jobs to be run, but only once
208 * when running jobs, the inequality used is greater but not
209 * equal to t1, and less then or equal to t2.
217 #if ENABLE_DEBUG_CROND_OPTION
219 crondlog("\005Wakeup dt=%d\n", dt);
221 if (dt < -60 * 60 || dt > 60 * 60) {
223 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
228 if (CheckJobs() > 0) {
237 return 0; /* not reached */
240 static int ChangeUser(const char *user)
246 * Obtain password entry and change privileges
248 pas = getpwnam(user);
250 crondlog("\011failed to get uid for %s", user);
253 setenv("USER", pas->pw_name, 1);
254 setenv("HOME", pas->pw_dir, 1);
255 setenv("SHELL", DEFAULT_SHELL, 1);
258 * Change running state to the user in question
260 err_msg = change_identity_e2str(pas);
262 crondlog("\011%s for user %s", err_msg, user);
265 if (chdir(pas->pw_dir) < 0) {
266 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
267 if (chdir(TMPDIR) < 0) {
268 crondlog("\011chdir failed: %s: %m", TMPDIR);
275 static void startlogger(void)
278 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
280 #if ENABLE_DEBUG_CROND_OPTION
281 else { /* test logfile */
284 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
287 bb_perror_msg("failed to open log file '%s': ", LogFile);
294 static const char *const DowAry[] = {
313 static const char *const MonAry[] = {
342 static char *ParseField(char *user, char *ary, int modvalue, int off,
343 const char *const *names, char *ptr)
353 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
356 /* Handle numeric digit or symbol or '*' */
359 n1 = 0; /* everything will be filled */
363 } else if (*ptr >= '0' && *ptr <= '9') {
365 n1 = strtol(ptr, &ptr, 10) + off;
367 n2 = strtol(ptr, &ptr, 10) + off;
373 for (i = 0; names[i]; ++i) {
374 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
379 ptr += strlen(names[i]);
389 /* handle optional range '-' */
392 crondlog("\111failed user %s parsing %s\n", user, base);
395 if (*ptr == '-' && n2 < 0) {
401 * collapse single-value ranges, handle skipmark, and fill
402 * in the character array appropriately.
409 skip = strtol(ptr + 1, &ptr, 10);
412 * fill array, using a failsafe is the easiest way to prevent
422 n1 = (n1 + 1) % modvalue;
425 ary[n1 % modvalue] = 1;
429 while (n1 != n2 && --failsafe);
432 crondlog("\111failed user %s parsing %s\n", user, base);
444 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
445 crondlog("\111failed user %s parsing %s\n", user, base);
449 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
452 #if ENABLE_DEBUG_CROND_OPTION
456 for (i = 0; i < modvalue; ++i) {
457 crondlog("\005%d", ary[i]);
466 static void FixDayDow(CronLine * line)
472 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
473 if (line->cl_Dow[i] == 0) {
478 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
479 if (line->cl_Days[i] == 0) {
484 if (weekUsed && !daysUsed) {
485 memset(line->cl_Days, 0, sizeof(line->cl_Days));
487 if (daysUsed && !weekUsed) {
488 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
494 static void SynchronizeFile(const char *fileName)
496 int maxEntries = MAXLINES;
500 if (strcmp(fileName, "root") == 0) {
503 maxLines = maxEntries * 10;
508 DeleteFile(fileName);
510 fi = fopen(fileName, "r");
514 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
515 CronFile *file = xzalloc(sizeof(CronFile));
518 file->cf_User = strdup(fileName);
519 pline = &file->cf_LineBase;
521 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
526 if (buf[0] == 0 || buf[0] == '#') {
529 if (--maxEntries == 0) {
532 memset(&line, 0, sizeof(line));
534 #if ENABLE_DEBUG_CROND_OPTION
536 crondlog("\111User %s Entry %s\n", fileName, buf);
540 /* parse date ranges */
541 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
542 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
543 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
544 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
545 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
553 * fix days and dow - if one is not * and the other
554 * is *, the other is set to 0, and vise-versa
559 *pline = xzalloc(sizeof(CronLine));
563 (*pline)->cl_Shell = strdup(ptr);
565 #if ENABLE_DEBUG_CROND_OPTION
567 crondlog("\111 Command %s\n", ptr);
571 pline = &((*pline)->cl_Next);
575 file->cf_Next = FileBase;
578 if (maxLines == 0 || maxEntries == 0) {
579 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
587 static void CheckUpdates(void)
592 fi = fopen(CRONUPDATE, "r");
595 while (fgets(buf, sizeof(buf), fi) != NULL) {
596 SynchronizeFile(strtok(buf, " \t\r\n"));
602 static void SynchronizeDir(void)
604 /* Attempt to delete the database. */
609 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
613 DeleteFile(file->cf_User);
617 * Remove cron update file
619 * Re-chdir, in case directory was renamed & deleted, or otherwise
622 * scan directory and add associated users
626 if (chdir(CDir) < 0) {
627 crondlog("\311cannot find %s\n", CDir);
630 DIR *dir = opendir(".");
634 while ((den = readdir(dir))) {
635 if (strchr(den->d_name, '.') != NULL) {
638 if (getpwnam(den->d_name)) {
639 SynchronizeFile(den->d_name);
641 crondlog("\007ignoring %s\n", den->d_name);
646 crondlog("\311cannot open current dir!\n");
653 * DeleteFile() - delete user database
655 * Note: multiple entries for same user may exist if we were unable to
656 * completely delete a database due to running processes.
659 static void DeleteFile(const char *userName)
661 CronFile **pfile = &FileBase;
664 while ((file = *pfile) != NULL) {
665 if (strcmp(userName, file->cf_User) == 0) {
666 CronLine **pline = &file->cf_LineBase;
669 file->cf_Running = 0;
670 file->cf_Deleted = 1;
672 while ((line = *pline) != NULL) {
673 if (line->cl_Pid > 0) {
674 file->cf_Running = 1;
675 pline = &line->cl_Next;
677 *pline = line->cl_Next;
678 free(line->cl_Shell);
682 if (file->cf_Running == 0) {
683 *pfile = file->cf_Next;
687 pfile = &file->cf_Next;
690 pfile = &file->cf_Next;
698 * determine which jobs need to be run. Under normal conditions, the
699 * period is about a minute (one scan). Worst case it will be one
703 static int TestJobs(time_t t1, time_t t2)
708 /* Find jobs > t1 and <= t2 */
710 for (t = t1 - t1 % 60; t <= t2; t += 60) {
712 struct tm *tp = localtime(&t);
716 for (file = FileBase; file; file = file->cf_Next) {
717 #if ENABLE_DEBUG_CROND_OPTION
719 crondlog("\005FILE %s:\n", file->cf_User);
721 if (file->cf_Deleted)
723 for (line = file->cf_LineBase; line; line = line->cl_Next) {
724 #if ENABLE_DEBUG_CROND_OPTION
726 crondlog("\005 LINE %s\n", line->cl_Shell);
728 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
729 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
730 && line->cl_Mons[tp->tm_mon]) {
731 #if ENABLE_DEBUG_CROND_OPTION
733 crondlog("\005 JobToDo: %d %s\n",
734 line->cl_Pid, line->cl_Shell);
737 if (line->cl_Pid > 0) {
738 crondlog("\010 process already running: %s %s\n",
739 file->cf_User, line->cl_Shell);
740 } else if (line->cl_Pid == 0) {
753 static void RunJobs(void)
758 for (file = FileBase; file; file = file->cf_Next) {
759 if (file->cf_Ready) {
762 for (line = file->cf_LineBase; line; line = line->cl_Next) {
763 if (line->cl_Pid < 0) {
765 RunJob(file->cf_User, line);
767 crondlog("\010USER %s pid %3d cmd %s\n",
768 file->cf_User, line->cl_Pid, line->cl_Shell);
769 if (line->cl_Pid < 0) {
772 else if (line->cl_Pid > 0) {
773 file->cf_Running = 1;
782 * CheckJobs() - check for job completion
784 * Check for job completion, return number of jobs still running after
788 static int CheckJobs(void)
792 int nStillRunning = 0;
794 for (file = FileBase; file; file = file->cf_Next) {
795 if (file->cf_Running) {
796 file->cf_Running = 0;
798 for (line = file->cf_LineBase; line; line = line->cl_Next) {
799 if (line->cl_Pid > 0) {
801 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
803 if (r < 0 || r == line->cl_Pid) {
804 EndJob(file->cf_User, line);
806 file->cf_Running = 1;
809 file->cf_Running = 1;
814 nStillRunning += file->cf_Running;
816 return nStillRunning;
820 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
822 ForkJob(const char *user, CronLine * line, int mailFd,
823 const char *prog, const char *cmd, const char *arg, const char *mailf)
825 /* Fork as the user in question and run program */
832 /* Change running state to the user in question */
834 if (ChangeUser(user) < 0) {
837 #if ENABLE_DEBUG_CROND_OPTION
839 crondlog("\005Child Running %s\n", prog);
844 dup2(mailFd, mailf != NULL);
845 dup2((mailf ? mailFd : 1), 2);
848 execl(prog, prog, cmd, arg, NULL);
849 crondlog("\024cannot exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
851 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
854 } else if (pid < 0) {
856 crondlog("\024cannot fork, user %s\n", user);
862 /* PARENT, FORK SUCCESS
863 * rename mail-file based on pid of process
867 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
868 rename(mailf, mailFile2);
871 * Close the mail file descriptor.. we can't just leave it open in
872 * a structure, closing it later, because we might run out of descriptors
880 static void RunJob(const char *user, CronLine * line)
886 line->cl_MailFlag = 0;
888 /* open mail file - owner root so nobody can screw with it. */
890 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
891 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
894 line->cl_MailFlag = 1;
895 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
897 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
899 crondlog("\024cannot create mail file user %s file %s, output to /dev/null\n", user, mailFile);
902 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
906 * EndJob - called when job terminates and when mail terminates
909 static void EndJob(const char *user, CronLine * line)
917 if (line->cl_Pid <= 0) {
923 * End of job and no mail file
924 * End of sendmail job
927 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
930 if (line->cl_MailFlag != 1) {
933 line->cl_MailFlag = 0;
936 * End of primary job - check for mail file. If size has increased and
937 * the file is still valid, we sendmail it.
940 mailFd = open(mailFile, O_RDONLY);
946 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
947 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
951 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
954 /* crond without sendmail */
956 static void RunJob(const char *user, CronLine * line)
958 /* Fork as the user in question and run program */
964 /* Change running state to the user in question */
966 if (ChangeUser(user) < 0) {
969 #if ENABLE_DEBUG_CROND_OPTION
971 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
975 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
976 crondlog("\024cannot exec, user %s cmd %s -c %s\n", user,
977 DEFAULT_SHELL, line->cl_Shell);
979 } else if (pid < 0) {
981 crondlog("\024cannot, user %s\n", user);
986 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */