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"
16 #include <sys/syslog.h>
18 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
21 #define CRONTABS "/var/spool/cron/crontabs"
24 #define TMPDIR "/var/spool/cron"
27 #define SENDMAIL "/usr/sbin/sendmail"
30 #define SENDMAIL_ARGS "-ti", "oem"
33 #define CRONUPDATE "cron.update"
36 #define MAXLINES 256 /* max lines in non-root crontabs */
39 typedef struct CronFile {
40 struct CronFile *cf_Next;
41 struct CronLine *cf_LineBase;
42 char *cf_User; /* username */
43 int cf_Ready; /* bool: one or more jobs ready */
44 int cf_Running; /* bool: one or more jobs running */
45 int cf_Deleted; /* marked for deletion, ignore */
48 typedef struct CronLine {
49 struct CronLine *cl_Next;
50 char *cl_Shell; /* shell command */
51 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
52 int cl_MailFlag; /* running pid is for mail */
53 int cl_MailPos; /* 'empty file' size */
54 char cl_Mins[60]; /* 0-59 */
55 char cl_Hrs[24]; /* 0-23 */
56 char cl_Days[32]; /* 1-31 */
57 char cl_Mons[12]; /* 0-11 */
58 char cl_Dow[7]; /* 0-6, beginning sunday */
67 #if ENABLE_DEBUG_CROND_OPTION
68 static unsigned DebugOpt;
71 static unsigned LogLevel = 8;
72 static const char *LogFile;
73 static const char *CDir = CRONTABS;
75 static void startlogger(void);
77 static void CheckUpdates(void);
78 static void SynchronizeDir(void);
79 static int TestJobs(time_t t1, time_t t2);
80 static void RunJobs(void);
81 static int CheckJobs(void);
83 static void RunJob(const char *user, CronLine * line);
85 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
86 static void EndJob(const char *user, CronLine * line);
88 #define EndJob(user, line) line->cl_Pid = 0
91 static void DeleteFile(const char *userName);
93 static CronFile *FileBase;
96 static void crondlog(const char *ctl, ...)
100 int level = (int) (ctl[0] & 0xf);
101 int type = level == 20 ?
102 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
107 if (level >= LogLevel) {
109 #if ENABLE_DEBUG_CROND_OPTION
111 vfprintf(stderr, fmt, va);
115 vsyslog(type, fmt, va);
117 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
119 vdprintf(logfd, fmt, va);
121 #if ENABLE_DEBUG_CROND_OPTION
123 bb_perror_msg("can't open log file");
134 int crond_main(int ac, char **av);
135 int crond_main(int ac, char **av)
138 char *lopt, *Lopt, *copt;
139 USE_DEBUG_CROND_OPTION(char *dopt;)
141 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l");
142 opterr = 0; /* disable getopt 'errors' message. */
143 opt = getopt32(ac, av, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
144 &lopt, &Lopt, &copt USE_DEBUG_CROND_OPTION(, &dopt));
145 if (opt & 1) /* -l */
146 LogLevel = xatou(lopt);
147 if (opt & 2) /* -L */
150 if (opt & 32) /* -c */
153 #if ENABLE_DEBUG_CROND_OPTION
154 if (opt & 64) { /* -d */
155 DebugOpt = xatou(dopt);
160 /* close stdin and stdout, stderr.
161 * close unused descriptors - don't need.
162 * optional detach from controlling terminal
165 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, av);
168 signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
170 startlogger(); /* need if syslog mode selected */
173 * main loop - synchronize to 1 second after the minute, minimum sleep
176 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
177 applet_name, LogLevel);
182 time_t t1 = time(NULL);
186 short sleep_time = 60;
189 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
195 * The file 'cron.update' is checked to determine new cron
196 * jobs. The directory is rescanned once an hour to deal
199 * check for disparity. Disparities over an hour either way
200 * result in resynchronization. A reverse-indexed disparity
201 * less then an hour causes us to effectively sleep until we
202 * match the original time (i.e. no re-execution of jobs that
203 * have just been run). A forward-indexed disparity less then
204 * an hour causes intermediate jobs to be run, but only once
207 * when running jobs, the inequality used is greater but not
208 * equal to t1, and less then or equal to t2.
216 #if ENABLE_DEBUG_CROND_OPTION
218 crondlog("\005Wakeup dt=%d\n", dt);
220 if (dt < -60 * 60 || dt > 60 * 60) {
222 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
227 if (CheckJobs() > 0) {
236 return 0; /* not reached */
239 static int ChangeUser(const char *user)
245 * Obtain password entry and change privileges
247 pas = getpwnam(user);
249 crondlog("\011failed to get uid for %s", user);
252 setenv("USER", pas->pw_name, 1);
253 setenv("HOME", pas->pw_dir, 1);
254 setenv("SHELL", DEFAULT_SHELL, 1);
257 * Change running state to the user in question
259 err_msg = change_identity_e2str(pas);
261 crondlog("\011%s for user %s", err_msg, user);
264 if (chdir(pas->pw_dir) < 0) {
265 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
266 if (chdir(TMPDIR) < 0) {
267 crondlog("\011chdir failed: %s: %m", TMPDIR);
274 static void startlogger(void)
277 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
279 #if ENABLE_DEBUG_CROND_OPTION
280 else { /* test logfile */
283 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
286 bb_perror_msg("failed to open log file '%s': ", LogFile);
293 static const char *const DowAry[] = {
312 static const char *const MonAry[] = {
341 static char *ParseField(char *user, char *ary, int modvalue, int off,
342 const char *const *names, char *ptr)
352 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
355 /* Handle numeric digit or symbol or '*' */
358 n1 = 0; /* everything will be filled */
362 } else if (*ptr >= '0' && *ptr <= '9') {
364 n1 = strtol(ptr, &ptr, 10) + off;
366 n2 = strtol(ptr, &ptr, 10) + off;
372 for (i = 0; names[i]; ++i) {
373 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
378 ptr += strlen(names[i]);
388 /* handle optional range '-' */
391 crondlog("\111failed user %s parsing %s\n", user, base);
394 if (*ptr == '-' && n2 < 0) {
400 * collapse single-value ranges, handle skipmark, and fill
401 * in the character array appropriately.
408 skip = strtol(ptr + 1, &ptr, 10);
411 * fill array, using a failsafe is the easiest way to prevent
421 n1 = (n1 + 1) % modvalue;
424 ary[n1 % modvalue] = 1;
428 while (n1 != n2 && --failsafe);
431 crondlog("\111failed user %s parsing %s\n", user, base);
443 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
444 crondlog("\111failed user %s parsing %s\n", user, base);
448 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
451 #if ENABLE_DEBUG_CROND_OPTION
455 for (i = 0; i < modvalue; ++i) {
456 crondlog("\005%d", ary[i]);
465 static void FixDayDow(CronLine * line)
471 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
472 if (line->cl_Dow[i] == 0) {
477 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
478 if (line->cl_Days[i] == 0) {
483 if (weekUsed && !daysUsed) {
484 memset(line->cl_Days, 0, sizeof(line->cl_Days));
486 if (daysUsed && !weekUsed) {
487 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
493 static void SynchronizeFile(const char *fileName)
495 int maxEntries = MAXLINES;
499 if (strcmp(fileName, "root") == 0) {
502 maxLines = maxEntries * 10;
507 DeleteFile(fileName);
509 fi = fopen(fileName, "r");
513 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
514 CronFile *file = xzalloc(sizeof(CronFile));
517 file->cf_User = strdup(fileName);
518 pline = &file->cf_LineBase;
520 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
525 if (buf[0] == 0 || buf[0] == '#') {
528 if (--maxEntries == 0) {
531 memset(&line, 0, sizeof(line));
533 #if ENABLE_DEBUG_CROND_OPTION
535 crondlog("\111User %s Entry %s\n", fileName, buf);
539 /* parse date ranges */
540 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
541 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
542 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
543 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
544 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
552 * fix days and dow - if one is not * and the other
553 * is *, the other is set to 0, and vise-versa
558 *pline = xzalloc(sizeof(CronLine));
562 (*pline)->cl_Shell = strdup(ptr);
564 #if ENABLE_DEBUG_CROND_OPTION
566 crondlog("\111 Command %s\n", ptr);
570 pline = &((*pline)->cl_Next);
574 file->cf_Next = FileBase;
577 if (maxLines == 0 || maxEntries == 0) {
578 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
586 static void CheckUpdates(void)
591 fi = fopen(CRONUPDATE, "r");
594 while (fgets(buf, sizeof(buf), fi) != NULL) {
595 SynchronizeFile(strtok(buf, " \t\r\n"));
601 static void SynchronizeDir(void)
603 /* Attempt to delete the database. */
608 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
612 DeleteFile(file->cf_User);
616 * Remove cron update file
618 * Re-chdir, in case directory was renamed & deleted, or otherwise
621 * scan directory and add associated users
625 if (chdir(CDir) < 0) {
626 crondlog("\311cannot find %s\n", CDir);
629 DIR *dir = opendir(".");
633 while ((den = readdir(dir))) {
634 if (strchr(den->d_name, '.') != NULL) {
637 if (getpwnam(den->d_name)) {
638 SynchronizeFile(den->d_name);
640 crondlog("\007ignoring %s\n", den->d_name);
645 crondlog("\311cannot open current dir!\n");
652 * DeleteFile() - delete user database
654 * Note: multiple entries for same user may exist if we were unable to
655 * completely delete a database due to running processes.
658 static void DeleteFile(const char *userName)
660 CronFile **pfile = &FileBase;
663 while ((file = *pfile) != NULL) {
664 if (strcmp(userName, file->cf_User) == 0) {
665 CronLine **pline = &file->cf_LineBase;
668 file->cf_Running = 0;
669 file->cf_Deleted = 1;
671 while ((line = *pline) != NULL) {
672 if (line->cl_Pid > 0) {
673 file->cf_Running = 1;
674 pline = &line->cl_Next;
676 *pline = line->cl_Next;
677 free(line->cl_Shell);
681 if (file->cf_Running == 0) {
682 *pfile = file->cf_Next;
686 pfile = &file->cf_Next;
689 pfile = &file->cf_Next;
697 * determine which jobs need to be run. Under normal conditions, the
698 * period is about a minute (one scan). Worst case it will be one
702 static int TestJobs(time_t t1, time_t t2)
707 /* Find jobs > t1 and <= t2 */
709 for (t = t1 - t1 % 60; t <= t2; t += 60) {
711 struct tm *tp = localtime(&t);
715 for (file = FileBase; file; file = file->cf_Next) {
716 #if ENABLE_DEBUG_CROND_OPTION
718 crondlog("\005FILE %s:\n", file->cf_User);
720 if (file->cf_Deleted)
722 for (line = file->cf_LineBase; line; line = line->cl_Next) {
723 #if ENABLE_DEBUG_CROND_OPTION
725 crondlog("\005 LINE %s\n", line->cl_Shell);
727 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
728 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
729 && line->cl_Mons[tp->tm_mon]) {
730 #if ENABLE_DEBUG_CROND_OPTION
732 crondlog("\005 JobToDo: %d %s\n",
733 line->cl_Pid, line->cl_Shell);
736 if (line->cl_Pid > 0) {
737 crondlog("\010 process already running: %s %s\n",
738 file->cf_User, line->cl_Shell);
739 } else if (line->cl_Pid == 0) {
752 static void RunJobs(void)
757 for (file = FileBase; file; file = file->cf_Next) {
758 if (file->cf_Ready) {
761 for (line = file->cf_LineBase; line; line = line->cl_Next) {
762 if (line->cl_Pid < 0) {
764 RunJob(file->cf_User, line);
766 crondlog("\010USER %s pid %3d cmd %s\n",
767 file->cf_User, line->cl_Pid, line->cl_Shell);
768 if (line->cl_Pid < 0) {
771 else if (line->cl_Pid > 0) {
772 file->cf_Running = 1;
781 * CheckJobs() - check for job completion
783 * Check for job completion, return number of jobs still running after
787 static int CheckJobs(void)
791 int nStillRunning = 0;
793 for (file = FileBase; file; file = file->cf_Next) {
794 if (file->cf_Running) {
795 file->cf_Running = 0;
797 for (line = file->cf_LineBase; line; line = line->cl_Next) {
798 if (line->cl_Pid > 0) {
800 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
802 if (r < 0 || r == line->cl_Pid) {
803 EndJob(file->cf_User, line);
805 file->cf_Running = 1;
808 file->cf_Running = 1;
813 nStillRunning += file->cf_Running;
815 return nStillRunning;
819 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
821 ForkJob(const char *user, CronLine * line, int mailFd,
822 const char *prog, const char *cmd, const char *arg, const char *mailf)
824 /* Fork as the user in question and run program */
831 /* Change running state to the user in question */
833 if (ChangeUser(user) < 0) {
836 #if ENABLE_DEBUG_CROND_OPTION
838 crondlog("\005Child Running %s\n", prog);
843 dup2(mailFd, mailf != NULL);
844 dup2((mailf ? mailFd : 1), 2);
847 execl(prog, prog, cmd, arg, NULL);
848 crondlog("\024cannot exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
850 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
853 } else if (pid < 0) {
855 crondlog("\024cannot fork, user %s\n", user);
861 /* PARENT, FORK SUCCESS
862 * rename mail-file based on pid of process
866 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
867 rename(mailf, mailFile2);
870 * Close the mail file descriptor.. we can't just leave it open in
871 * a structure, closing it later, because we might run out of descriptors
879 static void RunJob(const char *user, CronLine * line)
885 line->cl_MailFlag = 0;
887 /* open mail file - owner root so nobody can screw with it. */
889 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
890 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
893 line->cl_MailFlag = 1;
894 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
896 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
898 crondlog("\024cannot create mail file user %s file %s, output to /dev/null\n", user, mailFile);
901 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
905 * EndJob - called when job terminates and when mail terminates
908 static void EndJob(const char *user, CronLine * line)
916 if (line->cl_Pid <= 0) {
922 * End of job and no mail file
923 * End of sendmail job
926 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
929 if (line->cl_MailFlag != 1) {
932 line->cl_MailFlag = 0;
935 * End of primary job - check for mail file. If size has increased and
936 * the file is still valid, we sendmail it.
939 mailFd = open(mailFile, O_RDONLY);
945 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
946 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
950 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
953 /* crond without sendmail */
955 static void RunJob(const char *user, CronLine * line)
957 /* Fork as the user in question and run program */
963 /* Change running state to the user in question */
965 if (ChangeUser(user) < 0) {
968 #if ENABLE_DEBUG_CROND_OPTION
970 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
974 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
975 crondlog("\024cannot exec, user %s cmd %s -c %s\n", user,
976 DEFAULT_SHELL, line->cl_Shell);
978 } else if (pid < 0) {
980 crondlog("\024cannot, user %s\n", user);
985 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */