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 * May be distributed under the GNU General Public License
10 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 to be used in busybox
13 #define VERSION "2.3.2"
15 #undef FEATURE_DEBUG_OPT
30 #include <sys/ioctl.h>
33 #include <sys/resource.h>
37 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
40 #define CRONTABS "/var/spool/cron/crontabs"
43 #define TMPDIR "/var/spool/cron"
46 #define SENDMAIL "/usr/sbin/sendmail"
49 #define SENDMAIL_ARGS "-ti", "oem"
52 #define CRONUPDATE "cron.update"
55 #define MAXLINES 256 /* max lines in non-root crontabs */
58 typedef struct CronFile {
59 struct CronFile *cf_Next;
60 struct CronLine *cf_LineBase;
61 char *cf_User; /* username */
62 int cf_Ready; /* bool: one or more jobs ready */
63 int cf_Running; /* bool: one or more jobs running */
64 int cf_Deleted; /* marked for deletion, ignore */
67 typedef struct CronLine {
68 struct CronLine *cl_Next;
69 char *cl_Shell; /* shell command */
70 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
71 int cl_MailFlag; /* running pid is for mail */
72 int cl_MailPos; /* 'empty file' size */
73 char cl_Mins[60]; /* 0-59 */
74 char cl_Hrs[24]; /* 0-23 */
75 char cl_Days[32]; /* 1-31 */
76 char cl_Mons[12]; /* 0-11 */
77 char cl_Dow[7]; /* 0-6, beginning sunday */
86 #ifdef FEATURE_DEBUG_OPT
87 static short DebugOpt;
90 static short LogLevel = 8;
91 static const char *LogFile;
92 static const char *CDir = CRONTABS;
94 static void startlogger(void);
96 static void CheckUpdates(void);
97 static void SynchronizeDir(void);
98 static int TestJobs(time_t t1, time_t t2);
99 static void RunJobs(void);
100 static int CheckJobs(void);
102 static void RunJob(const char *user, CronLine * line);
104 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
105 static void EndJob(const char *user, CronLine * line);
107 #define EndJob(user, line) line->cl_Pid = 0
110 static void DeleteFile(const char *userName);
112 static CronFile *FileBase;
115 static void crondlog(const char *ctl, ...)
119 int level = (int) (ctl[0] & 0xf);
120 int type = level == 20 ?
121 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
126 if (level >= LogLevel) {
128 #ifdef FEATURE_DEBUG_OPT
130 vfprintf(stderr, fmt, va);
134 vsyslog(type, fmt, va);
136 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
138 vdprintf(logfd, fmt, va);
140 #ifdef FEATURE_DEBUG_OPT
142 bb_perror_msg("Can't open log file");
153 int crond_main(int ac, char **av)
156 char *lopt, *Lopt, *copt;
158 #ifdef FEATURE_DEBUG_OPT
161 bb_opt_complementally = "f-b:b-f:S-L:L-S:d-l";
163 bb_opt_complementally = "f-b:b-f:S-L:L-S";
166 opterr = 0; /* disable getopt 'errors' message. */
167 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
168 #ifdef FEATURE_DEBUG_OPT
171 , &lopt, &Lopt, &copt
172 #ifdef FEATURE_DEBUG_OPT
177 LogLevel = atoi(lopt);
189 #ifdef FEATURE_DEBUG_OPT
191 DebugOpt = atoi(dopt);
200 if (chdir(CDir) != 0) {
201 bb_perror_msg_and_die("%s", CDir);
203 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
204 * version - his died. ;(
207 * close stdin and stdout, stderr.
208 * close unused descriptors - don't need.
209 * optional detach from controlling terminal
213 #if defined(__uClinux__)
214 /* reexec for vfork() do continue parent */
215 vfork_daemon_rexec(1, 0, ac, av, "-f");
221 (void) startlogger(); /* need if syslog mode selected */
224 * main loop - synchronize to 1 second after the minute, minimum sleep
228 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
229 bb_applet_name, LogLevel);
234 time_t t1 = time(NULL);
238 short sleep_time = 60;
241 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
247 * The file 'cron.update' is checked to determine new cron
248 * jobs. The directory is rescanned once an hour to deal
251 * check for disparity. Disparities over an hour either way
252 * result in resynchronization. A reverse-indexed disparity
253 * less then an hour causes us to effectively sleep until we
254 * match the original time (i.e. no re-execution of jobs that
255 * have just been run). A forward-indexed disparity less then
256 * an hour causes intermediate jobs to be run, but only once
259 * when running jobs, the inequality used is greater but not
260 * equal to t1, and less then or equal to t2.
268 #ifdef FEATURE_DEBUG_OPT
270 crondlog("\005Wakeup dt=%d\n", dt);
272 if (dt < -60 * 60 || dt > 60 * 60) {
274 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
279 if (CheckJobs() > 0) {
291 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
295 static void fdprintf(int fd, const char *ctl, ...)
300 vdprintf(fd, ctl, va);
306 static int ChangeUser(const char *user)
312 * Obtain password entry and change privileges
314 pas = getpwnam(user);
316 crondlog("\011failed to get uid for %s", user);
319 setenv("USER", pas->pw_name, 1);
320 setenv("HOME", pas->pw_dir, 1);
321 setenv("SHELL", DEFAULT_SHELL, 1);
324 * Change running state to the user in question
326 err_msg = change_identity_e2str(pas);
328 crondlog("\011%s for user %s", err_msg, user);
331 if (chdir(pas->pw_dir) < 0) {
332 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
333 if (chdir(TMPDIR) < 0) {
334 crondlog("\011chdir failed: %s: %m", TMPDIR);
338 return (pas->pw_uid);
341 static void startlogger(void)
344 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
346 #ifdef FEATURE_DEBUG_OPT
347 else { /* test logfile */
350 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
353 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
360 static const char *const DowAry[] = {
379 static const char *const MonAry[] = {
408 static char *ParseField(char *user, char *ary, int modvalue, int off,
409 const char *const *names, char *ptr)
419 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
422 /* Handle numeric digit or symbol or '*' */
425 n1 = 0; /* everything will be filled */
429 } else if (*ptr >= '0' && *ptr <= '9') {
431 n1 = strtol(ptr, &ptr, 10) + off;
433 n2 = strtol(ptr, &ptr, 10) + off;
439 for (i = 0; names[i]; ++i) {
440 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
445 ptr += strlen(names[i]);
455 /* handle optional range '-' */
458 crondlog("\111failed user %s parsing %s\n", user, base);
461 if (*ptr == '-' && n2 < 0) {
467 * collapse single-value ranges, handle skipmark, and fill
468 * in the character array appropriately.
475 skip = strtol(ptr + 1, &ptr, 10);
478 * fill array, using a failsafe is the easiest way to prevent
488 n1 = (n1 + 1) % modvalue;
491 ary[n1 % modvalue] = 1;
495 while (n1 != n2 && --failsafe);
498 crondlog("\111failed user %s parsing %s\n", user, base);
510 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
511 crondlog("\111failed user %s parsing %s\n", user, base);
515 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
518 #ifdef FEATURE_DEBUG_OPT
522 for (i = 0; i < modvalue; ++i) {
523 crondlog("\005%d", ary[i]);
532 static void FixDayDow(CronLine * line)
538 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
539 if (line->cl_Dow[i] == 0) {
544 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
545 if (line->cl_Days[i] == 0) {
550 if (weekUsed && !daysUsed) {
551 memset(line->cl_Days, 0, sizeof(line->cl_Days));
553 if (daysUsed && !weekUsed) {
554 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
560 static void SynchronizeFile(const char *fileName)
562 int maxEntries = MAXLINES;
566 if (strcmp(fileName, "root") == 0) {
569 maxLines = maxEntries * 10;
574 DeleteFile(fileName);
576 fi = fopen(fileName, "r");
580 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
581 CronFile *file = calloc(1, sizeof(CronFile));
584 file->cf_User = strdup(fileName);
585 pline = &file->cf_LineBase;
587 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
592 if (buf[0] == 0 || buf[0] == '#') {
595 if (--maxEntries == 0) {
598 memset(&line, 0, sizeof(line));
600 #ifdef FEATURE_DEBUG_OPT
602 crondlog("\111User %s Entry %s\n", fileName, buf);
606 /* parse date ranges */
607 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
608 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
609 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
610 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
611 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
619 * fix days and dow - if one is not * and the other
620 * is *, the other is set to 0, and vise-versa
625 *pline = calloc(1, sizeof(CronLine));
629 (*pline)->cl_Shell = strdup(ptr);
631 #ifdef FEATURE_DEBUG_OPT
633 crondlog("\111 Command %s\n", ptr);
637 pline = &((*pline)->cl_Next);
641 file->cf_Next = FileBase;
644 if (maxLines == 0 || maxEntries == 0) {
645 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
653 static void CheckUpdates(void)
658 fi = fopen(CRONUPDATE, "r");
661 while (fgets(buf, sizeof(buf), fi) != NULL) {
662 SynchronizeFile(strtok(buf, " \t\r\n"));
668 static void SynchronizeDir(void)
670 /* Attempt to delete the database. */
675 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
679 DeleteFile(file->cf_User);
683 * Remove cron update file
685 * Re-chdir, in case directory was renamed & deleted, or otherwise
688 * scan directory and add associated users
692 if (chdir(CDir) < 0) {
693 crondlog("\311unable to find %s\n", CDir);
696 DIR *dir = opendir(".");
700 while ((den = readdir(dir))) {
701 if (strchr(den->d_name, '.') != NULL) {
704 if (getpwnam(den->d_name)) {
705 SynchronizeFile(den->d_name);
707 crondlog("\007ignoring %s\n", den->d_name);
712 crondlog("\311Unable to open current dir!\n");
719 * DeleteFile() - delete user database
721 * Note: multiple entries for same user may exist if we were unable to
722 * completely delete a database due to running processes.
725 static void DeleteFile(const char *userName)
727 CronFile **pfile = &FileBase;
730 while ((file = *pfile) != NULL) {
731 if (strcmp(userName, file->cf_User) == 0) {
732 CronLine **pline = &file->cf_LineBase;
735 file->cf_Running = 0;
736 file->cf_Deleted = 1;
738 while ((line = *pline) != NULL) {
739 if (line->cl_Pid > 0) {
740 file->cf_Running = 1;
741 pline = &line->cl_Next;
743 *pline = line->cl_Next;
744 free(line->cl_Shell);
748 if (file->cf_Running == 0) {
749 *pfile = file->cf_Next;
753 pfile = &file->cf_Next;
756 pfile = &file->cf_Next;
764 * determine which jobs need to be run. Under normal conditions, the
765 * period is about a minute (one scan). Worst case it will be one
769 static int TestJobs(time_t t1, time_t t2)
774 /* Find jobs > t1 and <= t2 */
776 for (t = t1 - t1 % 60; t <= t2; t += 60) {
778 struct tm *tp = localtime(&t);
782 for (file = FileBase; file; file = file->cf_Next) {
783 #ifdef FEATURE_DEBUG_OPT
785 crondlog("\005FILE %s:\n", file->cf_User);
787 if (file->cf_Deleted)
789 for (line = file->cf_LineBase; line; line = line->cl_Next) {
790 #ifdef FEATURE_DEBUG_OPT
792 crondlog("\005 LINE %s\n", line->cl_Shell);
794 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
795 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
796 && line->cl_Mons[tp->tm_mon]) {
797 #ifdef FEATURE_DEBUG_OPT
799 crondlog("\005 JobToDo: %d %s\n",
800 line->cl_Pid, line->cl_Shell);
803 if (line->cl_Pid > 0) {
804 crondlog("\010 process already running: %s %s\n",
805 file->cf_User, line->cl_Shell);
806 } else if (line->cl_Pid == 0) {
819 static void RunJobs(void)
824 for (file = FileBase; file; file = file->cf_Next) {
825 if (file->cf_Ready) {
828 for (line = file->cf_LineBase; line; line = line->cl_Next) {
829 if (line->cl_Pid < 0) {
831 RunJob(file->cf_User, line);
833 crondlog("\010USER %s pid %3d cmd %s\n",
834 file->cf_User, line->cl_Pid, line->cl_Shell);
835 if (line->cl_Pid < 0) {
838 else if (line->cl_Pid > 0) {
839 file->cf_Running = 1;
848 * CheckJobs() - check for job completion
850 * Check for job completion, return number of jobs still running after
854 static int CheckJobs(void)
858 int nStillRunning = 0;
860 for (file = FileBase; file; file = file->cf_Next) {
861 if (file->cf_Running) {
862 file->cf_Running = 0;
864 for (line = file->cf_LineBase; line; line = line->cl_Next) {
865 if (line->cl_Pid > 0) {
867 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
869 if (r < 0 || r == line->cl_Pid) {
870 EndJob(file->cf_User, line);
872 file->cf_Running = 1;
875 file->cf_Running = 1;
880 nStillRunning += file->cf_Running;
882 return (nStillRunning);
886 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
888 ForkJob(const char *user, CronLine * line, int mailFd,
889 const char *prog, const char *cmd, const char *arg, const char *mailf)
891 /* Fork as the user in question and run program */
898 /* Change running state to the user in question */
900 if (ChangeUser(user) < 0) {
903 #ifdef FEATURE_DEBUG_OPT
905 crondlog("\005Child Running %s\n", prog);
910 dup2(mailFd, mailf != NULL);
911 dup2((mailf ? mailFd : 1), 2);
914 execl(prog, prog, cmd, arg, NULL);
915 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
917 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
920 } else if (pid < 0) {
922 crondlog("\024couldn't fork, user %s\n", user);
928 /* PARENT, FORK SUCCESS
929 * rename mail-file based on pid of process
933 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
934 rename(mailf, mailFile2);
937 * Close the mail file descriptor.. we can't just leave it open in
938 * a structure, closing it later, because we might run out of descriptors
946 static void RunJob(const char *user, CronLine * line)
952 line->cl_MailFlag = 0;
954 /* open mail file - owner root so nobody can screw with it. */
956 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
957 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
960 line->cl_MailFlag = 1;
961 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
963 line->cl_MailPos = lseek(mailFd, 0, 1);
965 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
968 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
972 * EndJob - called when job terminates and when mail terminates
975 static void EndJob(const char *user, CronLine * line)
983 if (line->cl_Pid <= 0) {
989 * End of job and no mail file
990 * End of sendmail job
993 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
996 if (line->cl_MailFlag != 1) {
999 line->cl_MailFlag = 0;
1002 * End of primary job - check for mail file. If size has increased and
1003 * the file is still valid, we sendmail it.
1006 mailFd = open(mailFile, O_RDONLY);
1012 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
1013 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
1017 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1020 /* crond without sendmail */
1022 static void RunJob(const char *user, CronLine * line)
1024 /* Fork as the user in question and run program */
1030 /* Change running state to the user in question */
1032 if (ChangeUser(user) < 0) {
1035 #ifdef FEATURE_DEBUG_OPT
1037 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1041 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1042 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1043 DEFAULT_SHELL, line->cl_Shell);
1045 } else if (pid < 0) {
1047 crondlog("\024couldn't fork, user %s\n", user);
1052 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */