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)
121 char *lopt, *Lopt, *copt;
122 #ifdef FEATURE_DEBUG_OPT
124 bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l";
126 bb_opt_complementaly = "f-b:b-f:S-L:L-S";
129 opterr = 0; /* disable getopt 'errors' message.*/
130 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
131 #ifdef FEATURE_DEBUG_OPT
134 , &lopt, &Lopt, &copt
135 #ifdef FEATURE_DEBUG_OPT
140 LogLevel = atoi(lopt);
143 if (*Lopt != 0) LogFile = Lopt;
144 ForegroundOpt = opt & 4;
146 if (*copt != 0) CDir = copt;
148 #ifdef FEATURE_DEBUG_OPT
150 DebugOpt = atoi(dopt);
159 if (chdir(CDir) != 0)
160 bb_perror_msg_and_die("chdir");
162 signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original
163 * version - his died. ;(
166 * close stdin and stdout, stderr.
167 * close unused descriptors - don't need.
168 * optional detach from controlling terminal
171 if (ForegroundOpt == 0) {
173 bb_perror_msg_and_die("daemon");
176 (void)startlogger(); /* need if syslog mode selected */
179 * main loop - synchronize to 1 second after the minute, minimum sleep
183 log(9,"%s " VERSION " dillon, started, log level %d\n", av[0], LogLevel);
188 time_t t1 = time(NULL);
192 short sleep_time = 60;
195 sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time));
201 * The file 'cron.update' is checked to determine new cron
202 * jobs. The directory is rescanned once an hour to deal
205 * check for disparity. Disparities over an hour either way
206 * result in resynchronization. A reverse-indexed disparity
207 * less then an hour causes us to effectively sleep until we
208 * match the original time (i.e. no re-execution of jobs that
209 * have just been run). A forward-indexed disparity less then
210 * an hour causes intermediate jobs to be run, but only once
213 * when running jobs, the inequality used is greater but not
214 * equal to t1, and less then or equal to t2.
222 #ifdef FEATURE_DEBUG_OPT
224 log(5, "Wakeup dt=%d\n", dt);
226 if (dt < -60*60 || dt > 60*60) {
228 log9("time disparity of %d minutes detected\n", dt / 60);
246 vlog(int level, int MLOG_LEVEL, const char *ctl, va_list va)
251 if (level >= LogLevel) {
253 vsnprintf(buf,sizeof(buf), ctl, va);
254 #ifdef FEATURE_DEBUG_OPT
255 if (DebugOpt) fprintf(stderr,"%s",buf);
258 if (LoggerOpt == 0) syslog(MLOG_LEVEL, "%s", buf);
260 if ((logfd = open(LogFile,O_WRONLY|O_CREAT|O_APPEND,600)) >= 0){
261 write(logfd, buf, strlen(buf));
264 #ifdef FEATURE_DEBUG_OPT
265 bb_perror_msg("Can't open log file")
273 set log_level=9 and log messages
277 log9(const char *ctl, ...)
282 vlog(9, LOG_WARNING, ctl, va);
287 normal logger call point.
291 log(int level, const char *ctl, ...)
296 vlog(level, LOG_NOTICE, ctl, va);
302 logfd(int fd, const char *ctl, ...)
303 Updated to: log_error (used by jobs.c)
307 log_err(const char *ctl, ...)
312 vlog(20, LOG_ERR, ctl, va);
317 used by jobs.c (write to temp file..)
321 fdprintf(int fd, const char *ctl, ...)
326 vdprintf(fd, ctl, va);
332 ChangeUser(const char *user, short dochdir)
337 * Obtain password entry and change privilages
340 if ((pas = getpwnam(user)) == 0) {
341 log(9, "failed to get uid for %s", user);
344 setenv("USER", pas->pw_name, 1);
345 setenv("HOME", pas->pw_dir, 1);
346 setenv("SHELL", "/bin/sh", 1);
349 * Change running state to the user in question
352 if (initgroups(user, pas->pw_gid) < 0) {
353 log(9, "initgroups failed: %s %m", user);
356 if (setregid(pas->pw_gid, pas->pw_gid) < 0) {
357 log(9, "setregid failed: %s %d", user, pas->pw_gid);
360 if (setreuid(pas->pw_uid, pas->pw_uid) < 0) {
361 log(9, "setreuid failed: %s %d", user, pas->pw_uid);
365 if (chdir(pas->pw_dir) < 0) {
366 log(8, "chdir failed: %s %s", user, pas->pw_dir);
367 if (chdir(TMPDIR) < 0) {
368 log(9, "chdir failed: %s %s", TMPDIR, user);
382 openlog(bb_applet_name, LOG_CONS|LOG_PID,LOG_CRON);
384 else { /* test logfile */
385 if ((logfd = open(LogFile,O_WRONLY|O_CREAT|O_APPEND,600)) >= 0)
388 #ifdef FEATURE_DEBUG_OPT
389 printf("Failed to open log file '%s' reason: %m", LogFile)
396 static const char * const DowAry[] = {
415 static const char * const MonAry[] = {
445 ParseField(char *user, char *ary, int modvalue, int off,
446 const char * const *names, char *ptr)
455 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
459 * Handle numeric digit or symbol or '*'
463 n1 = 0; /* everything will be filled */
467 } else if (*ptr >= '0' && *ptr <= '9') {
469 n1 = strtol(ptr, &ptr, 10) + off;
471 n2 = strtol(ptr, &ptr, 10) + off;
476 for (i = 0; names[i]; ++i) {
477 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
482 ptr += strlen(names[i]);
492 * handle optional range '-'
496 log9("failed user %s parsing %s\n", user, base);
499 if (*ptr == '-' && n2 < 0) {
505 * collapse single-value ranges, handle skipmark, and fill
506 * in the character array appropriately.
513 skip = strtol(ptr + 1, &ptr, 10);
516 * fill array, using a failsafe is the easiest way to prevent
526 n1 = (n1 + 1) % modvalue;
529 ary[n1 % modvalue] = 1;
532 } while (n1 != n2 && --failsafe);
535 log9("failed user %s parsing %s\n", user, base);
546 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
547 log9("failed user %s parsing %s\n", user, base);
551 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
554 #ifdef FEATURE_DEBUG_OPT
558 for (i = 0; i < modvalue; ++i)
559 log(5, "%d", ary[i]);
568 FixDayDow(CronLine *line)
574 for (i = 0; i < arysize(line->cl_Dow); ++i) {
575 if (line->cl_Dow[i] == 0) {
580 for (i = 0; i < arysize(line->cl_Days); ++i) {
581 if (line->cl_Days[i] == 0) {
586 if (weekUsed && !daysUsed) {
587 memset(line->cl_Days, 0, sizeof(line->cl_Days));
589 if (daysUsed && !weekUsed) {
590 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
597 SynchronizeFile(const char *fileName)
599 int maxEntries = MAXLINES;
603 if (strcmp(fileName, "root") == 0)
605 maxLines = maxEntries * 10;
610 DeleteFile(fileName);
612 if ((fi = fopen(fileName, "r")) != NULL) {
615 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
616 CronFile *file = calloc(1, sizeof(CronFile));
619 file->cf_User = strdup(fileName);
620 pline = &file->cf_LineBase;
622 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
627 buf[strlen(buf)-1] = 0;
629 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
632 if (--maxEntries == 0)
635 memset(&line, 0, sizeof(line));
637 #ifdef FEATURE_DEBUG_OPT
639 log9("User %s Entry %s\n", fileName, buf);
646 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
647 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
648 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
649 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
650 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
660 * fix days and dow - if one is not * and the other
661 * is *, the other is set to 0, and vise-versa
666 *pline = calloc(1, sizeof(CronLine));
673 (*pline)->cl_Shell = strdup(ptr);
675 #ifdef FEATURE_DEBUG_OPT
677 log9(" Command %s\n", ptr);
681 pline = &((*pline)->cl_Next);
685 file->cf_Next = FileBase;
688 if (maxLines == 0 || maxEntries == 0)
689 log9("Maximum number of lines reached for user %s\n", fileName);
702 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
704 while (fgets(buf, sizeof(buf), fi) != NULL) {
705 SynchronizeFile(strtok(buf, " \t\r\n"));
715 * Attempt to delete the database. Note that we have to make a copy
723 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
727 user = strdup(file->cf_User);
733 * Remove cron update file
735 * Re-chdir, in case directory was renamed & deleted, or otherwise
738 * scan directory and add associated users
742 if (chdir(CDir) < 0) {
743 log9("unable to find %s\n", CDir);
750 if ((dir = opendir("."))) {
751 while ((den = readdir(dir))) {
752 if (strchr(den->d_name, '.') != NULL)
754 if (getpwnam(den->d_name))
755 SynchronizeFile(den->d_name);
757 log(7, "ignoring %s\n", den->d_name);
761 log9("Unable to open current dir!\n");
769 * DeleteFile() - delete user database
771 * Note: multiple entries for same user may exist if we were unable to
772 * completely delete a database due to running processes.
776 DeleteFile(const char *userName)
778 CronFile **pfile = &FileBase;
781 while ((file = *pfile) != NULL) {
782 if (strcmp(userName, file->cf_User) == 0) {
783 CronLine **pline = &file->cf_LineBase;
786 file->cf_Running = 0;
787 file->cf_Deleted = 1;
789 while ((line = *pline) != NULL) {
790 if (line->cl_Pid > 0) {
791 file->cf_Running = 1;
792 pline = &line->cl_Next;
794 *pline = line->cl_Next;
795 free(line->cl_Shell);
799 if (file->cf_Running == 0) {
800 *pfile = file->cf_Next;
804 pfile = &file->cf_Next;
807 pfile = &file->cf_Next;
815 * determine which jobs need to be run. Under normal conditions, the
816 * period is about a minute (one scan). Worst case it will be one
821 TestJobs(time_t t1, time_t t2)
827 * Find jobs > t1 and <= t2
830 for (t = t1 - t1 % 60; t <= t2; t += 60) {
832 struct tm *tp = localtime(&t);
836 for (file = FileBase; file; file = file->cf_Next) {
837 #ifdef FEATURE_DEBUG_OPT
839 log(5, "FILE %s:\n", file->cf_User);
841 if (file->cf_Deleted)
843 for (line = file->cf_LineBase; line; line = line->cl_Next) {
844 #ifdef FEATURE_DEBUG_OPT
846 log(5, " LINE %s\n", line->cl_Shell);
848 if (line->cl_Mins[tp->tm_min] &&
849 line->cl_Hrs[tp->tm_hour] &&
850 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
851 line->cl_Mons[tp->tm_mon]
853 #ifdef FEATURE_DEBUG_OPT
855 log(5, " JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
857 if (line->cl_Pid > 0) {
858 log(8, " process already running: %s %s\n",
862 } else if (line->cl_Pid == 0) {
881 for (file = FileBase; file; file = file->cf_Next) {
882 if (file->cf_Ready) {
885 for (line = file->cf_LineBase; line; line = line->cl_Next) {
886 if (line->cl_Pid < 0) {
890 log(8, "USER %s pid %3d cmd %s\n",
895 if (line->cl_Pid < 0)
897 else if (line->cl_Pid > 0)
898 file->cf_Running = 1;
906 * CheckJobs() - check for job completion
908 * Check for job completion, return number of jobs still running after
917 int nStillRunning = 0;
919 for (file = FileBase; file; file = file->cf_Next) {
920 if (file->cf_Running) {
921 file->cf_Running = 0;
923 for (line = file->cf_LineBase; line; line = line->cl_Next) {
924 if (line->cl_Pid > 0) {
926 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
928 if (r < 0 || r == line->cl_Pid) {
931 file->cf_Running = 1;
933 file->cf_Running = 1;
938 nStillRunning += file->cf_Running;
940 return(nStillRunning);
946 RunJob(CronFile *file, CronLine *line)
952 line->cl_MailFlag = 0;
955 * open mail file - owner root so nobody can screw with it.
958 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
959 file->cf_User, getpid());
960 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
963 line->cl_MailFlag = 1;
964 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n",
968 line->cl_MailPos = lseek(mailFd, 0, 1);
972 * Fork as the user in question and run program
975 if ((line->cl_Pid = fork()) == 0) {
981 * Change running state to the user in question
984 if (ChangeUser(file->cf_User, 1) < 0)
987 #ifdef FEATURE_DEBUG_OPT
989 log(5, "Child Running %s\n", line->cl_Shell);
993 * stdin is already /dev/null, setup stdout and stderr
1001 log_err("unable to create mail file user %s file %s, output to /dev/null\n",
1006 execl("/bin/sh", "/bin/sh", "-c", line->cl_Shell, NULL, NULL);
1007 log_err("unable to exec, user %s cmd /bin/sh -c %s\n",
1011 fdprintf(1, "Exec failed: /bin/sh -c %s\n", line->cl_Shell);
1013 } else if (line->cl_Pid < 0) {
1015 * PARENT, FORK FAILED
1017 log_err("couldn't fork, user %s\n", file->cf_User);
1022 * PARENT, FORK SUCCESS
1024 * rename mail-file based on pid of process
1026 char mailFile2[128];
1028 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
1029 file->cf_User, line->cl_Pid);
1030 rename(mailFile, mailFile2);
1034 * Close the mail file descriptor.. we can't just leave it open in
1035 * a structure, closing it later, because we might run out of descriptors
1043 * EndJob - called when job terminates and when mail terminates
1047 EndJob(const CronFile *file, CronLine *line)
1057 if (line->cl_Pid <= 0) {
1063 * End of job and no mail file
1064 * End of sendmail job
1067 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1068 file->cf_User, line->cl_Pid);
1071 if (line->cl_MailFlag != 1)
1074 line->cl_MailFlag = 0;
1077 * End of primary job - check for mail file. If size has increased and
1078 * the file is still valid, we sendmail it.
1081 mailFd = open(mailFile, O_RDONLY);
1087 if (fstat(mailFd, &sbuf) < 0 ||
1088 sbuf.st_uid != DaemonUid ||
1089 sbuf.st_nlink != 0 ||
1090 sbuf.st_size == line->cl_MailPos ||
1091 !S_ISREG(sbuf.st_mode)
1097 if ((line->cl_Pid = fork()) == 0) {
1103 * change user id - no way in hell security can be compromised
1104 * by the mailing and we already verified the mail file.
1107 if (ChangeUser(file->cf_User, 1) < 0)
1111 * run sendmail with mail file as standard input, only if
1119 execl(SENDMAIL, SENDMAIL, SENDMAIL_ARGS, NULL, NULL);
1120 log_err("unable to exec %s %s, user %s, output to sink null",
1126 } else if (line->cl_Pid < 0) {
1128 * PARENT, FORK FAILED
1130 log_err("unable to fork, user %s", file->cf_User);