2 * crond -d[#] -c <crondir> -f -b
4 * run as root, but NOT setuid root
6 * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com)
7 * May be distributed under the GNU General Public License
9 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 to be used in busybox
12 #define VERSION "2.3.2"
14 #undef FEATURE_DEBUG_OPT
29 #include <sys/ioctl.h>
32 #include <sys/resource.h>
36 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
39 #define CRONTABS "/var/spool/cron/crontabs"
42 #define TMPDIR "/var/spool/cron"
45 #define LOG_FILE "/var/log/cron"
48 #define SENDMAIL "/usr/sbin/sendmail"
51 #define SENDMAIL_ARGS "-t", "-oem", "-i"
54 #define CRONUPDATE "cron.update"
57 #define MAXLINES 256 /* max lines in non-root crontabs */
62 typedef struct CronFile {
63 struct CronFile *cf_Next;
64 struct CronLine *cf_LineBase;
65 char *cf_User; /* username */
66 int cf_Ready; /* bool: one or more jobs ready */
67 int cf_Running; /* bool: one or more jobs running */
68 int cf_Deleted; /* marked for deletion, ignore */
71 typedef struct CronLine {
72 struct CronLine *cl_Next;
73 char *cl_Shell; /* shell command */
74 int cl_Pid; /* running pid, 0, or armed (-1) */
75 int cl_MailFlag; /* running pid is for mail */
76 int cl_MailPos; /* 'empty file' size */
77 char cl_Mins[60]; /* 0-59 */
78 char cl_Hrs[24]; /* 0-23 */
79 char cl_Days[32]; /* 1-31 */
80 char cl_Mons[12]; /* 0-11 */
81 char cl_Dow[7]; /* 0-6, beginning sunday */
90 #ifdef FEATURE_DEBUG_OPT
91 static short DebugOpt;
94 static short LogLevel = 8;
95 static short ForegroundOpt;
96 static short LoggerOpt;
97 static const char *LogFile = LOG_FILE;
98 static const char *CDir = CRONTABS;
100 static void log(int level, const char *ctl, ...);
101 static void log9(const char *ctl, ...);
102 static void startlogger(void);
104 static void CheckUpdates(void);
105 static void SynchronizeDir(void);
106 static int TestJobs(time_t t1, time_t t2);
107 static void RunJobs(void);
108 static int CheckJobs(void);
109 static void RunJob(CronFile *file, CronLine *line);
110 static void EndJob(const CronFile *file, CronLine *line);
112 static void DeleteFile(const char *userName);
114 static CronFile *FileBase;
118 crond_main(int ac, char **av)
122 opterr = 0; /* disable getopt 'errors' message.*/
124 while ((i = getopt(ac,av,
125 #ifdef FEATURE_DEBUG_OPT
128 "l:L:fbSc:")) != EOF){
132 LogLevel = atoi(optarg);
134 #ifdef FEATURE_DEBUG_OPT
136 DebugOpt = atoi(optarg);
146 case 'S': /* select logging to syslog */
149 case 'L': /* select internal file logger */
151 if (*optarg != 0) LogFile = optarg;
154 if (*optarg != 0) CDir = optarg;
156 default: /* parse error */
165 if (chdir(CDir) != 0)
166 bb_perror_msg_and_die("chdir");
169 * close stdin and stdout, stderr.
170 * close unused descriptors - don't need.
171 * optional detach from controlling terminal
174 if (ForegroundOpt == 0) {
176 bb_perror_msg_and_die("daemon");
179 (void)startlogger(); /* need if syslog mode selected */
180 signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original
181 * version - his died. ;(
185 * main loop - synchronize to 1 second after the minute, minimum sleep
189 log(9,"%s " VERSION " dillon, started, log level %d\n", av[0], LogLevel);
194 time_t t1 = time(NULL);
198 short sleep_time = 60;
201 sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time));
207 * The file 'cron.update' is checked to determine new cron
208 * jobs. The directory is rescanned once an hour to deal
211 * check for disparity. Disparities over an hour either way
212 * result in resynchronization. A reverse-indexed disparity
213 * less then an hour causes us to effectively sleep until we
214 * match the original time (i.e. no re-execution of jobs that
215 * have just been run). A forward-indexed disparity less then
216 * an hour causes intermediate jobs to be run, but only once
219 * when running jobs, the inequality used is greater but not
220 * equal to t1, and less then or equal to t2.
228 #ifdef FEATURE_DEBUG_OPT
230 log(5, "Wakeup dt=%d\n", dt);
232 if (dt < -60*60 || dt > 60*60) {
234 log9("time disparity of %d minutes detected\n", dt / 60);
252 vlog(int level, int MLOG_LEVEL, const char *ctl, va_list va)
257 if (level >= LogLevel) {
259 vsnprintf(buf,sizeof(buf), ctl, va);
260 #ifdef FEATURE_DEBUG_OPT
261 if (DebugOpt) fprintf(stderr,"%s",buf);
264 if (LoggerOpt == 0) syslog(MLOG_LEVEL, "%s", buf);
266 if ((logfd = open(LogFile,O_WRONLY|O_CREAT|O_APPEND,600)) >= 0){
267 write(logfd, buf, strlen(buf));
270 #ifdef FEATURE_DEBUG_OPT
271 bb_perror_msg("Can't open log file")
279 set log_level=9 and log messages
283 log9(const char *ctl, ...)
288 vlog(9, LOG_WARNING, ctl, va);
293 normal logger call point.
297 log(int level, const char *ctl, ...)
302 vlog(level, LOG_NOTICE, ctl, va);
308 logfd(int fd, const char *ctl, ...)
309 Updated to: log_error (used by jobs.c)
313 log_err(const char *ctl, ...)
318 vlog(20, LOG_ERR, ctl, va);
323 used by jobs.c (write to temp file..)
327 fdprintf(int fd, const char *ctl, ...)
332 vdprintf(fd, ctl, va);
338 ChangeUser(const char *user, short dochdir)
343 * Obtain password entry and change privilages
346 if ((pas = getpwnam(user)) == 0) {
347 log(9, "failed to get uid for %s", user);
350 setenv("USER", pas->pw_name, 1);
351 setenv("HOME", pas->pw_dir, 1);
352 setenv("SHELL", "/bin/sh", 1);
355 * Change running state to the user in question
358 if (initgroups(user, pas->pw_gid) < 0) {
359 log(9, "initgroups failed: %s %m", user);
362 if (setregid(pas->pw_gid, pas->pw_gid) < 0) {
363 log(9, "setregid failed: %s %d", user, pas->pw_gid);
366 if (setreuid(pas->pw_uid, pas->pw_uid) < 0) {
367 log(9, "setreuid failed: %s %d", user, pas->pw_uid);
371 if (chdir(pas->pw_dir) < 0) {
372 log(8, "chdir failed: %s %s", user, pas->pw_dir);
373 if (chdir(TMPDIR) < 0) {
374 log(9, "chdir failed: %s %s", TMPDIR, user);
388 openlog(bb_applet_name, LOG_CONS|LOG_PID,LOG_CRON);
390 else { /* test logfile */
391 if ((logfd = open(LogFile,O_WRONLY|O_CREAT|O_APPEND,600)) >= 0)
394 #ifdef FEATURE_DEBUG_OPT
395 printf("Failed to open log file '%s' reason: %m", LogFile)
402 static const char * const DowAry[] = {
421 static const char * const MonAry[] = {
451 ParseField(char *user, char *ary, int modvalue, int off,
452 const char * const *names, char *ptr)
461 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
465 * Handle numeric digit or symbol or '*'
469 n1 = 0; /* everything will be filled */
473 } else if (*ptr >= '0' && *ptr <= '9') {
475 n1 = strtol(ptr, &ptr, 10) + off;
477 n2 = strtol(ptr, &ptr, 10) + off;
482 for (i = 0; names[i]; ++i) {
483 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
488 ptr += strlen(names[i]);
498 * handle optional range '-'
502 log9("failed user %s parsing %s\n", user, base);
505 if (*ptr == '-' && n2 < 0) {
511 * collapse single-value ranges, handle skipmark, and fill
512 * in the character array appropriately.
519 skip = strtol(ptr + 1, &ptr, 10);
522 * fill array, using a failsafe is the easiest way to prevent
532 n1 = (n1 + 1) % modvalue;
535 ary[n1 % modvalue] = 1;
538 } while (n1 != n2 && --failsafe);
541 log9("failed user %s parsing %s\n", user, base);
552 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
553 log9("failed user %s parsing %s\n", user, base);
557 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
560 #ifdef FEATURE_DEBUG_OPT
564 for (i = 0; i < modvalue; ++i)
565 log(5, "%d", ary[i]);
574 FixDayDow(CronLine *line)
580 for (i = 0; i < arysize(line->cl_Dow); ++i) {
581 if (line->cl_Dow[i] == 0) {
586 for (i = 0; i < arysize(line->cl_Days); ++i) {
587 if (line->cl_Days[i] == 0) {
592 if (weekUsed && !daysUsed) {
593 memset(line->cl_Days, 0, sizeof(line->cl_Days));
595 if (daysUsed && !weekUsed) {
596 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
603 SynchronizeFile(const char *fileName)
605 int maxEntries = MAXLINES;
609 if (strcmp(fileName, "root") == 0)
611 maxLines = maxEntries * 10;
616 DeleteFile(fileName);
618 if ((fi = fopen(fileName, "r")) != NULL) {
621 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
622 CronFile *file = calloc(1, sizeof(CronFile));
625 file->cf_User = strdup(fileName);
626 pline = &file->cf_LineBase;
628 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
633 buf[strlen(buf)-1] = 0;
635 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
638 if (--maxEntries == 0)
641 memset(&line, 0, sizeof(line));
643 #ifdef FEATURE_DEBUG_OPT
645 log9("User %s Entry %s\n", fileName, buf);
652 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
653 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
654 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
655 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
656 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
666 * fix days and dow - if one is not * and the other
667 * is *, the other is set to 0, and vise-versa
672 *pline = calloc(1, sizeof(CronLine));
679 (*pline)->cl_Shell = strdup(ptr);
681 #ifdef FEATURE_DEBUG_OPT
683 log9(" Command %s\n", ptr);
687 pline = &((*pline)->cl_Next);
691 file->cf_Next = FileBase;
694 if (maxLines == 0 || maxEntries == 0)
695 log9("Maximum number of lines reached for user %s\n", fileName);
708 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
710 while (fgets(buf, sizeof(buf), fi) != NULL) {
711 SynchronizeFile(strtok(buf, " \t\r\n"));
721 * Attempt to delete the database. Note that we have to make a copy
729 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
733 user = strdup(file->cf_User);
739 * Remove cron update file
741 * Re-chdir, in case directory was renamed & deleted, or otherwise
744 * scan directory and add associated users
748 if (chdir(CDir) < 0) {
749 log9("unable to find %s\n", CDir);
756 if ((dir = opendir("."))) {
757 while ((den = readdir(dir))) {
758 if (strchr(den->d_name, '.') != NULL)
760 if (getpwnam(den->d_name))
761 SynchronizeFile(den->d_name);
763 log(7, "ignoring %s\n", den->d_name);
767 log9("Unable to open current dir!\n");
775 * DeleteFile() - delete user database
777 * Note: multiple entries for same user may exist if we were unable to
778 * completely delete a database due to running processes.
782 DeleteFile(const char *userName)
784 CronFile **pfile = &FileBase;
787 while ((file = *pfile) != NULL) {
788 if (strcmp(userName, file->cf_User) == 0) {
789 CronLine **pline = &file->cf_LineBase;
792 file->cf_Running = 0;
793 file->cf_Deleted = 1;
795 while ((line = *pline) != NULL) {
796 if (line->cl_Pid > 0) {
797 file->cf_Running = 1;
798 pline = &line->cl_Next;
800 *pline = line->cl_Next;
801 free(line->cl_Shell);
805 if (file->cf_Running == 0) {
806 *pfile = file->cf_Next;
810 pfile = &file->cf_Next;
813 pfile = &file->cf_Next;
821 * determine which jobs need to be run. Under normal conditions, the
822 * period is about a minute (one scan). Worst case it will be one
827 TestJobs(time_t t1, time_t t2)
833 * Find jobs > t1 and <= t2
836 for (t = t1 - t1 % 60; t <= t2; t += 60) {
838 struct tm *tp = localtime(&t);
842 for (file = FileBase; file; file = file->cf_Next) {
843 #ifdef FEATURE_DEBUG_OPT
845 log(5, "FILE %s:\n", file->cf_User);
847 if (file->cf_Deleted)
849 for (line = file->cf_LineBase; line; line = line->cl_Next) {
850 #ifdef FEATURE_DEBUG_OPT
852 log(5, " LINE %s\n", line->cl_Shell);
854 if (line->cl_Mins[tp->tm_min] &&
855 line->cl_Hrs[tp->tm_hour] &&
856 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
857 line->cl_Mons[tp->tm_mon]
859 #ifdef FEATURE_DEBUG_OPT
861 log(5, " JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
863 if (line->cl_Pid > 0) {
864 log(8, " process already running: %s %s\n",
868 } else if (line->cl_Pid == 0) {
887 for (file = FileBase; file; file = file->cf_Next) {
888 if (file->cf_Ready) {
891 for (line = file->cf_LineBase; line; line = line->cl_Next) {
892 if (line->cl_Pid < 0) {
896 log(8, "USER %s pid %3d cmd %s\n",
901 if (line->cl_Pid < 0)
903 else if (line->cl_Pid > 0)
904 file->cf_Running = 1;
912 * CheckJobs() - check for job completion
914 * Check for job completion, return number of jobs still running after
923 int nStillRunning = 0;
925 for (file = FileBase; file; file = file->cf_Next) {
926 if (file->cf_Running) {
927 file->cf_Running = 0;
929 for (line = file->cf_LineBase; line; line = line->cl_Next) {
930 if (line->cl_Pid > 0) {
932 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
934 if (r < 0 || r == line->cl_Pid) {
937 file->cf_Running = 1;
939 file->cf_Running = 1;
944 nStillRunning += file->cf_Running;
946 return(nStillRunning);
952 RunJob(CronFile *file, CronLine *line)
958 line->cl_MailFlag = 0;
961 * open mail file - owner root so nobody can screw with it.
964 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
965 file->cf_User, getpid());
966 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
969 line->cl_MailFlag = 1;
970 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n",
974 line->cl_MailPos = lseek(mailFd, 0, 1);
978 * Fork as the user in question and run program
981 if ((line->cl_Pid = fork()) == 0) {
987 * Change running state to the user in question
990 if (ChangeUser(file->cf_User, 1) < 0)
993 #ifdef FEATURE_DEBUG_OPT
995 log(5, "Child Running %s\n", line->cl_Shell);
999 * stdin is already /dev/null, setup stdout and stderr
1007 log_err("unable to create mail file user %s file %s, output to /dev/null\n",
1012 execl("/bin/sh", "/bin/sh", "-c", line->cl_Shell, NULL, NULL);
1013 log_err("unable to exec, user %s cmd /bin/sh -c %s\n",
1017 fdprintf(1, "Exec failed: /bin/sh -c %s\n", line->cl_Shell);
1019 } else if (line->cl_Pid < 0) {
1021 * PARENT, FORK FAILED
1023 log_err("couldn't fork, user %s\n", file->cf_User);
1028 * PARENT, FORK SUCCESS
1030 * rename mail-file based on pid of process
1032 char mailFile2[128];
1034 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
1035 file->cf_User, line->cl_Pid);
1036 rename(mailFile, mailFile2);
1040 * Close the mail file descriptor.. we can't just leave it open in
1041 * a structure, closing it later, because we might run out of descriptors
1049 * EndJob - called when job terminates and when mail terminates
1053 EndJob(const CronFile *file, CronLine *line)
1063 if (line->cl_Pid <= 0) {
1069 * End of job and no mail file
1070 * End of sendmail job
1073 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1074 file->cf_User, line->cl_Pid);
1077 if (line->cl_MailFlag != 1)
1080 line->cl_MailFlag = 0;
1083 * End of primary job - check for mail file. If size has increased and
1084 * the file is still valid, we sendmail it.
1087 mailFd = open(mailFile, O_RDONLY);
1093 if (fstat(mailFd, &sbuf) < 0 ||
1094 sbuf.st_uid != DaemonUid ||
1095 sbuf.st_nlink != 0 ||
1096 sbuf.st_size == line->cl_MailPos ||
1097 !S_ISREG(sbuf.st_mode)
1103 if ((line->cl_Pid = fork()) == 0) {
1109 * change user id - no way in hell security can be compromised
1110 * by the mailing and we already verified the mail file.
1113 if (ChangeUser(file->cf_User, 1) < 0)
1117 * run sendmail with mail file as standard input, only if
1125 execl(SENDMAIL, SENDMAIL, SENDMAIL_ARGS, NULL, NULL);
1126 log_err("unable to exec %s %s, user %s, output to sink null",
1132 } else if (line->cl_Pid < 0) {
1134 * PARENT, FORK FAILED
1136 log_err("unable to fork, user %s", file->cf_User);