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, ...)
117 int level = (int)(ctl[0] & 0xf);
118 int type = level == 20 ?
119 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
123 if (level >= LogLevel) {
125 #ifdef FEATURE_DEBUG_OPT
126 if (DebugOpt) vfprintf(stderr, ctl, va);
129 if (LogFile == 0) vsyslog(type, ctl, va);
133 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0) {
134 vdprintf(logfd, ctl, va);
136 #ifdef FEATURE_DEBUG_OPT
138 bb_perror_msg("Can't open log file");
149 crond_main(int ac, char **av)
152 char *lopt, *Lopt, *copt;
153 #ifdef FEATURE_DEBUG_OPT
155 bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l";
157 bb_opt_complementaly = "f-b:b-f:S-L:L-S";
160 opterr = 0; /* disable getopt 'errors' message.*/
161 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
162 #ifdef FEATURE_DEBUG_OPT
165 , &lopt, &Lopt, &copt
166 #ifdef FEATURE_DEBUG_OPT
171 LogLevel = atoi(lopt);
173 if (*Lopt != 0) LogFile = Lopt;
175 if (*copt != 0) CDir = copt;
177 #ifdef FEATURE_DEBUG_OPT
179 DebugOpt = atoi(dopt);
188 if (chdir(CDir) != 0)
189 bb_perror_msg_and_die("%s", CDir);
191 signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original
192 * version - his died. ;(
195 * close stdin and stdout, stderr.
196 * close unused descriptors - don't need.
197 * optional detach from controlling terminal
201 if(daemon(1, 0) < 0) {
202 bb_perror_msg_and_die("daemon");
204 #if defined(__uClinux__)
206 /* reexec for vfork() do continue parent */
207 vfork_daemon_rexec(ac, av, "-f");
212 (void)startlogger(); /* need if syslog mode selected */
215 * main loop - synchronize to 1 second after the minute, minimum sleep
219 crondlog("\011%s " VERSION " dillon, started, log level %d\n", bb_applet_name,
225 time_t t1 = time(NULL);
229 short sleep_time = 60;
232 sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time));
238 * The file 'cron.update' is checked to determine new cron
239 * jobs. The directory is rescanned once an hour to deal
242 * check for disparity. Disparities over an hour either way
243 * result in resynchronization. A reverse-indexed disparity
244 * less then an hour causes us to effectively sleep until we
245 * match the original time (i.e. no re-execution of jobs that
246 * have just been run). A forward-indexed disparity less then
247 * an hour causes intermediate jobs to be run, but only once
250 * when running jobs, the inequality used is greater but not
251 * equal to t1, and less then or equal to t2.
259 #ifdef FEATURE_DEBUG_OPT
261 crondlog("\005Wakeup dt=%d\n", dt);
263 if (dt < -60*60 || dt > 60*60) {
265 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
282 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
287 fdprintf(int fd, const char *ctl, ...)
292 vdprintf(fd, ctl, va);
299 ChangeUser(const char *user)
305 * Obtain password entry and change privilages
308 if ((pas = getpwnam(user)) == 0) {
309 crondlog("\011failed to get uid for %s", user);
312 setenv("USER", pas->pw_name, 1);
313 setenv("HOME", pas->pw_dir, 1);
314 setenv("SHELL", DEFAULT_SHELL, 1);
317 * Change running state to the user in question
319 err_msg = change_identity_e2str(pas);
321 crondlog("\011%s for user %s", err_msg, user);
324 if (chdir(pas->pw_dir) < 0) {
325 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
326 if (chdir(TMPDIR) < 0) {
327 crondlog("\011chdir failed: %s: %m", TMPDIR);
338 openlog(bb_applet_name, LOG_CONS|LOG_PID, LOG_CRON);
339 #ifdef FEATURE_DEBUG_OPT
340 else { /* test logfile */
343 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0)
346 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
352 static const char * const DowAry[] = {
371 static const char * const MonAry[] = {
401 ParseField(char *user, char *ary, int modvalue, int off,
402 const char * const *names, char *ptr)
411 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
415 * Handle numeric digit or symbol or '*'
419 n1 = 0; /* everything will be filled */
423 } else if (*ptr >= '0' && *ptr <= '9') {
425 n1 = strtol(ptr, &ptr, 10) + off;
427 n2 = strtol(ptr, &ptr, 10) + off;
432 for (i = 0; names[i]; ++i) {
433 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
438 ptr += strlen(names[i]);
448 * handle optional range '-'
452 crondlog("\111failed user %s parsing %s\n", user, base);
455 if (*ptr == '-' && n2 < 0) {
461 * collapse single-value ranges, handle skipmark, and fill
462 * in the character array appropriately.
469 skip = strtol(ptr + 1, &ptr, 10);
472 * fill array, using a failsafe is the easiest way to prevent
482 n1 = (n1 + 1) % modvalue;
485 ary[n1 % modvalue] = 1;
488 } while (n1 != n2 && --failsafe);
491 crondlog("\111failed user %s parsing %s\n", user, base);
502 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
503 crondlog("\111failed user %s parsing %s\n", user, base);
507 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
510 #ifdef FEATURE_DEBUG_OPT
514 for (i = 0; i < modvalue; ++i)
515 crondlog("\005%d", ary[i]);
524 FixDayDow(CronLine *line)
530 for (i = 0; i < arysize(line->cl_Dow); ++i) {
531 if (line->cl_Dow[i] == 0) {
536 for (i = 0; i < arysize(line->cl_Days); ++i) {
537 if (line->cl_Days[i] == 0) {
542 if (weekUsed && !daysUsed) {
543 memset(line->cl_Days, 0, sizeof(line->cl_Days));
545 if (daysUsed && !weekUsed) {
546 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
553 SynchronizeFile(const char *fileName)
555 int maxEntries = MAXLINES;
559 if (strcmp(fileName, "root") == 0)
561 maxLines = maxEntries * 10;
566 DeleteFile(fileName);
568 if ((fi = fopen(fileName, "r")) != NULL) {
571 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
572 CronFile *file = calloc(1, sizeof(CronFile));
575 file->cf_User = strdup(fileName);
576 pline = &file->cf_LineBase;
578 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
583 buf[strlen(buf)-1] = 0;
585 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
588 if (--maxEntries == 0)
591 memset(&line, 0, sizeof(line));
593 #ifdef FEATURE_DEBUG_OPT
595 crondlog("\111User %s Entry %s\n", fileName, buf);
602 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
603 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
604 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
605 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
606 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
616 * fix days and dow - if one is not * and the other
617 * is *, the other is set to 0, and vise-versa
622 *pline = calloc(1, sizeof(CronLine));
629 (*pline)->cl_Shell = strdup(ptr);
631 #ifdef FEATURE_DEBUG_OPT
633 crondlog("\111 Command %s\n", ptr);
637 pline = &((*pline)->cl_Next);
641 file->cf_Next = FileBase;
644 if (maxLines == 0 || maxEntries == 0)
645 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
658 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
660 while (fgets(buf, sizeof(buf), fi) != NULL) {
661 SynchronizeFile(strtok(buf, " \t\r\n"));
671 * Attempt to delete the database.
677 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
681 DeleteFile(file->cf_User);
685 * Remove cron update file
687 * Re-chdir, in case directory was renamed & deleted, or otherwise
690 * scan directory and add associated users
694 if (chdir(CDir) < 0) {
695 crondlog("\311unable to find %s\n", CDir);
701 if ((dir = opendir("."))) {
702 while ((den = readdir(dir))) {
703 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);
712 crondlog("\311Unable to open current dir!\n");
719 * DeleteFile() - delete user database
721 * Note: multiple entries for same user may exist if we were unable to
722 * completely delete a database due to running processes.
726 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
771 TestJobs(time_t t1, time_t t2)
777 * Find jobs > t1 and <= t2
780 for (t = t1 - t1 % 60; t <= t2; t += 60) {
782 struct tm *tp = localtime(&t);
786 for (file = FileBase; file; file = file->cf_Next) {
787 #ifdef FEATURE_DEBUG_OPT
789 crondlog("\005FILE %s:\n", file->cf_User);
791 if (file->cf_Deleted)
793 for (line = file->cf_LineBase; line; line = line->cl_Next) {
794 #ifdef FEATURE_DEBUG_OPT
796 crondlog("\005 LINE %s\n", line->cl_Shell);
798 if (line->cl_Mins[tp->tm_min] &&
799 line->cl_Hrs[tp->tm_hour] &&
800 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
801 line->cl_Mons[tp->tm_mon]
803 #ifdef FEATURE_DEBUG_OPT
805 crondlog("\005 JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
807 if (line->cl_Pid > 0) {
808 crondlog("\010 process already running: %s %s\n",
812 } else if (line->cl_Pid == 0) {
831 for (file = FileBase; file; file = file->cf_Next) {
832 if (file->cf_Ready) {
835 for (line = file->cf_LineBase; line; line = line->cl_Next) {
836 if (line->cl_Pid < 0) {
838 RunJob(file->cf_User, line);
840 crondlog("\010USER %s pid %3d cmd %s\n",
845 if (line->cl_Pid < 0)
847 else if (line->cl_Pid > 0)
848 file->cf_Running = 1;
856 * CheckJobs() - check for job completion
858 * Check for job completion, return number of jobs still running after
867 int nStillRunning = 0;
869 for (file = FileBase; file; file = file->cf_Next) {
870 if (file->cf_Running) {
871 file->cf_Running = 0;
873 for (line = file->cf_LineBase; line; line = line->cl_Next) {
874 if (line->cl_Pid > 0) {
876 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
878 if (r < 0 || r == line->cl_Pid) {
879 EndJob(file->cf_User, line);
881 file->cf_Running = 1;
883 file->cf_Running = 1;
888 nStillRunning += file->cf_Running;
890 return(nStillRunning);
894 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
896 ForkJob(const char *user, CronLine *line, int mailFd,
897 const char *prog, const char *cmd, const char *arg, const char *mailf)
900 * Fork as the user in question and run program
911 * Change running state to the user in question
914 if (ChangeUser(user) < 0)
917 #ifdef FEATURE_DEBUG_OPT
919 crondlog("\005Child Running %s\n", prog);
923 dup2(mailFd, mailf != NULL);
924 dup2((mailf ? mailFd : 1), 2);
927 execl(prog, prog, cmd, arg, NULL);
928 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user,
931 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
933 } else if (pid < 0) {
937 crondlog("\024couldn't fork, user %s\n", user);
943 * PARENT, FORK SUCCESS
945 * rename mail-file based on pid of process
949 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
951 rename(mailf, mailFile2);
954 * Close the mail file descriptor.. we can't just leave it open in
955 * a structure, closing it later, because we might run out of descriptors
963 RunJob(const char *user, CronLine *line)
969 line->cl_MailFlag = 0;
972 * open mail file - owner root so nobody can screw with it.
975 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
977 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
980 line->cl_MailFlag = 1;
981 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
983 line->cl_MailPos = lseek(mailFd, 0, 1);
985 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n",
989 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
993 * EndJob - called when job terminates and when mail terminates
997 EndJob(const char *user, CronLine *line)
1007 if (line->cl_Pid <= 0) {
1013 * End of job and no mail file
1014 * End of sendmail job
1017 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1018 user, line->cl_Pid);
1021 if (line->cl_MailFlag != 1)
1024 line->cl_MailFlag = 0;
1027 * End of primary job - check for mail file. If size has increased and
1028 * the file is still valid, we sendmail it.
1031 mailFd = open(mailFile, O_RDONLY);
1037 if (fstat(mailFd, &sbuf) < 0 ||
1038 sbuf.st_uid != DaemonUid ||
1039 sbuf.st_nlink != 0 ||
1040 sbuf.st_size == line->cl_MailPos ||
1041 !S_ISREG(sbuf.st_mode)
1046 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1049 /* crond whithout sendmail */
1052 RunJob(const char *user, CronLine *line)
1055 * Fork as the user in question and run program
1065 * Change running state to the user in question
1068 if (ChangeUser(user) < 0)
1071 #ifdef FEATURE_DEBUG_OPT
1073 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1076 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1077 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1078 DEFAULT_SHELL, line->cl_Shell);
1080 } else if (pid < 0) {
1084 crondlog("\024couldn't fork, user %s\n", user);
1089 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */