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);
102 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
103 static void EndJob(const char *user, CronLine *line);
105 #define EndJob(user, line) line->cl_Pid = 0
108 static void DeleteFile(const char *userName);
110 static CronFile *FileBase;
114 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
128 if (DebugOpt) vfprintf(stderr, fmt, va);
131 if (LogFile == 0) vsyslog(type, fmt, va);
135 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0) {
136 vdprintf(logfd, fmt, va);
138 #ifdef FEATURE_DEBUG_OPT
140 bb_perror_msg("Can't open log file");
151 crond_main(int ac, char **av)
154 char *lopt, *Lopt, *copt;
155 #ifdef FEATURE_DEBUG_OPT
157 bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l";
159 bb_opt_complementaly = "f-b:b-f:S-L:L-S";
162 opterr = 0; /* disable getopt 'errors' message.*/
163 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
164 #ifdef FEATURE_DEBUG_OPT
167 , &lopt, &Lopt, &copt
168 #ifdef FEATURE_DEBUG_OPT
173 LogLevel = atoi(lopt);
175 if (*Lopt != 0) LogFile = Lopt;
177 if (*copt != 0) CDir = copt;
179 #ifdef FEATURE_DEBUG_OPT
181 DebugOpt = atoi(dopt);
190 if (chdir(CDir) != 0)
191 bb_perror_msg_and_die("%s", CDir);
193 signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original
194 * version - his died. ;(
197 * close stdin and stdout, stderr.
198 * close unused descriptors - don't need.
199 * optional detach from controlling terminal
203 if(daemon(1, 0) < 0) {
204 bb_perror_msg_and_die("daemon");
206 #if defined(__uClinux__)
208 /* reexec for vfork() do continue parent */
209 vfork_daemon_rexec(ac, av, "-f");
214 (void)startlogger(); /* need if syslog mode selected */
217 * main loop - synchronize to 1 second after the minute, minimum sleep
221 crondlog("\011%s " VERSION " dillon, started, log level %d\n", bb_applet_name,
227 time_t t1 = time(NULL);
231 short sleep_time = 60;
234 sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time));
240 * The file 'cron.update' is checked to determine new cron
241 * jobs. The directory is rescanned once an hour to deal
244 * check for disparity. Disparities over an hour either way
245 * result in resynchronization. A reverse-indexed disparity
246 * less then an hour causes us to effectively sleep until we
247 * match the original time (i.e. no re-execution of jobs that
248 * have just been run). A forward-indexed disparity less then
249 * an hour causes intermediate jobs to be run, but only once
252 * when running jobs, the inequality used is greater but not
253 * equal to t1, and less then or equal to t2.
261 #ifdef FEATURE_DEBUG_OPT
263 crondlog("\005Wakeup dt=%d\n", dt);
265 if (dt < -60*60 || dt > 60*60) {
267 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
284 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
289 fdprintf(int fd, const char *ctl, ...)
294 vdprintf(fd, ctl, va);
301 ChangeUser(const char *user)
307 * Obtain password entry and change privilages
310 if ((pas = getpwnam(user)) == 0) {
311 crondlog("\011failed to get uid for %s", user);
314 setenv("USER", pas->pw_name, 1);
315 setenv("HOME", pas->pw_dir, 1);
316 setenv("SHELL", DEFAULT_SHELL, 1);
319 * Change running state to the user in question
321 err_msg = change_identity_e2str(pas);
323 crondlog("\011%s for user %s", err_msg, user);
326 if (chdir(pas->pw_dir) < 0) {
327 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
328 if (chdir(TMPDIR) < 0) {
329 crondlog("\011chdir failed: %s: %m", TMPDIR);
340 openlog(bb_applet_name, LOG_CONS|LOG_PID, LOG_CRON);
341 #ifdef FEATURE_DEBUG_OPT
342 else { /* test logfile */
345 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0)
348 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
354 static const char * const DowAry[] = {
373 static const char * const MonAry[] = {
403 ParseField(char *user, char *ary, int modvalue, int off,
404 const char * const *names, char *ptr)
413 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
417 * Handle numeric digit or symbol or '*'
421 n1 = 0; /* everything will be filled */
425 } else if (*ptr >= '0' && *ptr <= '9') {
427 n1 = strtol(ptr, &ptr, 10) + off;
429 n2 = strtol(ptr, &ptr, 10) + off;
434 for (i = 0; names[i]; ++i) {
435 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
440 ptr += strlen(names[i]);
450 * handle optional range '-'
454 crondlog("\111failed user %s parsing %s\n", user, base);
457 if (*ptr == '-' && n2 < 0) {
463 * collapse single-value ranges, handle skipmark, and fill
464 * in the character array appropriately.
471 skip = strtol(ptr + 1, &ptr, 10);
474 * fill array, using a failsafe is the easiest way to prevent
484 n1 = (n1 + 1) % modvalue;
487 ary[n1 % modvalue] = 1;
490 } while (n1 != n2 && --failsafe);
493 crondlog("\111failed user %s parsing %s\n", user, base);
504 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
505 crondlog("\111failed user %s parsing %s\n", user, base);
509 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
512 #ifdef FEATURE_DEBUG_OPT
516 for (i = 0; i < modvalue; ++i)
517 crondlog("\005%d", ary[i]);
526 FixDayDow(CronLine *line)
532 for (i = 0; i < arysize(line->cl_Dow); ++i) {
533 if (line->cl_Dow[i] == 0) {
538 for (i = 0; i < arysize(line->cl_Days); ++i) {
539 if (line->cl_Days[i] == 0) {
544 if (weekUsed && !daysUsed) {
545 memset(line->cl_Days, 0, sizeof(line->cl_Days));
547 if (daysUsed && !weekUsed) {
548 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
555 SynchronizeFile(const char *fileName)
557 int maxEntries = MAXLINES;
561 if (strcmp(fileName, "root") == 0)
563 maxLines = maxEntries * 10;
568 DeleteFile(fileName);
570 if ((fi = fopen(fileName, "r")) != NULL) {
573 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
574 CronFile *file = calloc(1, sizeof(CronFile));
577 file->cf_User = strdup(fileName);
578 pline = &file->cf_LineBase;
580 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
585 buf[strlen(buf)-1] = 0;
587 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
590 if (--maxEntries == 0)
593 memset(&line, 0, sizeof(line));
595 #ifdef FEATURE_DEBUG_OPT
597 crondlog("\111User %s Entry %s\n", fileName, buf);
604 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
605 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
606 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
607 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
608 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
618 * fix days and dow - if one is not * and the other
619 * is *, the other is set to 0, and vise-versa
624 *pline = calloc(1, sizeof(CronLine));
631 (*pline)->cl_Shell = strdup(ptr);
633 #ifdef FEATURE_DEBUG_OPT
635 crondlog("\111 Command %s\n", ptr);
639 pline = &((*pline)->cl_Next);
643 file->cf_Next = FileBase;
646 if (maxLines == 0 || maxEntries == 0)
647 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
660 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
662 while (fgets(buf, sizeof(buf), fi) != NULL) {
663 SynchronizeFile(strtok(buf, " \t\r\n"));
673 * Attempt to delete the database.
679 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
683 DeleteFile(file->cf_User);
687 * Remove cron update file
689 * Re-chdir, in case directory was renamed & deleted, or otherwise
692 * scan directory and add associated users
696 if (chdir(CDir) < 0) {
697 crondlog("\311unable to find %s\n", CDir);
703 if ((dir = opendir("."))) {
704 while ((den = readdir(dir))) {
705 if (strchr(den->d_name, '.') != NULL)
707 if (getpwnam(den->d_name))
708 SynchronizeFile(den->d_name);
710 crondlog("\007ignoring %s\n", den->d_name);
714 crondlog("\311Unable to open current dir!\n");
721 * DeleteFile() - delete user database
723 * Note: multiple entries for same user may exist if we were unable to
724 * completely delete a database due to running processes.
728 DeleteFile(const char *userName)
730 CronFile **pfile = &FileBase;
733 while ((file = *pfile) != NULL) {
734 if (strcmp(userName, file->cf_User) == 0) {
735 CronLine **pline = &file->cf_LineBase;
738 file->cf_Running = 0;
739 file->cf_Deleted = 1;
741 while ((line = *pline) != NULL) {
742 if (line->cl_Pid > 0) {
743 file->cf_Running = 1;
744 pline = &line->cl_Next;
746 *pline = line->cl_Next;
747 free(line->cl_Shell);
751 if (file->cf_Running == 0) {
752 *pfile = file->cf_Next;
756 pfile = &file->cf_Next;
759 pfile = &file->cf_Next;
767 * determine which jobs need to be run. Under normal conditions, the
768 * period is about a minute (one scan). Worst case it will be one
773 TestJobs(time_t t1, time_t t2)
779 * Find jobs > t1 and <= t2
782 for (t = t1 - t1 % 60; t <= t2; t += 60) {
784 struct tm *tp = localtime(&t);
788 for (file = FileBase; file; file = file->cf_Next) {
789 #ifdef FEATURE_DEBUG_OPT
791 crondlog("\005FILE %s:\n", file->cf_User);
793 if (file->cf_Deleted)
795 for (line = file->cf_LineBase; line; line = line->cl_Next) {
796 #ifdef FEATURE_DEBUG_OPT
798 crondlog("\005 LINE %s\n", line->cl_Shell);
800 if (line->cl_Mins[tp->tm_min] &&
801 line->cl_Hrs[tp->tm_hour] &&
802 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
803 line->cl_Mons[tp->tm_mon]
805 #ifdef FEATURE_DEBUG_OPT
807 crondlog("\005 JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
809 if (line->cl_Pid > 0) {
810 crondlog("\010 process already running: %s %s\n",
814 } else if (line->cl_Pid == 0) {
833 for (file = FileBase; file; file = file->cf_Next) {
834 if (file->cf_Ready) {
837 for (line = file->cf_LineBase; line; line = line->cl_Next) {
838 if (line->cl_Pid < 0) {
840 RunJob(file->cf_User, line);
842 crondlog("\010USER %s pid %3d cmd %s\n",
847 if (line->cl_Pid < 0)
849 else if (line->cl_Pid > 0)
850 file->cf_Running = 1;
858 * CheckJobs() - check for job completion
860 * Check for job completion, return number of jobs still running after
869 int nStillRunning = 0;
871 for (file = FileBase; file; file = file->cf_Next) {
872 if (file->cf_Running) {
873 file->cf_Running = 0;
875 for (line = file->cf_LineBase; line; line = line->cl_Next) {
876 if (line->cl_Pid > 0) {
878 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
880 if (r < 0 || r == line->cl_Pid) {
881 EndJob(file->cf_User, line);
883 file->cf_Running = 1;
885 file->cf_Running = 1;
890 nStillRunning += file->cf_Running;
892 return(nStillRunning);
896 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
898 ForkJob(const char *user, CronLine *line, int mailFd,
899 const char *prog, const char *cmd, const char *arg, const char *mailf)
902 * Fork as the user in question and run program
913 * Change running state to the user in question
916 if (ChangeUser(user) < 0)
919 #ifdef FEATURE_DEBUG_OPT
921 crondlog("\005Child Running %s\n", prog);
925 dup2(mailFd, mailf != NULL);
926 dup2((mailf ? mailFd : 1), 2);
929 execl(prog, prog, cmd, arg, NULL);
930 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user,
933 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
935 } else if (pid < 0) {
939 crondlog("\024couldn't fork, user %s\n", user);
945 * PARENT, FORK SUCCESS
947 * rename mail-file based on pid of process
951 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
953 rename(mailf, mailFile2);
956 * Close the mail file descriptor.. we can't just leave it open in
957 * a structure, closing it later, because we might run out of descriptors
965 RunJob(const char *user, CronLine *line)
971 line->cl_MailFlag = 0;
974 * open mail file - owner root so nobody can screw with it.
977 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
979 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
982 line->cl_MailFlag = 1;
983 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
985 line->cl_MailPos = lseek(mailFd, 0, 1);
987 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n",
991 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
995 * EndJob - called when job terminates and when mail terminates
999 EndJob(const char *user, CronLine *line)
1009 if (line->cl_Pid <= 0) {
1015 * End of job and no mail file
1016 * End of sendmail job
1019 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1020 user, line->cl_Pid);
1023 if (line->cl_MailFlag != 1)
1026 line->cl_MailFlag = 0;
1029 * End of primary job - check for mail file. If size has increased and
1030 * the file is still valid, we sendmail it.
1033 mailFd = open(mailFile, O_RDONLY);
1039 if (fstat(mailFd, &sbuf) < 0 ||
1040 sbuf.st_uid != DaemonUid ||
1041 sbuf.st_nlink != 0 ||
1042 sbuf.st_size == line->cl_MailPos ||
1043 !S_ISREG(sbuf.st_mode)
1048 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1051 /* crond whithout sendmail */
1054 RunJob(const char *user, CronLine *line)
1057 * Fork as the user in question and run program
1067 * Change running state to the user in question
1070 if (ChangeUser(user) < 0)
1073 #ifdef FEATURE_DEBUG_OPT
1075 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1078 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1079 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1080 DEFAULT_SHELL, line->cl_Shell);
1082 } else if (pid < 0) {
1086 crondlog("\024couldn't fork, user %s\n", user);
1091 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */