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.
14 #include <sys/syslog.h>
18 #define CRONTABS "/var/spool/cron/crontabs"
21 #define TMPDIR "/var/spool/cron"
24 #define SENDMAIL "sendmail"
27 #define SENDMAIL_ARGS "-ti", "oem"
30 #define CRONUPDATE "cron.update"
33 #define MAXLINES 256 /* max lines in non-root crontabs */
36 typedef struct CronFile {
37 struct CronFile *cf_Next;
38 struct CronLine *cf_LineBase;
39 char *cf_User; /* username */
40 int cf_Ready; /* bool: one or more jobs ready */
41 int cf_Running; /* bool: one or more jobs running */
42 int cf_Deleted; /* marked for deletion, ignore */
45 typedef struct CronLine {
46 struct CronLine *cl_Next;
47 char *cl_Shell; /* shell command */
48 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
49 int cl_MailFlag; /* running pid is for mail */
50 int cl_MailPos; /* 'empty file' size */
51 char cl_Mins[60]; /* 0-59 */
52 char cl_Hrs[24]; /* 0-23 */
53 char cl_Days[32]; /* 1-31 */
54 char cl_Mons[12]; /* 0-11 */
55 char cl_Dow[7]; /* 0-6, beginning sunday */
64 #if ENABLE_DEBUG_CROND_OPTION
65 static unsigned DebugOpt;
68 static unsigned LogLevel = 8;
69 static const char *LogFile;
70 static const char *CDir = CRONTABS;
72 static void startlogger(void);
74 static void CheckUpdates(void);
75 static void SynchronizeDir(void);
76 static int TestJobs(time_t t1, time_t t2);
77 static void RunJobs(void);
78 static int CheckJobs(void);
80 static void RunJob(const char *user, CronLine * line);
82 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
83 static void EndJob(const char *user, CronLine * line);
85 #define EndJob(user, line) line->cl_Pid = 0
88 static void DeleteFile(const char *userName);
90 static CronFile *FileBase;
93 static void crondlog(const char *ctl, ...)
97 int level = (int) (ctl[0] & 0xf);
98 int type = level == 20 ?
99 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
104 if (level >= LogLevel) {
106 #if ENABLE_DEBUG_CROND_OPTION
108 vfprintf(stderr, fmt, va);
112 vsyslog(type, fmt, va);
114 #if !ENABLE_DEBUG_CROND_OPTION
115 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
117 int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
120 vdprintf(logfd, fmt, va);
131 int crond_main(int ac, char **av);
132 int crond_main(int ac, char **av)
135 char *lopt, *Lopt, *copt;
136 USE_DEBUG_CROND_OPTION(char *dopt;)
138 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l");
139 opterr = 0; /* disable getopt 'errors' message. */
140 opt = getopt32(av, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
141 &lopt, &Lopt, &copt USE_DEBUG_CROND_OPTION(, &dopt));
142 if (opt & 1) /* -l */
143 LogLevel = xatou(lopt);
144 if (opt & 2) /* -L */
147 if (opt & 32) /* -c */
150 #if ENABLE_DEBUG_CROND_OPTION
151 if (opt & 64) { /* -d */
152 DebugOpt = xatou(dopt);
157 /* close stdin and stdout, stderr.
158 * close unused descriptors - don't need.
159 * optional detach from controlling terminal
162 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, av);
165 signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
167 startlogger(); /* need if syslog mode selected */
170 * main loop - synchronize to 1 second after the minute, minimum sleep
173 crondlog("\011%s " BB_VER " started, log level %d\n",
174 applet_name, LogLevel);
179 time_t t1 = time(NULL);
183 short sleep_time = 60;
185 write_pidfile("/var/run/crond.pid");
187 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
193 * The file 'cron.update' is checked to determine new cron
194 * jobs. The directory is rescanned once an hour to deal
197 * check for disparity. Disparities over an hour either way
198 * result in resynchronization. A reverse-indexed disparity
199 * less then an hour causes us to effectively sleep until we
200 * match the original time (i.e. no re-execution of jobs that
201 * have just been run). A forward-indexed disparity less then
202 * an hour causes intermediate jobs to be run, but only once
205 * when running jobs, the inequality used is greater but not
206 * equal to t1, and less then or equal to t2.
214 #if ENABLE_DEBUG_CROND_OPTION
216 crondlog("\005Wakeup dt=%d\n", dt);
218 if (dt < -60 * 60 || dt > 60 * 60) {
220 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
225 if (CheckJobs() > 0) {
234 return 0; /* not reached */
237 static int ChangeUser(const char *user)
243 * Obtain password entry and change privileges
245 pas = getpwnam(user);
247 crondlog("\011failed to get uid for %s", user);
250 setenv("USER", pas->pw_name, 1);
251 setenv("HOME", pas->pw_dir, 1);
252 setenv("SHELL", DEFAULT_SHELL, 1);
255 * Change running state to the user in question
257 err_msg = change_identity_e2str(pas);
259 crondlog("\011%s for user %s", err_msg, user);
262 if (chdir(pas->pw_dir) < 0) {
263 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
264 if (chdir(TMPDIR) < 0) {
265 crondlog("\011chdir failed: %s: %m", TMPDIR);
272 static void startlogger(void)
275 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
277 #if ENABLE_DEBUG_CROND_OPTION
278 else { /* test logfile */
281 logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
290 static const char *const DowAry[] = {
309 static const char *const MonAry[] = {
338 static char *ParseField(char *user, char *ary, int modvalue, int off,
339 const char *const *names, char *ptr)
349 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
352 /* Handle numeric digit or symbol or '*' */
355 n1 = 0; /* everything will be filled */
359 } else if (*ptr >= '0' && *ptr <= '9') {
361 n1 = strtol(ptr, &ptr, 10) + off;
363 n2 = strtol(ptr, &ptr, 10) + off;
369 for (i = 0; names[i]; ++i) {
370 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
375 ptr += strlen(names[i]);
385 /* handle optional range '-' */
388 crondlog("\111failed user %s parsing %s\n", user, base);
391 if (*ptr == '-' && n2 < 0) {
397 * collapse single-value ranges, handle skipmark, and fill
398 * in the character array appropriately.
405 skip = strtol(ptr + 1, &ptr, 10);
408 * fill array, using a failsafe is the easiest way to prevent
418 n1 = (n1 + 1) % modvalue;
421 ary[n1 % modvalue] = 1;
425 while (n1 != n2 && --failsafe);
428 crondlog("\111failed user %s parsing %s\n", user, base);
440 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
441 crondlog("\111failed user %s parsing %s\n", user, base);
445 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
448 #if ENABLE_DEBUG_CROND_OPTION
452 for (i = 0; i < modvalue; ++i) {
453 crondlog("\005%d", ary[i]);
462 static void FixDayDow(CronLine * line)
468 for (i = 0; i < (int)(ARRAY_SIZE(line->cl_Dow)); ++i) {
469 if (line->cl_Dow[i] == 0) {
474 for (i = 0; i < (int)(ARRAY_SIZE(line->cl_Days)); ++i) {
475 if (line->cl_Days[i] == 0) {
480 if (weekUsed && !daysUsed) {
481 memset(line->cl_Days, 0, sizeof(line->cl_Days));
483 if (daysUsed && !weekUsed) {
484 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
490 static void SynchronizeFile(const char *fileName)
492 int maxEntries = MAXLINES;
496 if (strcmp(fileName, "root") == 0) {
499 maxLines = maxEntries * 10;
504 DeleteFile(fileName);
506 fi = fopen(fileName, "r");
510 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
511 CronFile *file = xzalloc(sizeof(CronFile));
514 file->cf_User = strdup(fileName);
515 pline = &file->cf_LineBase;
517 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
522 if (buf[0] == 0 || buf[0] == '#') {
525 if (--maxEntries == 0) {
528 memset(&line, 0, sizeof(line));
530 #if ENABLE_DEBUG_CROND_OPTION
532 crondlog("\111User %s Entry %s\n", fileName, buf);
536 /* parse date ranges */
537 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
538 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
539 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
540 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
541 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
549 * fix days and dow - if one is not * and the other
550 * is *, the other is set to 0, and vise-versa
555 *pline = xzalloc(sizeof(CronLine));
559 (*pline)->cl_Shell = strdup(ptr);
561 #if ENABLE_DEBUG_CROND_OPTION
563 crondlog("\111 Command %s\n", ptr);
567 pline = &((*pline)->cl_Next);
571 file->cf_Next = FileBase;
574 if (maxLines == 0 || maxEntries == 0) {
575 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
583 static void CheckUpdates(void)
588 fi = fopen(CRONUPDATE, "r");
591 while (fgets(buf, sizeof(buf), fi) != NULL) {
592 SynchronizeFile(strtok(buf, " \t\r\n"));
598 static void SynchronizeDir(void)
600 /* Attempt to delete the database. */
605 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
609 DeleteFile(file->cf_User);
613 * Remove cron update file
615 * Re-chdir, in case directory was renamed & deleted, or otherwise
618 * scan directory and add associated users
622 if (chdir(CDir) < 0) {
623 crondlog("\311cannot find %s\n", CDir);
626 DIR *dir = opendir(".");
630 while ((den = readdir(dir))) {
631 if (strchr(den->d_name, '.') != NULL) {
634 if (getpwnam(den->d_name)) {
635 SynchronizeFile(den->d_name);
637 crondlog("\007ignoring %s\n", den->d_name);
642 crondlog("\311cannot open current dir!\n");
649 * DeleteFile() - delete user database
651 * Note: multiple entries for same user may exist if we were unable to
652 * completely delete a database due to running processes.
655 static void DeleteFile(const char *userName)
657 CronFile **pfile = &FileBase;
660 while ((file = *pfile) != NULL) {
661 if (strcmp(userName, file->cf_User) == 0) {
662 CronLine **pline = &file->cf_LineBase;
665 file->cf_Running = 0;
666 file->cf_Deleted = 1;
668 while ((line = *pline) != NULL) {
669 if (line->cl_Pid > 0) {
670 file->cf_Running = 1;
671 pline = &line->cl_Next;
673 *pline = line->cl_Next;
674 free(line->cl_Shell);
678 if (file->cf_Running == 0) {
679 *pfile = file->cf_Next;
683 pfile = &file->cf_Next;
686 pfile = &file->cf_Next;
694 * determine which jobs need to be run. Under normal conditions, the
695 * period is about a minute (one scan). Worst case it will be one
699 static int TestJobs(time_t t1, time_t t2)
704 /* Find jobs > t1 and <= t2 */
706 for (t = t1 - t1 % 60; t <= t2; t += 60) {
708 struct tm *tp = localtime(&t);
712 for (file = FileBase; file; file = file->cf_Next) {
713 #if ENABLE_DEBUG_CROND_OPTION
715 crondlog("\005FILE %s:\n", file->cf_User);
717 if (file->cf_Deleted)
719 for (line = file->cf_LineBase; line; line = line->cl_Next) {
720 #if ENABLE_DEBUG_CROND_OPTION
722 crondlog("\005 LINE %s\n", line->cl_Shell);
724 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
725 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
726 && line->cl_Mons[tp->tm_mon]) {
727 #if ENABLE_DEBUG_CROND_OPTION
729 crondlog("\005 JobToDo: %d %s\n",
730 line->cl_Pid, line->cl_Shell);
733 if (line->cl_Pid > 0) {
734 crondlog("\010 process already running: %s %s\n",
735 file->cf_User, line->cl_Shell);
736 } else if (line->cl_Pid == 0) {
749 static void RunJobs(void)
754 for (file = FileBase; file; file = file->cf_Next) {
755 if (file->cf_Ready) {
758 for (line = file->cf_LineBase; line; line = line->cl_Next) {
759 if (line->cl_Pid < 0) {
761 RunJob(file->cf_User, line);
763 crondlog("\010USER %s pid %3d cmd %s\n",
764 file->cf_User, line->cl_Pid, line->cl_Shell);
765 if (line->cl_Pid < 0) {
768 else if (line->cl_Pid > 0) {
769 file->cf_Running = 1;
778 * CheckJobs() - check for job completion
780 * Check for job completion, return number of jobs still running after
784 static int CheckJobs(void)
788 int nStillRunning = 0;
790 for (file = FileBase; file; file = file->cf_Next) {
791 if (file->cf_Running) {
792 file->cf_Running = 0;
794 for (line = file->cf_LineBase; line; line = line->cl_Next) {
795 if (line->cl_Pid > 0) {
797 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
799 if (r < 0 || r == line->cl_Pid) {
800 EndJob(file->cf_User, line);
802 file->cf_Running = 1;
805 file->cf_Running = 1;
810 nStillRunning += file->cf_Running;
812 return nStillRunning;
816 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
818 ForkJob(const char *user, CronLine * line, int mailFd,
819 const char *prog, const char *cmd, const char *arg, const char *mailf)
821 /* Fork as the user in question and run program */
828 /* Change running state to the user in question */
830 if (ChangeUser(user) < 0) {
833 #if ENABLE_DEBUG_CROND_OPTION
835 crondlog("\005Child Running %s\n", prog);
840 dup2(mailFd, mailf != NULL);
841 dup2((mailf ? mailFd : 1), 2);
844 execl(prog, prog, cmd, arg, NULL);
845 crondlog("\024cannot exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
847 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
850 } else if (pid < 0) {
852 crondlog("\024cannot fork, user %s\n", user);
858 /* PARENT, FORK SUCCESS
859 * rename mail-file based on pid of process
863 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
864 rename(mailf, mailFile2);
867 * Close the mail file descriptor.. we can't just leave it open in
868 * a structure, closing it later, because we might run out of descriptors
876 static void RunJob(const char *user, CronLine * line)
882 line->cl_MailFlag = 0;
884 /* open mail file - owner root so nobody can screw with it. */
886 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
887 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
890 line->cl_MailFlag = 1;
891 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
893 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
895 crondlog("\024cannot create mail file user %s file %s, output to /dev/null\n", user, mailFile);
898 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
902 * EndJob - called when job terminates and when mail terminates
905 static void EndJob(const char *user, CronLine * line)
913 if (line->cl_Pid <= 0) {
919 * End of job and no mail file
920 * End of sendmail job
923 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
926 if (line->cl_MailFlag != 1) {
929 line->cl_MailFlag = 0;
932 * End of primary job - check for mail file. If size has increased and
933 * the file is still valid, we sendmail it.
936 mailFd = open(mailFile, O_RDONLY);
942 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
943 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
944 || !S_ISREG(sbuf.st_mode)
949 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
952 /* crond without sendmail */
954 static void RunJob(const char *user, CronLine * line)
956 /* Fork as the user in question and run program */
962 /* Change running state to the user in question */
964 if (ChangeUser(user) < 0) {
967 #if ENABLE_DEBUG_CROND_OPTION
969 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
973 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
974 crondlog("\024cannot exec, user %s cmd %s -c %s\n", user,
975 DEFAULT_SHELL, line->cl_Shell);
977 } else if (pid < 0) {
979 crondlog("\024cannot, user %s\n", user);
984 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */