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;
140 #if ENABLE_DEBUG_CROND_OPTION
143 opt_complementary = "f-b:b-f:S-L:L-S:d-l";
145 opt_complementary = "f-b:b-f:S-L:L-S";
148 opterr = 0; /* disable getopt 'errors' message. */
149 opt = getopt32(ac, av, "l:L:fbSc:"
150 #if ENABLE_DEBUG_CROND_OPTION
153 , &lopt, &Lopt, &copt
154 #if ENABLE_DEBUG_CROND_OPTION
159 LogLevel = xatou(lopt);
171 #if ENABLE_DEBUG_CROND_OPTION
173 DebugOpt = xatou(dopt);
183 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
184 * version - his died. ;(
187 * close stdin and stdout, stderr.
188 * close unused descriptors - don't need.
189 * optional detach from controlling terminal
195 vfork_daemon_rexec(1, 0, av);
201 (void) startlogger(); /* need if syslog mode selected */
204 * main loop - synchronize to 1 second after the minute, minimum sleep
208 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
209 applet_name, LogLevel);
214 time_t t1 = time(NULL);
218 short sleep_time = 60;
221 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
227 * The file 'cron.update' is checked to determine new cron
228 * jobs. The directory is rescanned once an hour to deal
231 * check for disparity. Disparities over an hour either way
232 * result in resynchronization. A reverse-indexed disparity
233 * less then an hour causes us to effectively sleep until we
234 * match the original time (i.e. no re-execution of jobs that
235 * have just been run). A forward-indexed disparity less then
236 * an hour causes intermediate jobs to be run, but only once
239 * when running jobs, the inequality used is greater but not
240 * equal to t1, and less then or equal to t2.
248 #if ENABLE_DEBUG_CROND_OPTION
250 crondlog("\005Wakeup dt=%d\n", dt);
252 if (dt < -60 * 60 || dt > 60 * 60) {
254 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
259 if (CheckJobs() > 0) {
268 return 0; /* not reached */
271 static int ChangeUser(const char *user)
277 * Obtain password entry and change privileges
279 pas = getpwnam(user);
281 crondlog("\011failed to get uid for %s", user);
284 setenv("USER", pas->pw_name, 1);
285 setenv("HOME", pas->pw_dir, 1);
286 setenv("SHELL", DEFAULT_SHELL, 1);
289 * Change running state to the user in question
291 err_msg = change_identity_e2str(pas);
293 crondlog("\011%s for user %s", err_msg, user);
296 if (chdir(pas->pw_dir) < 0) {
297 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
298 if (chdir(TMPDIR) < 0) {
299 crondlog("\011chdir failed: %s: %m", TMPDIR);
306 static void startlogger(void)
309 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
311 #if ENABLE_DEBUG_CROND_OPTION
312 else { /* test logfile */
315 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
318 bb_perror_msg("failed to open log file '%s': ", LogFile);
325 static const char *const DowAry[] = {
344 static const char *const MonAry[] = {
373 static char *ParseField(char *user, char *ary, int modvalue, int off,
374 const char *const *names, char *ptr)
384 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
387 /* Handle numeric digit or symbol or '*' */
390 n1 = 0; /* everything will be filled */
394 } else if (*ptr >= '0' && *ptr <= '9') {
396 n1 = strtol(ptr, &ptr, 10) + off;
398 n2 = strtol(ptr, &ptr, 10) + off;
404 for (i = 0; names[i]; ++i) {
405 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
410 ptr += strlen(names[i]);
420 /* handle optional range '-' */
423 crondlog("\111failed user %s parsing %s\n", user, base);
426 if (*ptr == '-' && n2 < 0) {
432 * collapse single-value ranges, handle skipmark, and fill
433 * in the character array appropriately.
440 skip = strtol(ptr + 1, &ptr, 10);
443 * fill array, using a failsafe is the easiest way to prevent
453 n1 = (n1 + 1) % modvalue;
456 ary[n1 % modvalue] = 1;
460 while (n1 != n2 && --failsafe);
463 crondlog("\111failed user %s parsing %s\n", user, base);
475 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
476 crondlog("\111failed user %s parsing %s\n", user, base);
480 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
483 #if ENABLE_DEBUG_CROND_OPTION
487 for (i = 0; i < modvalue; ++i) {
488 crondlog("\005%d", ary[i]);
497 static void FixDayDow(CronLine * line)
503 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
504 if (line->cl_Dow[i] == 0) {
509 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
510 if (line->cl_Days[i] == 0) {
515 if (weekUsed && !daysUsed) {
516 memset(line->cl_Days, 0, sizeof(line->cl_Days));
518 if (daysUsed && !weekUsed) {
519 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
525 static void SynchronizeFile(const char *fileName)
527 int maxEntries = MAXLINES;
531 if (strcmp(fileName, "root") == 0) {
534 maxLines = maxEntries * 10;
539 DeleteFile(fileName);
541 fi = fopen(fileName, "r");
545 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
546 CronFile *file = xzalloc(sizeof(CronFile));
549 file->cf_User = strdup(fileName);
550 pline = &file->cf_LineBase;
552 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
557 if (buf[0] == 0 || buf[0] == '#') {
560 if (--maxEntries == 0) {
563 memset(&line, 0, sizeof(line));
565 #if ENABLE_DEBUG_CROND_OPTION
567 crondlog("\111User %s Entry %s\n", fileName, buf);
571 /* parse date ranges */
572 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
573 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
574 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
575 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
576 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
584 * fix days and dow - if one is not * and the other
585 * is *, the other is set to 0, and vise-versa
590 *pline = xzalloc(sizeof(CronLine));
594 (*pline)->cl_Shell = strdup(ptr);
596 #if ENABLE_DEBUG_CROND_OPTION
598 crondlog("\111 Command %s\n", ptr);
602 pline = &((*pline)->cl_Next);
606 file->cf_Next = FileBase;
609 if (maxLines == 0 || maxEntries == 0) {
610 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
618 static void CheckUpdates(void)
623 fi = fopen(CRONUPDATE, "r");
626 while (fgets(buf, sizeof(buf), fi) != NULL) {
627 SynchronizeFile(strtok(buf, " \t\r\n"));
633 static void SynchronizeDir(void)
635 /* Attempt to delete the database. */
640 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
644 DeleteFile(file->cf_User);
648 * Remove cron update file
650 * Re-chdir, in case directory was renamed & deleted, or otherwise
653 * scan directory and add associated users
657 if (chdir(CDir) < 0) {
658 crondlog("\311cannot find %s\n", CDir);
661 DIR *dir = opendir(".");
665 while ((den = readdir(dir))) {
666 if (strchr(den->d_name, '.') != NULL) {
669 if (getpwnam(den->d_name)) {
670 SynchronizeFile(den->d_name);
672 crondlog("\007ignoring %s\n", den->d_name);
677 crondlog("\311cannot open current dir!\n");
684 * DeleteFile() - delete user database
686 * Note: multiple entries for same user may exist if we were unable to
687 * completely delete a database due to running processes.
690 static void DeleteFile(const char *userName)
692 CronFile **pfile = &FileBase;
695 while ((file = *pfile) != NULL) {
696 if (strcmp(userName, file->cf_User) == 0) {
697 CronLine **pline = &file->cf_LineBase;
700 file->cf_Running = 0;
701 file->cf_Deleted = 1;
703 while ((line = *pline) != NULL) {
704 if (line->cl_Pid > 0) {
705 file->cf_Running = 1;
706 pline = &line->cl_Next;
708 *pline = line->cl_Next;
709 free(line->cl_Shell);
713 if (file->cf_Running == 0) {
714 *pfile = file->cf_Next;
718 pfile = &file->cf_Next;
721 pfile = &file->cf_Next;
729 * determine which jobs need to be run. Under normal conditions, the
730 * period is about a minute (one scan). Worst case it will be one
734 static int TestJobs(time_t t1, time_t t2)
739 /* Find jobs > t1 and <= t2 */
741 for (t = t1 - t1 % 60; t <= t2; t += 60) {
743 struct tm *tp = localtime(&t);
747 for (file = FileBase; file; file = file->cf_Next) {
748 #if ENABLE_DEBUG_CROND_OPTION
750 crondlog("\005FILE %s:\n", file->cf_User);
752 if (file->cf_Deleted)
754 for (line = file->cf_LineBase; line; line = line->cl_Next) {
755 #if ENABLE_DEBUG_CROND_OPTION
757 crondlog("\005 LINE %s\n", line->cl_Shell);
759 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
760 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
761 && line->cl_Mons[tp->tm_mon]) {
762 #if ENABLE_DEBUG_CROND_OPTION
764 crondlog("\005 JobToDo: %d %s\n",
765 line->cl_Pid, line->cl_Shell);
768 if (line->cl_Pid > 0) {
769 crondlog("\010 process already running: %s %s\n",
770 file->cf_User, line->cl_Shell);
771 } else if (line->cl_Pid == 0) {
784 static void RunJobs(void)
789 for (file = FileBase; file; file = file->cf_Next) {
790 if (file->cf_Ready) {
793 for (line = file->cf_LineBase; line; line = line->cl_Next) {
794 if (line->cl_Pid < 0) {
796 RunJob(file->cf_User, line);
798 crondlog("\010USER %s pid %3d cmd %s\n",
799 file->cf_User, line->cl_Pid, line->cl_Shell);
800 if (line->cl_Pid < 0) {
803 else if (line->cl_Pid > 0) {
804 file->cf_Running = 1;
813 * CheckJobs() - check for job completion
815 * Check for job completion, return number of jobs still running after
819 static int CheckJobs(void)
823 int nStillRunning = 0;
825 for (file = FileBase; file; file = file->cf_Next) {
826 if (file->cf_Running) {
827 file->cf_Running = 0;
829 for (line = file->cf_LineBase; line; line = line->cl_Next) {
830 if (line->cl_Pid > 0) {
832 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
834 if (r < 0 || r == line->cl_Pid) {
835 EndJob(file->cf_User, line);
837 file->cf_Running = 1;
840 file->cf_Running = 1;
845 nStillRunning += file->cf_Running;
847 return nStillRunning;
851 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
853 ForkJob(const char *user, CronLine * line, int mailFd,
854 const char *prog, const char *cmd, const char *arg, const char *mailf)
856 /* Fork as the user in question and run program */
863 /* Change running state to the user in question */
865 if (ChangeUser(user) < 0) {
868 #if ENABLE_DEBUG_CROND_OPTION
870 crondlog("\005Child Running %s\n", prog);
875 dup2(mailFd, mailf != NULL);
876 dup2((mailf ? mailFd : 1), 2);
879 execl(prog, prog, cmd, arg, NULL);
880 crondlog("\024cannot exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
882 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
885 } else if (pid < 0) {
887 crondlog("\024cannot fork, user %s\n", user);
893 /* PARENT, FORK SUCCESS
894 * rename mail-file based on pid of process
898 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
899 rename(mailf, mailFile2);
902 * Close the mail file descriptor.. we can't just leave it open in
903 * a structure, closing it later, because we might run out of descriptors
911 static void RunJob(const char *user, CronLine * line)
917 line->cl_MailFlag = 0;
919 /* open mail file - owner root so nobody can screw with it. */
921 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
922 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
925 line->cl_MailFlag = 1;
926 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
928 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
930 crondlog("\024cannot create mail file user %s file %s, output to /dev/null\n", user, mailFile);
933 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
937 * EndJob - called when job terminates and when mail terminates
940 static void EndJob(const char *user, CronLine * line)
948 if (line->cl_Pid <= 0) {
954 * End of job and no mail file
955 * End of sendmail job
958 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
961 if (line->cl_MailFlag != 1) {
964 line->cl_MailFlag = 0;
967 * End of primary job - check for mail file. If size has increased and
968 * the file is still valid, we sendmail it.
971 mailFd = open(mailFile, O_RDONLY);
977 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
978 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
982 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
985 /* crond without sendmail */
987 static void RunJob(const char *user, CronLine * line)
989 /* Fork as the user in question and run program */
995 /* Change running state to the user in question */
997 if (ChangeUser(user) < 0) {
1000 #if ENABLE_DEBUG_CROND_OPTION
1002 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1006 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1007 crondlog("\024cannot exec, user %s cmd %s -c %s\n", user,
1008 DEFAULT_SHELL, line->cl_Shell);
1010 } else if (pid < 0) {
1012 crondlog("\024cannot, user %s\n", user);
1017 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */