1 /* vi: set sw=4 ts=4: */
3 * crond -d[#] -c <crondir> -f -b
5 * run as root, but NOT setuid root
7 * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com)
8 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
10 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
13 #define VERSION "2.3.2"
15 #undef FEATURE_DEBUG_OPT
30 #include <sys/ioctl.h>
33 #include <sys/resource.h>
37 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
40 #define CRONTABS "/var/spool/cron/crontabs"
43 #define TMPDIR "/var/spool/cron"
46 #define SENDMAIL "/usr/sbin/sendmail"
49 #define SENDMAIL_ARGS "-ti", "oem"
52 #define CRONUPDATE "cron.update"
55 #define MAXLINES 256 /* max lines in non-root crontabs */
58 typedef struct CronFile {
59 struct CronFile *cf_Next;
60 struct CronLine *cf_LineBase;
61 char *cf_User; /* username */
62 int cf_Ready; /* bool: one or more jobs ready */
63 int cf_Running; /* bool: one or more jobs running */
64 int cf_Deleted; /* marked for deletion, ignore */
67 typedef struct CronLine {
68 struct CronLine *cl_Next;
69 char *cl_Shell; /* shell command */
70 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
71 int cl_MailFlag; /* running pid is for mail */
72 int cl_MailPos; /* 'empty file' size */
73 char cl_Mins[60]; /* 0-59 */
74 char cl_Hrs[24]; /* 0-23 */
75 char cl_Days[32]; /* 1-31 */
76 char cl_Mons[12]; /* 0-11 */
77 char cl_Dow[7]; /* 0-6, beginning sunday */
86 #ifdef FEATURE_DEBUG_OPT
87 static short DebugOpt;
90 static short LogLevel = 8;
91 static const char *LogFile;
92 static const char *CDir = CRONTABS;
94 static void startlogger(void);
96 static void CheckUpdates(void);
97 static void SynchronizeDir(void);
98 static int TestJobs(time_t t1, time_t t2);
99 static void RunJobs(void);
100 static int CheckJobs(void);
102 static void RunJob(const char *user, CronLine * line);
104 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
105 static void EndJob(const char *user, CronLine * line);
107 #define EndJob(user, line) line->cl_Pid = 0
110 static void DeleteFile(const char *userName);
112 static CronFile *FileBase;
115 static void crondlog(const char *ctl, ...)
119 int level = (int) (ctl[0] & 0xf);
120 int type = level == 20 ?
121 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
126 if (level >= LogLevel) {
128 #ifdef FEATURE_DEBUG_OPT
130 vfprintf(stderr, fmt, va);
134 vsyslog(type, fmt, va);
136 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
138 vdprintf(logfd, fmt, va);
140 #ifdef FEATURE_DEBUG_OPT
142 bb_perror_msg("Can't open log file");
153 int crond_main(int ac, char **av)
156 char *lopt, *Lopt, *copt;
158 #ifdef FEATURE_DEBUG_OPT
161 bb_opt_complementally = "f-b:b-f:S-L:L-S:d-l";
163 bb_opt_complementally = "f-b:b-f:S-L:L-S";
166 opterr = 0; /* disable getopt 'errors' message. */
167 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
168 #ifdef FEATURE_DEBUG_OPT
171 , &lopt, &Lopt, &copt
172 #ifdef FEATURE_DEBUG_OPT
177 LogLevel = atoi(lopt);
189 #ifdef FEATURE_DEBUG_OPT
191 DebugOpt = atoi(dopt);
201 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
202 * version - his died. ;(
205 * close stdin and stdout, stderr.
206 * close unused descriptors - don't need.
207 * optional detach from controlling terminal
211 #if defined(__uClinux__)
212 /* reexec for vfork() do continue parent */
213 vfork_daemon_rexec(1, 0, ac, av, "-f");
219 (void) startlogger(); /* need if syslog mode selected */
222 * main loop - synchronize to 1 second after the minute, minimum sleep
226 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
227 bb_applet_name, LogLevel);
232 time_t t1 = time(NULL);
236 short sleep_time = 60;
239 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
245 * The file 'cron.update' is checked to determine new cron
246 * jobs. The directory is rescanned once an hour to deal
249 * check for disparity. Disparities over an hour either way
250 * result in resynchronization. A reverse-indexed disparity
251 * less then an hour causes us to effectively sleep until we
252 * match the original time (i.e. no re-execution of jobs that
253 * have just been run). A forward-indexed disparity less then
254 * an hour causes intermediate jobs to be run, but only once
257 * when running jobs, the inequality used is greater but not
258 * equal to t1, and less then or equal to t2.
266 #ifdef FEATURE_DEBUG_OPT
268 crondlog("\005Wakeup dt=%d\n", dt);
270 if (dt < -60 * 60 || dt > 60 * 60) {
272 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
277 if (CheckJobs() > 0) {
289 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
293 static void fdprintf(int fd, const char *ctl, ...)
298 vdprintf(fd, ctl, va);
304 static int ChangeUser(const char *user)
310 * Obtain password entry and change privileges
312 pas = getpwnam(user);
314 crondlog("\011failed to get uid for %s", user);
317 setenv("USER", pas->pw_name, 1);
318 setenv("HOME", pas->pw_dir, 1);
319 setenv("SHELL", DEFAULT_SHELL, 1);
322 * Change running state to the user in question
324 err_msg = change_identity_e2str(pas);
326 crondlog("\011%s for user %s", err_msg, user);
329 if (chdir(pas->pw_dir) < 0) {
330 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
331 if (chdir(TMPDIR) < 0) {
332 crondlog("\011chdir failed: %s: %m", TMPDIR);
336 return (pas->pw_uid);
339 static void startlogger(void)
342 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
344 #ifdef FEATURE_DEBUG_OPT
345 else { /* test logfile */
348 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
351 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
358 static const char *const DowAry[] = {
377 static const char *const MonAry[] = {
406 static char *ParseField(char *user, char *ary, int modvalue, int off,
407 const char *const *names, char *ptr)
417 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
420 /* Handle numeric digit or symbol or '*' */
423 n1 = 0; /* everything will be filled */
427 } else if (*ptr >= '0' && *ptr <= '9') {
429 n1 = strtol(ptr, &ptr, 10) + off;
431 n2 = strtol(ptr, &ptr, 10) + off;
437 for (i = 0; names[i]; ++i) {
438 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
443 ptr += strlen(names[i]);
453 /* handle optional range '-' */
456 crondlog("\111failed user %s parsing %s\n", user, base);
459 if (*ptr == '-' && n2 < 0) {
465 * collapse single-value ranges, handle skipmark, and fill
466 * in the character array appropriately.
473 skip = strtol(ptr + 1, &ptr, 10);
476 * fill array, using a failsafe is the easiest way to prevent
486 n1 = (n1 + 1) % modvalue;
489 ary[n1 % modvalue] = 1;
493 while (n1 != n2 && --failsafe);
496 crondlog("\111failed user %s parsing %s\n", user, base);
508 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
509 crondlog("\111failed user %s parsing %s\n", user, base);
513 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
516 #ifdef FEATURE_DEBUG_OPT
520 for (i = 0; i < modvalue; ++i) {
521 crondlog("\005%d", ary[i]);
530 static void FixDayDow(CronLine * line)
536 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
537 if (line->cl_Dow[i] == 0) {
542 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
543 if (line->cl_Days[i] == 0) {
548 if (weekUsed && !daysUsed) {
549 memset(line->cl_Days, 0, sizeof(line->cl_Days));
551 if (daysUsed && !weekUsed) {
552 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
558 static void SynchronizeFile(const char *fileName)
560 int maxEntries = MAXLINES;
564 if (strcmp(fileName, "root") == 0) {
567 maxLines = maxEntries * 10;
572 DeleteFile(fileName);
574 fi = fopen(fileName, "r");
578 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
579 CronFile *file = calloc(1, sizeof(CronFile));
582 file->cf_User = strdup(fileName);
583 pline = &file->cf_LineBase;
585 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
590 if (buf[0] == 0 || buf[0] == '#') {
593 if (--maxEntries == 0) {
596 memset(&line, 0, sizeof(line));
598 #ifdef FEATURE_DEBUG_OPT
600 crondlog("\111User %s Entry %s\n", fileName, buf);
604 /* parse date ranges */
605 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
606 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
607 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
608 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
609 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
617 * fix days and dow - if one is not * and the other
618 * is *, the other is set to 0, and vise-versa
623 *pline = calloc(1, sizeof(CronLine));
627 (*pline)->cl_Shell = strdup(ptr);
629 #ifdef FEATURE_DEBUG_OPT
631 crondlog("\111 Command %s\n", ptr);
635 pline = &((*pline)->cl_Next);
639 file->cf_Next = FileBase;
642 if (maxLines == 0 || maxEntries == 0) {
643 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
651 static void CheckUpdates(void)
656 fi = fopen(CRONUPDATE, "r");
659 while (fgets(buf, sizeof(buf), fi) != NULL) {
660 SynchronizeFile(strtok(buf, " \t\r\n"));
666 static void SynchronizeDir(void)
668 /* Attempt to delete the database. */
673 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
677 DeleteFile(file->cf_User);
681 * Remove cron update file
683 * Re-chdir, in case directory was renamed & deleted, or otherwise
686 * scan directory and add associated users
690 if (chdir(CDir) < 0) {
691 crondlog("\311unable to find %s\n", CDir);
694 DIR *dir = opendir(".");
698 while ((den = readdir(dir))) {
699 if (strchr(den->d_name, '.') != NULL) {
702 if (getpwnam(den->d_name)) {
703 SynchronizeFile(den->d_name);
705 crondlog("\007ignoring %s\n", den->d_name);
710 crondlog("\311Unable to open current dir!\n");
717 * DeleteFile() - delete user database
719 * Note: multiple entries for same user may exist if we were unable to
720 * completely delete a database due to running processes.
723 static void DeleteFile(const char *userName)
725 CronFile **pfile = &FileBase;
728 while ((file = *pfile) != NULL) {
729 if (strcmp(userName, file->cf_User) == 0) {
730 CronLine **pline = &file->cf_LineBase;
733 file->cf_Running = 0;
734 file->cf_Deleted = 1;
736 while ((line = *pline) != NULL) {
737 if (line->cl_Pid > 0) {
738 file->cf_Running = 1;
739 pline = &line->cl_Next;
741 *pline = line->cl_Next;
742 free(line->cl_Shell);
746 if (file->cf_Running == 0) {
747 *pfile = file->cf_Next;
751 pfile = &file->cf_Next;
754 pfile = &file->cf_Next;
762 * determine which jobs need to be run. Under normal conditions, the
763 * period is about a minute (one scan). Worst case it will be one
767 static int TestJobs(time_t t1, time_t t2)
772 /* Find jobs > t1 and <= t2 */
774 for (t = t1 - t1 % 60; t <= t2; t += 60) {
776 struct tm *tp = localtime(&t);
780 for (file = FileBase; file; file = file->cf_Next) {
781 #ifdef FEATURE_DEBUG_OPT
783 crondlog("\005FILE %s:\n", file->cf_User);
785 if (file->cf_Deleted)
787 for (line = file->cf_LineBase; line; line = line->cl_Next) {
788 #ifdef FEATURE_DEBUG_OPT
790 crondlog("\005 LINE %s\n", line->cl_Shell);
792 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
793 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
794 && line->cl_Mons[tp->tm_mon]) {
795 #ifdef FEATURE_DEBUG_OPT
797 crondlog("\005 JobToDo: %d %s\n",
798 line->cl_Pid, line->cl_Shell);
801 if (line->cl_Pid > 0) {
802 crondlog("\010 process already running: %s %s\n",
803 file->cf_User, line->cl_Shell);
804 } else if (line->cl_Pid == 0) {
817 static void RunJobs(void)
822 for (file = FileBase; file; file = file->cf_Next) {
823 if (file->cf_Ready) {
826 for (line = file->cf_LineBase; line; line = line->cl_Next) {
827 if (line->cl_Pid < 0) {
829 RunJob(file->cf_User, line);
831 crondlog("\010USER %s pid %3d cmd %s\n",
832 file->cf_User, line->cl_Pid, line->cl_Shell);
833 if (line->cl_Pid < 0) {
836 else if (line->cl_Pid > 0) {
837 file->cf_Running = 1;
846 * CheckJobs() - check for job completion
848 * Check for job completion, return number of jobs still running after
852 static int CheckJobs(void)
856 int nStillRunning = 0;
858 for (file = FileBase; file; file = file->cf_Next) {
859 if (file->cf_Running) {
860 file->cf_Running = 0;
862 for (line = file->cf_LineBase; line; line = line->cl_Next) {
863 if (line->cl_Pid > 0) {
865 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
867 if (r < 0 || r == line->cl_Pid) {
868 EndJob(file->cf_User, line);
870 file->cf_Running = 1;
873 file->cf_Running = 1;
878 nStillRunning += file->cf_Running;
880 return (nStillRunning);
884 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
886 ForkJob(const char *user, CronLine * line, int mailFd,
887 const char *prog, const char *cmd, const char *arg, const char *mailf)
889 /* Fork as the user in question and run program */
896 /* Change running state to the user in question */
898 if (ChangeUser(user) < 0) {
901 #ifdef FEATURE_DEBUG_OPT
903 crondlog("\005Child Running %s\n", prog);
908 dup2(mailFd, mailf != NULL);
909 dup2((mailf ? mailFd : 1), 2);
912 execl(prog, prog, cmd, arg, NULL);
913 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
915 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
918 } else if (pid < 0) {
920 crondlog("\024couldn't fork, user %s\n", user);
926 /* PARENT, FORK SUCCESS
927 * rename mail-file based on pid of process
931 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
932 rename(mailf, mailFile2);
935 * Close the mail file descriptor.. we can't just leave it open in
936 * a structure, closing it later, because we might run out of descriptors
944 static void RunJob(const char *user, CronLine * line)
950 line->cl_MailFlag = 0;
952 /* open mail file - owner root so nobody can screw with it. */
954 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
955 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
958 line->cl_MailFlag = 1;
959 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
961 line->cl_MailPos = lseek(mailFd, 0, 1);
963 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
966 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
970 * EndJob - called when job terminates and when mail terminates
973 static void EndJob(const char *user, CronLine * line)
981 if (line->cl_Pid <= 0) {
987 * End of job and no mail file
988 * End of sendmail job
991 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
994 if (line->cl_MailFlag != 1) {
997 line->cl_MailFlag = 0;
1000 * End of primary job - check for mail file. If size has increased and
1001 * the file is still valid, we sendmail it.
1004 mailFd = open(mailFile, O_RDONLY);
1010 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
1011 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
1015 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1018 /* crond without sendmail */
1020 static void RunJob(const char *user, CronLine * line)
1022 /* Fork as the user in question and run program */
1028 /* Change running state to the user in question */
1030 if (ChangeUser(user) < 0) {
1033 #ifdef FEATURE_DEBUG_OPT
1035 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1039 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1040 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1041 DEFAULT_SHELL, line->cl_Shell);
1043 } else if (pid < 0) {
1045 crondlog("\024couldn't fork, user %s\n", user);
1050 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */