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 SENDMAIL "/usr/sbin/sendmail"
48 #define SENDMAIL_ARGS "-ti", "oem"
51 #define CRONUPDATE "cron.update"
54 #define MAXLINES 256 /* max lines in non-root crontabs */
57 typedef struct CronFile {
58 struct CronFile *cf_Next;
59 struct CronLine *cf_LineBase;
60 char *cf_User; /* username */
61 int cf_Ready; /* bool: one or more jobs ready */
62 int cf_Running; /* bool: one or more jobs running */
63 int cf_Deleted; /* marked for deletion, ignore */
66 typedef struct CronLine {
67 struct CronLine *cl_Next;
68 char *cl_Shell; /* shell command */
69 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
70 int cl_MailFlag; /* running pid is for mail */
71 int cl_MailPos; /* 'empty file' size */
72 char cl_Mins[60]; /* 0-59 */
73 char cl_Hrs[24]; /* 0-23 */
74 char cl_Days[32]; /* 1-31 */
75 char cl_Mons[12]; /* 0-11 */
76 char cl_Dow[7]; /* 0-6, beginning sunday */
85 #ifdef FEATURE_DEBUG_OPT
86 static short DebugOpt;
89 static short LogLevel = 8;
90 static const char *LogFile;
91 static const char *CDir = CRONTABS;
93 static void startlogger(void);
95 static void CheckUpdates(void);
96 static void SynchronizeDir(void);
97 static int TestJobs(time_t t1, time_t t2);
98 static void RunJobs(void);
99 static int CheckJobs(void);
101 static void RunJob(const char *user, CronLine * line);
103 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
104 static void EndJob(const char *user, CronLine * line);
106 #define EndJob(user, line) line->cl_Pid = 0
109 static void DeleteFile(const char *userName);
111 static CronFile *FileBase;
114 static void crondlog(const char *ctl, ...)
118 int level = (int) (ctl[0] & 0xf);
119 int type = level == 20 ?
120 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
125 if (level >= LogLevel) {
127 #ifdef FEATURE_DEBUG_OPT
129 vfprintf(stderr, fmt, va);
133 vsyslog(type, fmt, va);
135 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 600);
137 vdprintf(logfd, fmt, va);
139 #ifdef FEATURE_DEBUG_OPT
141 bb_perror_msg("Can't open log file");
152 int crond_main(int ac, char **av)
155 char *lopt, *Lopt, *copt;
157 #ifdef FEATURE_DEBUG_OPT
160 bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l";
162 bb_opt_complementaly = "f-b:b-f:S-L:L-S";
165 opterr = 0; /* disable getopt 'errors' message. */
166 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
167 #ifdef FEATURE_DEBUG_OPT
170 , &lopt, &Lopt, &copt
171 #ifdef FEATURE_DEBUG_OPT
176 LogLevel = atoi(lopt);
188 #ifdef FEATURE_DEBUG_OPT
190 DebugOpt = atoi(dopt);
199 if (chdir(CDir) != 0) {
200 bb_perror_msg_and_die("%s", CDir);
202 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
203 * version - his died. ;(
206 * close stdin and stdout, stderr.
207 * close unused descriptors - don't need.
208 * optional detach from controlling terminal
212 #if defined(__uClinux__)
213 /* reexec for vfork() do continue parent */
214 vfork_daemon_rexec(1, 0, ac, av, "-f");
216 if (daemon(1, 0) < 0) {
217 bb_perror_msg_and_die("daemon");
222 (void) startlogger(); /* need if syslog mode selected */
225 * main loop - synchronize to 1 second after the minute, minimum sleep
229 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
230 bb_applet_name, LogLevel);
235 time_t t1 = time(NULL);
239 short sleep_time = 60;
242 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
248 * The file 'cron.update' is checked to determine new cron
249 * jobs. The directory is rescanned once an hour to deal
252 * check for disparity. Disparities over an hour either way
253 * result in resynchronization. A reverse-indexed disparity
254 * less then an hour causes us to effectively sleep until we
255 * match the original time (i.e. no re-execution of jobs that
256 * have just been run). A forward-indexed disparity less then
257 * an hour causes intermediate jobs to be run, but only once
260 * when running jobs, the inequality used is greater but not
261 * equal to t1, and less then or equal to t2.
269 #ifdef FEATURE_DEBUG_OPT
271 crondlog("\005Wakeup dt=%d\n", dt);
273 if (dt < -60 * 60 || dt > 60 * 60) {
275 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
280 if (CheckJobs() > 0) {
292 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
296 static void fdprintf(int fd, const char *ctl, ...)
301 vdprintf(fd, ctl, va);
307 static int ChangeUser(const char *user)
313 * Obtain password entry and change privileges
315 pas = getpwnam(user);
317 crondlog("\011failed to get uid for %s", user);
320 setenv("USER", pas->pw_name, 1);
321 setenv("HOME", pas->pw_dir, 1);
322 setenv("SHELL", DEFAULT_SHELL, 1);
325 * Change running state to the user in question
327 err_msg = change_identity_e2str(pas);
329 crondlog("\011%s for user %s", err_msg, user);
332 if (chdir(pas->pw_dir) < 0) {
333 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
334 if (chdir(TMPDIR) < 0) {
335 crondlog("\011chdir failed: %s: %m", TMPDIR);
339 return (pas->pw_uid);
342 static void startlogger(void)
345 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
347 #ifdef FEATURE_DEBUG_OPT
348 else { /* test logfile */
351 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 600)) >= 0) {
354 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
361 static const char *const DowAry[] = {
380 static const char *const MonAry[] = {
409 static char *ParseField(char *user, char *ary, int modvalue, int off,
410 const char *const *names, char *ptr)
420 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
423 /* Handle numeric digit or symbol or '*' */
426 n1 = 0; /* everything will be filled */
430 } else if (*ptr >= '0' && *ptr <= '9') {
432 n1 = strtol(ptr, &ptr, 10) + off;
434 n2 = strtol(ptr, &ptr, 10) + off;
440 for (i = 0; names[i]; ++i) {
441 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
446 ptr += strlen(names[i]);
456 /* handle optional range '-' */
459 crondlog("\111failed user %s parsing %s\n", user, base);
462 if (*ptr == '-' && n2 < 0) {
468 * collapse single-value ranges, handle skipmark, and fill
469 * in the character array appropriately.
476 skip = strtol(ptr + 1, &ptr, 10);
479 * fill array, using a failsafe is the easiest way to prevent
489 n1 = (n1 + 1) % modvalue;
492 ary[n1 % modvalue] = 1;
496 while (n1 != n2 && --failsafe);
499 crondlog("\111failed user %s parsing %s\n", user, base);
511 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
512 crondlog("\111failed user %s parsing %s\n", user, base);
516 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
519 #ifdef FEATURE_DEBUG_OPT
523 for (i = 0; i < modvalue; ++i) {
524 crondlog("\005%d", ary[i]);
533 static void FixDayDow(CronLine * line)
539 for (i = 0; i < arysize(line->cl_Dow); ++i) {
540 if (line->cl_Dow[i] == 0) {
545 for (i = 0; i < arysize(line->cl_Days); ++i) {
546 if (line->cl_Days[i] == 0) {
551 if (weekUsed && !daysUsed) {
552 memset(line->cl_Days, 0, sizeof(line->cl_Days));
554 if (daysUsed && !weekUsed) {
555 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
561 static void SynchronizeFile(const char *fileName)
563 int maxEntries = MAXLINES;
567 if (strcmp(fileName, "root") == 0) {
570 maxLines = maxEntries * 10;
575 DeleteFile(fileName);
577 fi = fopen(fileName, "r");
581 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
582 CronFile *file = calloc(1, sizeof(CronFile));
585 file->cf_User = strdup(fileName);
586 pline = &file->cf_LineBase;
588 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
593 if (buf[0] == 0 || buf[0] == '#') {
596 if (--maxEntries == 0) {
599 memset(&line, 0, sizeof(line));
601 #ifdef FEATURE_DEBUG_OPT
603 crondlog("\111User %s Entry %s\n", fileName, buf);
607 /* parse date ranges */
608 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
609 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
610 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
611 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
612 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
620 * fix days and dow - if one is not * and the other
621 * is *, the other is set to 0, and vise-versa
626 *pline = calloc(1, sizeof(CronLine));
630 (*pline)->cl_Shell = strdup(ptr);
632 #ifdef FEATURE_DEBUG_OPT
634 crondlog("\111 Command %s\n", ptr);
638 pline = &((*pline)->cl_Next);
642 file->cf_Next = FileBase;
645 if (maxLines == 0 || maxEntries == 0) {
646 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
654 static void CheckUpdates(void)
659 fi = fopen(CRONUPDATE, "r");
662 while (fgets(buf, sizeof(buf), fi) != NULL) {
663 SynchronizeFile(strtok(buf, " \t\r\n"));
669 static void SynchronizeDir(void)
671 /* Attempt to delete the database. */
676 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
680 DeleteFile(file->cf_User);
684 * Remove cron update file
686 * Re-chdir, in case directory was renamed & deleted, or otherwise
689 * scan directory and add associated users
693 if (chdir(CDir) < 0) {
694 crondlog("\311unable to find %s\n", CDir);
697 DIR *dir = opendir(".");
701 while ((den = readdir(dir))) {
702 if (strchr(den->d_name, '.') != NULL) {
705 if (getpwnam(den->d_name)) {
706 SynchronizeFile(den->d_name);
708 crondlog("\007ignoring %s\n", den->d_name);
713 crondlog("\311Unable to open current dir!\n");
720 * DeleteFile() - delete user database
722 * Note: multiple entries for same user may exist if we were unable to
723 * completely delete a database due to running processes.
726 static void DeleteFile(const char *userName)
728 CronFile **pfile = &FileBase;
731 while ((file = *pfile) != NULL) {
732 if (strcmp(userName, file->cf_User) == 0) {
733 CronLine **pline = &file->cf_LineBase;
736 file->cf_Running = 0;
737 file->cf_Deleted = 1;
739 while ((line = *pline) != NULL) {
740 if (line->cl_Pid > 0) {
741 file->cf_Running = 1;
742 pline = &line->cl_Next;
744 *pline = line->cl_Next;
745 free(line->cl_Shell);
749 if (file->cf_Running == 0) {
750 *pfile = file->cf_Next;
754 pfile = &file->cf_Next;
757 pfile = &file->cf_Next;
765 * determine which jobs need to be run. Under normal conditions, the
766 * period is about a minute (one scan). Worst case it will be one
770 static int TestJobs(time_t t1, time_t t2)
775 /* Find jobs > t1 and <= t2 */
777 for (t = t1 - t1 % 60; t <= t2; t += 60) {
779 struct tm *tp = localtime(&t);
783 for (file = FileBase; file; file = file->cf_Next) {
784 #ifdef FEATURE_DEBUG_OPT
786 crondlog("\005FILE %s:\n", file->cf_User);
788 if (file->cf_Deleted)
790 for (line = file->cf_LineBase; line; line = line->cl_Next) {
791 #ifdef FEATURE_DEBUG_OPT
793 crondlog("\005 LINE %s\n", line->cl_Shell);
795 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
796 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
797 && line->cl_Mons[tp->tm_mon]) {
798 #ifdef FEATURE_DEBUG_OPT
800 crondlog("\005 JobToDo: %d %s\n",
801 line->cl_Pid, line->cl_Shell);
804 if (line->cl_Pid > 0) {
805 crondlog("\010 process already running: %s %s\n",
806 file->cf_User, line->cl_Shell);
807 } else if (line->cl_Pid == 0) {
820 static void RunJobs(void)
825 for (file = FileBase; file; file = file->cf_Next) {
826 if (file->cf_Ready) {
829 for (line = file->cf_LineBase; line; line = line->cl_Next) {
830 if (line->cl_Pid < 0) {
832 RunJob(file->cf_User, line);
834 crondlog("\010USER %s pid %3d cmd %s\n",
835 file->cf_User, line->cl_Pid, line->cl_Shell);
836 if (line->cl_Pid < 0) {
839 else if (line->cl_Pid > 0) {
840 file->cf_Running = 1;
849 * CheckJobs() - check for job completion
851 * Check for job completion, return number of jobs still running after
855 static int CheckJobs(void)
859 int nStillRunning = 0;
861 for (file = FileBase; file; file = file->cf_Next) {
862 if (file->cf_Running) {
863 file->cf_Running = 0;
865 for (line = file->cf_LineBase; line; line = line->cl_Next) {
866 if (line->cl_Pid > 0) {
868 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
870 if (r < 0 || r == line->cl_Pid) {
871 EndJob(file->cf_User, line);
873 file->cf_Running = 1;
876 file->cf_Running = 1;
881 nStillRunning += file->cf_Running;
883 return (nStillRunning);
887 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
889 ForkJob(const char *user, CronLine * line, int mailFd,
890 const char *prog, const char *cmd, const char *arg, const char *mailf)
892 /* Fork as the user in question and run program */
899 /* Change running state to the user in question */
901 if (ChangeUser(user) < 0) {
904 #ifdef FEATURE_DEBUG_OPT
906 crondlog("\005Child Running %s\n", prog);
911 dup2(mailFd, mailf != NULL);
912 dup2((mailf ? mailFd : 1), 2);
915 execl(prog, prog, cmd, arg, NULL);
916 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
918 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
921 } else if (pid < 0) {
923 crondlog("\024couldn't fork, user %s\n", user);
929 /* PARENT, FORK SUCCESS
930 * rename mail-file based on pid of process
934 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
935 rename(mailf, mailFile2);
938 * Close the mail file descriptor.. we can't just leave it open in
939 * a structure, closing it later, because we might run out of descriptors
947 static void RunJob(const char *user, CronLine * line)
953 line->cl_MailFlag = 0;
955 /* open mail file - owner root so nobody can screw with it. */
957 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
958 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
961 line->cl_MailFlag = 1;
962 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
964 line->cl_MailPos = lseek(mailFd, 0, 1);
966 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
969 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
973 * EndJob - called when job terminates and when mail terminates
976 static void EndJob(const char *user, CronLine * line)
984 if (line->cl_Pid <= 0) {
990 * End of job and no mail file
991 * End of sendmail job
994 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
997 if (line->cl_MailFlag != 1) {
1000 line->cl_MailFlag = 0;
1003 * End of primary job - check for mail file. If size has increased and
1004 * the file is still valid, we sendmail it.
1007 mailFd = open(mailFile, O_RDONLY);
1013 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
1014 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
1018 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1021 /* crond without sendmail */
1023 static void RunJob(const char *user, CronLine * line)
1025 /* Fork as the user in question and run program */
1031 /* Change running state to the user in question */
1033 if (ChangeUser(user) < 0) {
1036 #ifdef FEATURE_DEBUG_OPT
1038 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1042 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1043 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1044 DEFAULT_SHELL, line->cl_Shell);
1046 } else if (pid < 0) {
1048 crondlog("\024couldn't fork, user %s\n", user);
1053 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */