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
31 #include <sys/ioctl.h>
34 #include <sys/resource.h>
38 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
41 #define CRONTABS "/var/spool/cron/crontabs"
44 #define TMPDIR "/var/spool/cron"
47 #define LOG_FILE "/var/log/cron"
50 #define SENDMAIL "/usr/sbin/sendmail"
53 #define SENDMAIL_ARGS "-t", "-oem", "-i"
56 #define CRONUPDATE "cron.update"
59 #define MAXLINES 256 /* max lines in non-root crontabs */
64 typedef struct CronFile {
65 struct CronFile *cf_Next;
66 struct CronLine *cf_LineBase;
67 char *cf_User; /* username */
68 int cf_Ready; /* bool: one or more jobs ready */
69 int cf_Running; /* bool: one or more jobs running */
70 int cf_Deleted; /* marked for deletion, ignore */
73 typedef struct CronLine {
74 struct CronLine *cl_Next;
75 char *cl_Shell; /* shell command */
76 int cl_Pid; /* running pid, 0, or armed (-1) */
77 int cl_MailFlag; /* running pid is for mail */
78 int cl_MailPos; /* 'empty file' size */
79 char cl_Mins[60]; /* 0-59 */
80 char cl_Hrs[24]; /* 0-23 */
81 char cl_Days[32]; /* 1-31 */
82 char cl_Mons[12]; /* 0-11 */
83 char cl_Dow[7]; /* 0-6, beginning sunday */
92 #ifdef FEATURE_DEBUG_OPT
93 static short DebugOpt;
96 static short LogLevel = 8;
97 static short ForegroundOpt;
98 static short LoggerOpt;
99 static const char *LogFile = LOG_FILE;
100 static const char *CDir = CRONTABS;
102 static void log(int level, const char *ctl, ...);
103 static void log9(const char *ctl, ...);
104 static void startlogger(void);
106 static void CheckUpdates(void);
107 static void SynchronizeDir(void);
108 static int TestJobs(time_t t1, time_t t2);
109 static void RunJobs(void);
110 static int CheckJobs(void);
111 static void RunJob(CronFile *file, CronLine *line);
112 static void EndJob(const CronFile *file, CronLine *line);
114 static void DeleteFile(const char *userName);
116 static CronFile *FileBase;
120 crond_main(int ac, char **av)
124 opterr = 0; /* disable getopt 'errors' message.*/
126 while ((i = getopt(ac,av,
127 #ifdef FEATURE_DEBUG_OPT
130 "l:L:fbSc:")) != EOF){
134 LogLevel = atoi(optarg);
136 #ifdef FEATURE_DEBUG_OPT
138 DebugOpt = atoi(optarg);
148 case 'S': /* select logging to syslog */
151 case 'L': /* select internal file logger */
153 if (*optarg != 0) LogFile = optarg;
156 if (*optarg != 0) CDir = optarg;
158 default: /* parse error */
167 if (chdir(CDir) != 0)
168 perror_msg_and_die("chdir");
171 * close stdin and stdout, stderr.
172 * close unused descriptors - don't need.
173 * optional detach from controlling terminal
176 if (ForegroundOpt == 0) {
178 perror_msg_and_die("daemon");
181 (void)startlogger(); /* need if syslog mode selected */
182 signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original
183 * version - his died. ;(
187 * main loop - synchronize to 1 second after the minute, minimum sleep
191 log(9,"%s " VERSION " dillon, started, log level %d\n", av[0], LogLevel);
196 time_t t1 = time(NULL);
200 short sleep_time = 60;
203 sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time));
209 * The file 'cron.update' is checked to determine new cron
210 * jobs. The directory is rescanned once an hour to deal
213 * check for disparity. Disparities over an hour either way
214 * result in resynchronization. A reverse-indexed disparity
215 * less then an hour causes us to effectively sleep until we
216 * match the original time (i.e. no re-execution of jobs that
217 * have just been run). A forward-indexed disparity less then
218 * an hour causes intermediate jobs to be run, but only once
221 * when running jobs, the inequality used is greater but not
222 * equal to t1, and less then or equal to t2.
230 #ifdef FEATURE_DEBUG_OPT
232 log(5, "Wakeup dt=%d\n", dt);
234 if (dt < -60*60 || dt > 60*60) {
236 log9("time disparity of %d minutes detected\n", dt / 60);
254 vlog(int level, int MLOG_LEVEL, const char *ctl, va_list va)
259 if (level >= LogLevel) {
261 vsnprintf(buf,sizeof(buf), ctl, va);
262 #ifdef FEATURE_DEBUG_OPT
263 if (DebugOpt) fprintf(stderr,"%s",buf);
266 if (LoggerOpt == 0) syslog(MLOG_LEVEL, "%s", buf);
268 if ((logfd = open(LogFile,O_WRONLY|O_CREAT|O_APPEND,600)) >= 0){
269 write(logfd, buf, strlen(buf));
272 #ifdef FEATURE_DEBUG_OPT
273 perror_msg("Can't open log file")
281 set log_level=9 and log messages
285 log9(const char *ctl, ...)
290 vlog(9, LOG_WARNING, ctl, va);
295 normal logger call point.
299 log(int level, const char *ctl, ...)
304 vlog(level, LOG_NOTICE, ctl, va);
310 logfd(int fd, const char *ctl, ...)
311 Updated to: log_error (used by jobs.c)
315 log_err(const char *ctl, ...)
320 vlog(20, LOG_ERR, ctl, va);
325 used by jobs.c (write to temp file..)
329 fdprintf(int fd, const char *ctl, ...)
334 vdprintf(fd, ctl, va);
340 ChangeUser(const char *user, short dochdir)
345 * Obtain password entry and change privilages
348 if ((pas = getpwnam(user)) == 0) {
349 log(9, "failed to get uid for %s", user);
352 setenv("USER", pas->pw_name, 1);
353 setenv("HOME", pas->pw_dir, 1);
354 setenv("SHELL", "/bin/sh", 1);
357 * Change running state to the user in question
360 if (initgroups(user, pas->pw_gid) < 0) {
361 log(9, "initgroups failed: %s %m", user);
364 if (setregid(pas->pw_gid, pas->pw_gid) < 0) {
365 log(9, "setregid failed: %s %d", user, pas->pw_gid);
368 if (setreuid(pas->pw_uid, pas->pw_uid) < 0) {
369 log(9, "setreuid failed: %s %d", user, pas->pw_uid);
373 if (chdir(pas->pw_dir) < 0) {
374 log(8, "chdir failed: %s %s", user, pas->pw_dir);
375 if (chdir(TMPDIR) < 0) {
376 log(9, "chdir failed: %s %s", TMPDIR, user);
390 openlog(applet_name, LOG_CONS|LOG_PID,LOG_CRON);
392 else { /* test logfile */
393 if ((logfd = open(LogFile,O_WRONLY|O_CREAT|O_APPEND,600)) >= 0)
396 #ifdef FEATURE_DEBUG_OPT
397 printf("Failed to open log file '%s' reason: %m", LogFile)
404 static const char * const DowAry[] = {
423 static const char * const MonAry[] = {
453 ParseField(char *user, char *ary, int modvalue, int off,
454 const char * const *names, char *ptr)
463 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
467 * Handle numeric digit or symbol or '*'
471 n1 = 0; /* everything will be filled */
475 } else if (*ptr >= '0' && *ptr <= '9') {
477 n1 = strtol(ptr, &ptr, 10) + off;
479 n2 = strtol(ptr, &ptr, 10) + off;
484 for (i = 0; names[i]; ++i) {
485 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
490 ptr += strlen(names[i]);
500 * handle optional range '-'
504 log9("failed user %s parsing %s\n", user, base);
507 if (*ptr == '-' && n2 < 0) {
513 * collapse single-value ranges, handle skipmark, and fill
514 * in the character array appropriately.
521 skip = strtol(ptr + 1, &ptr, 10);
524 * fill array, using a failsafe is the easiest way to prevent
534 n1 = (n1 + 1) % modvalue;
537 ary[n1 % modvalue] = 1;
540 } while (n1 != n2 && --failsafe);
543 log9("failed user %s parsing %s\n", user, base);
554 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
555 log9("failed user %s parsing %s\n", user, base);
559 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
562 #ifdef FEATURE_DEBUG_OPT
566 for (i = 0; i < modvalue; ++i)
567 log(5, "%d", ary[i]);
576 FixDayDow(CronLine *line)
582 for (i = 0; i < arysize(line->cl_Dow); ++i) {
583 if (line->cl_Dow[i] == 0) {
588 for (i = 0; i < arysize(line->cl_Days); ++i) {
589 if (line->cl_Days[i] == 0) {
594 if (weekUsed && !daysUsed) {
595 memset(line->cl_Days, 0, sizeof(line->cl_Days));
597 if (daysUsed && !weekUsed) {
598 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
605 SynchronizeFile(const char *fileName)
607 int maxEntries = MAXLINES;
611 if (strcmp(fileName, "root") == 0)
613 maxLines = maxEntries * 10;
618 DeleteFile(fileName);
620 if ((fi = fopen(fileName, "r")) != NULL) {
623 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
624 CronFile *file = calloc(1, sizeof(CronFile));
627 file->cf_User = strdup(fileName);
628 pline = &file->cf_LineBase;
630 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
635 buf[strlen(buf)-1] = 0;
637 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
640 if (--maxEntries == 0)
643 memset(&line, 0, sizeof(line));
645 #ifdef FEATURE_DEBUG_OPT
647 log9("User %s Entry %s\n", fileName, buf);
654 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
655 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
656 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
657 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
658 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
668 * fix days and dow - if one is not * and the other
669 * is *, the other is set to 0, and vise-versa
674 *pline = calloc(1, sizeof(CronLine));
681 (*pline)->cl_Shell = strdup(ptr);
683 #ifdef FEATURE_DEBUG_OPT
685 log9(" Command %s\n", ptr);
689 pline = &((*pline)->cl_Next);
693 file->cf_Next = FileBase;
696 if (maxLines == 0 || maxEntries == 0)
697 log9("Maximum number of lines reached for user %s\n", fileName);
710 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
712 while (fgets(buf, sizeof(buf), fi) != NULL) {
713 SynchronizeFile(strtok(buf, " \t\r\n"));
723 * Attempt to delete the database. Note that we have to make a copy
731 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
735 user = strdup(file->cf_User);
741 * Remove cron update file
743 * Re-chdir, in case directory was renamed & deleted, or otherwise
746 * scan directory and add associated users
750 if (chdir(CDir) < 0) {
751 log9("unable to find %s\n", CDir);
758 if ((dir = opendir("."))) {
759 while ((den = readdir(dir))) {
760 if (strchr(den->d_name, '.') != NULL)
762 if (getpwnam(den->d_name))
763 SynchronizeFile(den->d_name);
765 log(7, "ignoring %s\n", den->d_name);
769 log9("Unable to open current dir!\n");
777 * DeleteFile() - delete user database
779 * Note: multiple entries for same user may exist if we were unable to
780 * completely delete a database due to running processes.
784 DeleteFile(const char *userName)
786 CronFile **pfile = &FileBase;
789 while ((file = *pfile) != NULL) {
790 if (strcmp(userName, file->cf_User) == 0) {
791 CronLine **pline = &file->cf_LineBase;
794 file->cf_Running = 0;
795 file->cf_Deleted = 1;
797 while ((line = *pline) != NULL) {
798 if (line->cl_Pid > 0) {
799 file->cf_Running = 1;
800 pline = &line->cl_Next;
802 *pline = line->cl_Next;
803 free(line->cl_Shell);
807 if (file->cf_Running == 0) {
808 *pfile = file->cf_Next;
812 pfile = &file->cf_Next;
815 pfile = &file->cf_Next;
823 * determine which jobs need to be run. Under normal conditions, the
824 * period is about a minute (one scan). Worst case it will be one
829 TestJobs(time_t t1, time_t t2)
835 * Find jobs > t1 and <= t2
838 for (t = t1 - t1 % 60; t <= t2; t += 60) {
840 struct tm *tp = localtime(&t);
844 for (file = FileBase; file; file = file->cf_Next) {
845 #ifdef FEATURE_DEBUG_OPT
847 log(5, "FILE %s:\n", file->cf_User);
849 if (file->cf_Deleted)
851 for (line = file->cf_LineBase; line; line = line->cl_Next) {
852 #ifdef FEATURE_DEBUG_OPT
854 log(5, " LINE %s\n", line->cl_Shell);
856 if (line->cl_Mins[tp->tm_min] &&
857 line->cl_Hrs[tp->tm_hour] &&
858 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
859 line->cl_Mons[tp->tm_mon]
861 #ifdef FEATURE_DEBUG_OPT
863 log(5, " JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
865 if (line->cl_Pid > 0) {
866 log(8, " process already running: %s %s\n",
870 } else if (line->cl_Pid == 0) {
889 for (file = FileBase; file; file = file->cf_Next) {
890 if (file->cf_Ready) {
893 for (line = file->cf_LineBase; line; line = line->cl_Next) {
894 if (line->cl_Pid < 0) {
898 log(8, "USER %s pid %3d cmd %s\n",
903 if (line->cl_Pid < 0)
905 else if (line->cl_Pid > 0)
906 file->cf_Running = 1;
914 * CheckJobs() - check for job completion
916 * Check for job completion, return number of jobs still running after
925 int nStillRunning = 0;
927 for (file = FileBase; file; file = file->cf_Next) {
928 if (file->cf_Running) {
929 file->cf_Running = 0;
931 for (line = file->cf_LineBase; line; line = line->cl_Next) {
932 if (line->cl_Pid > 0) {
934 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
936 if (r < 0 || r == line->cl_Pid) {
939 file->cf_Running = 1;
941 file->cf_Running = 1;
946 nStillRunning += file->cf_Running;
948 return(nStillRunning);
954 RunJob(CronFile *file, CronLine *line)
960 line->cl_MailFlag = 0;
963 * open mail file - owner root so nobody can screw with it.
966 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
967 file->cf_User, getpid());
968 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
971 line->cl_MailFlag = 1;
972 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n",
976 line->cl_MailPos = lseek(mailFd, 0, 1);
980 * Fork as the user in question and run program
983 if ((line->cl_Pid = fork()) == 0) {
989 * Change running state to the user in question
992 if (ChangeUser(file->cf_User, 1) < 0)
995 #ifdef FEATURE_DEBUG_OPT
997 log(5, "Child Running %s\n", line->cl_Shell);
1001 * stdin is already /dev/null, setup stdout and stderr
1009 log_err("unable to create mail file user %s file %s, output to /dev/null\n",
1014 execl("/bin/sh", "/bin/sh", "-c", line->cl_Shell, NULL, NULL);
1015 log_err("unable to exec, user %s cmd /bin/sh -c %s\n",
1019 fdprintf(1, "Exec failed: /bin/sh -c %s\n", line->cl_Shell);
1021 } else if (line->cl_Pid < 0) {
1023 * PARENT, FORK FAILED
1025 log_err("couldn't fork, user %s\n", file->cf_User);
1030 * PARENT, FORK SUCCESS
1032 * rename mail-file based on pid of process
1034 char mailFile2[128];
1036 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
1037 file->cf_User, line->cl_Pid);
1038 rename(mailFile, mailFile2);
1042 * Close the mail file descriptor.. we can't just leave it open in
1043 * a structure, closing it later, because we might run out of descriptors
1051 * EndJob - called when job terminates and when mail terminates
1055 EndJob(const CronFile *file, CronLine *line)
1065 if (line->cl_Pid <= 0) {
1071 * End of job and no mail file
1072 * End of sendmail job
1075 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1076 file->cf_User, line->cl_Pid);
1079 if (line->cl_MailFlag != 1)
1082 line->cl_MailFlag = 0;
1085 * End of primary job - check for mail file. If size has increased and
1086 * the file is still valid, we sendmail it.
1089 mailFd = open(mailFile, O_RDONLY);
1095 if (fstat(mailFd, &sbuf) < 0 ||
1096 sbuf.st_uid != DaemonUid ||
1097 sbuf.st_nlink != 0 ||
1098 sbuf.st_size == line->cl_MailPos ||
1099 !S_ISREG(sbuf.st_mode)
1105 if ((line->cl_Pid = fork()) == 0) {
1111 * change user id - no way in hell security can be compromised
1112 * by the mailing and we already verified the mail file.
1115 if (ChangeUser(file->cf_User, 1) < 0)
1119 * run sendmail with mail file as standard input, only if
1127 execl(SENDMAIL, SENDMAIL, SENDMAIL_ARGS, NULL, NULL);
1128 log_err("unable to exec %s %s, user %s, output to sink null",
1134 } else if (line->cl_Pid < 0) {
1136 * PARENT, FORK FAILED
1138 log_err("unable to fork, user %s", file->cf_User);