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)
9 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
11 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
18 #define CRONTABS "/var/spool/cron/crontabs"
21 #define TMPDIR "/var/spool/cron"
24 #define SENDMAIL "sendmail"
27 #define SENDMAIL_ARGS "-ti", "oem"
30 #define CRONUPDATE "cron.update"
33 #define MAXLINES 256 /* max lines in non-root crontabs */
36 typedef struct CronFile {
37 struct CronFile *cf_Next;
38 struct CronLine *cf_LineBase;
39 char *cf_User; /* username */
40 int cf_Ready; /* bool: one or more jobs ready */
41 int cf_Running; /* bool: one or more jobs running */
42 int cf_Deleted; /* marked for deletion, ignore */
45 typedef struct CronLine {
46 struct CronLine *cl_Next;
47 char *cl_Shell; /* shell command */
48 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
49 int cl_MailFlag; /* running pid is for mail */
50 int cl_MailPos; /* 'empty file' size */
51 char cl_Mins[60]; /* 0-59 */
52 char cl_Hrs[24]; /* 0-23 */
53 char cl_Days[32]; /* 1-31 */
54 char cl_Mons[12]; /* 0-11 */
55 char cl_Dow[7]; /* 0-6, beginning sunday */
64 #if ENABLE_DEBUG_CROND_OPTION
65 static unsigned DebugOpt;
68 static unsigned LogLevel = 8;
69 static const char *LogFile;
70 static const char *CDir = CRONTABS;
72 static void startlogger(void);
74 static void CheckUpdates(void);
75 static void SynchronizeDir(void);
76 static int TestJobs(time_t t1, time_t t2);
77 static void RunJobs(void);
78 static int CheckJobs(void);
80 static void RunJob(const char *user, CronLine * line);
82 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
83 static void EndJob(const char *user, CronLine * line);
85 #define EndJob(user, line) line->cl_Pid = 0
88 static void DeleteFile(const char *userName);
90 static CronFile *FileBase;
93 static void crondlog(const char *ctl, ...)
97 int level = (int) (ctl[0] & 0xf);
98 int type = level == 20 ?
99 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
103 if (level >= LogLevel) {
105 #if ENABLE_DEBUG_CROND_OPTION
107 vfprintf(stderr, fmt, va);
110 if (LogFile == NULL) {
111 vsyslog(type, fmt, va);
113 #if !ENABLE_DEBUG_CROND_OPTION
114 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
116 int logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
119 vdprintf(logfd, fmt, va);
130 int crond_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
131 int crond_main(int ac, char **av)
134 char *lopt, *Lopt, *copt;
135 USE_DEBUG_CROND_OPTION(char *dopt;)
137 opt_complementary = "f-b:b-f:S-L:L-S" USE_DEBUG_CROND_OPTION(":d-l");
138 opterr = 0; /* disable getopt 'errors' message. */
139 opt = getopt32(av, "l:L:fbSc:" USE_DEBUG_CROND_OPTION("d:"),
140 &lopt, &Lopt, &copt USE_DEBUG_CROND_OPTION(, &dopt));
141 if (opt & 1) /* -l */
142 LogLevel = xatou(lopt);
143 if (opt & 2) /* -L */
146 if (opt & 32) /* -c */
149 #if ENABLE_DEBUG_CROND_OPTION
150 if (opt & 64) { /* -d */
151 DebugOpt = xatou(dopt);
156 /* close stdin and stdout, stderr.
157 * close unused descriptors - don't need.
158 * optional detach from controlling terminal
161 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, av);
164 signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
166 startlogger(); /* need if syslog mode selected */
169 * main loop - synchronize to 1 second after the minute, minimum sleep
172 crondlog("\011%s " BB_VER " started, log level %d\n",
173 applet_name, LogLevel);
178 time_t t1 = time(NULL);
182 short sleep_time = 60;
184 write_pidfile("/var/run/crond.pid");
186 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
192 * The file 'cron.update' is checked to determine new cron
193 * jobs. The directory is rescanned once an hour to deal
196 * check for disparity. Disparities over an hour either way
197 * result in resynchronization. A reverse-indexed disparity
198 * less then an hour causes us to effectively sleep until we
199 * match the original time (i.e. no re-execution of jobs that
200 * have just been run). A forward-indexed disparity less then
201 * an hour causes intermediate jobs to be run, but only once
204 * when running jobs, the inequality used is greater but not
205 * equal to t1, and less then or equal to t2.
213 #if ENABLE_DEBUG_CROND_OPTION
215 crondlog("\005Wakeup dt=%d\n", dt);
217 if (dt < -60 * 60 || dt > 60 * 60) {
219 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
224 if (CheckJobs() > 0) {
233 return 0; /* not reached */
236 static int ChangeUser(const char *user)
242 * Obtain password entry and change privileges
244 pas = getpwnam(user);
246 crondlog("\011failed to get uid for %s", user);
249 setenv("USER", pas->pw_name, 1);
250 setenv("HOME", pas->pw_dir, 1);
251 setenv("SHELL", DEFAULT_SHELL, 1);
254 * Change running state to the user in question
256 err_msg = change_identity_e2str(pas);
258 crondlog("\011%s for user %s", err_msg, user);
261 if (chdir(pas->pw_dir) < 0) {
262 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
263 if (chdir(TMPDIR) < 0) {
264 crondlog("\011chdir failed: %s: %m", TMPDIR);
271 static void startlogger(void)
273 if (LogFile == NULL) {
274 openlog(applet_name, LOG_CONS | LOG_PID, LOG_CRON);
276 #if ENABLE_DEBUG_CROND_OPTION
277 else { /* test logfile */
280 logfd = open3_or_warn(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
289 static const char DowAry[] ALIGN1 =
290 "sun""mon""tue""wed""thu""fri""sat"
291 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
294 static const char MonAry[] ALIGN1 =
295 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
296 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
299 static char *ParseField(char *user, char *ary, int modvalue, int off,
300 const char *names, char *ptr)
301 /* 'names' is a pointer to a set of 3-char abbreviations */
311 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
314 /* Handle numeric digit or symbol or '*' */
317 n1 = 0; /* everything will be filled */
321 } else if (*ptr >= '0' && *ptr <= '9') {
323 n1 = strtol(ptr, &ptr, 10) + off;
325 n2 = strtol(ptr, &ptr, 10) + off;
331 for (i = 0; names[i]; i += 3) {
332 /* was using strncmp before... */
333 if (strncasecmp(ptr, &names[i], 3) == 0) {
346 /* handle optional range '-' */
349 crondlog("\111failed user %s parsing %s\n", user, base);
352 if (*ptr == '-' && n2 < 0) {
358 * collapse single-value ranges, handle skipmark, and fill
359 * in the character array appropriately.
366 skip = strtol(ptr + 1, &ptr, 10);
369 * fill array, using a failsafe is the easiest way to prevent
379 n1 = (n1 + 1) % modvalue;
382 ary[n1 % modvalue] = 1;
386 while (n1 != n2 && --failsafe);
389 crondlog("\111failed user %s parsing %s\n", user, base);
401 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
402 crondlog("\111failed user %s parsing %s\n", user, base);
406 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
409 #if ENABLE_DEBUG_CROND_OPTION
413 for (i = 0; i < modvalue; ++i) {
414 crondlog("\005%d", ary[i]);
423 static void FixDayDow(CronLine * line)
429 for (i = 0; i < (int)(ARRAY_SIZE(line->cl_Dow)); ++i) {
430 if (line->cl_Dow[i] == 0) {
435 for (i = 0; i < (int)(ARRAY_SIZE(line->cl_Days)); ++i) {
436 if (line->cl_Days[i] == 0) {
441 if (weekUsed && !daysUsed) {
442 memset(line->cl_Days, 0, sizeof(line->cl_Days));
444 if (daysUsed && !weekUsed) {
445 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
451 static void SynchronizeFile(const char *fileName)
453 int maxEntries = MAXLINES;
457 if (strcmp(fileName, "root") == 0) {
460 maxLines = maxEntries * 10;
465 DeleteFile(fileName);
467 fi = fopen(fileName, "r");
471 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
472 CronFile *file = xzalloc(sizeof(CronFile));
475 file->cf_User = strdup(fileName);
476 pline = &file->cf_LineBase;
478 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
483 if (buf[0] == 0 || buf[0] == '#') {
486 if (--maxEntries == 0) {
489 memset(&line, 0, sizeof(line));
491 #if ENABLE_DEBUG_CROND_OPTION
493 crondlog("\111User %s Entry %s\n", fileName, buf);
497 /* parse date ranges */
498 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
499 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
500 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
501 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
502 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
510 * fix days and dow - if one is not * and the other
511 * is *, the other is set to 0, and vise-versa
516 *pline = xzalloc(sizeof(CronLine));
520 (*pline)->cl_Shell = strdup(ptr);
522 #if ENABLE_DEBUG_CROND_OPTION
524 crondlog("\111 Command %s\n", ptr);
528 pline = &((*pline)->cl_Next);
532 file->cf_Next = FileBase;
535 if (maxLines == 0 || maxEntries == 0) {
536 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
544 static void CheckUpdates(void)
549 fi = fopen(CRONUPDATE, "r");
552 while (fgets(buf, sizeof(buf), fi) != NULL) {
553 SynchronizeFile(strtok(buf, " \t\r\n"));
559 static void SynchronizeDir(void)
561 /* Attempt to delete the database. */
566 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
570 DeleteFile(file->cf_User);
574 * Remove cron update file
576 * Re-chdir, in case directory was renamed & deleted, or otherwise
579 * scan directory and add associated users
583 if (chdir(CDir) < 0) {
584 crondlog("\311cannot find %s\n", CDir);
587 DIR *dir = opendir(".");
591 while ((den = readdir(dir))) {
592 if (strchr(den->d_name, '.') != NULL) {
595 if (getpwnam(den->d_name)) {
596 SynchronizeFile(den->d_name);
598 crondlog("\007ignoring %s\n", den->d_name);
603 crondlog("\311cannot open current dir!\n");
610 * DeleteFile() - delete user database
612 * Note: multiple entries for same user may exist if we were unable to
613 * completely delete a database due to running processes.
616 static void DeleteFile(const char *userName)
618 CronFile **pfile = &FileBase;
621 while ((file = *pfile) != NULL) {
622 if (strcmp(userName, file->cf_User) == 0) {
623 CronLine **pline = &file->cf_LineBase;
626 file->cf_Running = 0;
627 file->cf_Deleted = 1;
629 while ((line = *pline) != NULL) {
630 if (line->cl_Pid > 0) {
631 file->cf_Running = 1;
632 pline = &line->cl_Next;
634 *pline = line->cl_Next;
635 free(line->cl_Shell);
639 if (file->cf_Running == 0) {
640 *pfile = file->cf_Next;
644 pfile = &file->cf_Next;
647 pfile = &file->cf_Next;
655 * determine which jobs need to be run. Under normal conditions, the
656 * period is about a minute (one scan). Worst case it will be one
660 static int TestJobs(time_t t1, time_t t2)
665 /* Find jobs > t1 and <= t2 */
667 for (t = t1 - t1 % 60; t <= t2; t += 60) {
669 struct tm *tp = localtime(&t);
673 for (file = FileBase; file; file = file->cf_Next) {
674 #if ENABLE_DEBUG_CROND_OPTION
676 crondlog("\005FILE %s:\n", file->cf_User);
678 if (file->cf_Deleted)
680 for (line = file->cf_LineBase; line; line = line->cl_Next) {
681 #if ENABLE_DEBUG_CROND_OPTION
683 crondlog("\005 LINE %s\n", line->cl_Shell);
685 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
686 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
687 && line->cl_Mons[tp->tm_mon]) {
688 #if ENABLE_DEBUG_CROND_OPTION
690 crondlog("\005 JobToDo: %d %s\n",
691 line->cl_Pid, line->cl_Shell);
694 if (line->cl_Pid > 0) {
695 crondlog("\010 process already running: %s %s\n",
696 file->cf_User, line->cl_Shell);
697 } else if (line->cl_Pid == 0) {
710 static void RunJobs(void)
715 for (file = FileBase; file; file = file->cf_Next) {
716 if (file->cf_Ready) {
719 for (line = file->cf_LineBase; line; line = line->cl_Next) {
720 if (line->cl_Pid < 0) {
722 RunJob(file->cf_User, line);
724 crondlog("\010USER %s pid %3d cmd %s\n",
725 file->cf_User, line->cl_Pid, line->cl_Shell);
726 if (line->cl_Pid < 0) {
729 else if (line->cl_Pid > 0) {
730 file->cf_Running = 1;
739 * CheckJobs() - check for job completion
741 * Check for job completion, return number of jobs still running after
745 static int CheckJobs(void)
749 int nStillRunning = 0;
751 for (file = FileBase; file; file = file->cf_Next) {
752 if (file->cf_Running) {
753 file->cf_Running = 0;
755 for (line = file->cf_LineBase; line; line = line->cl_Next) {
756 if (line->cl_Pid > 0) {
758 int r = waitpid(line->cl_Pid, &status, WNOHANG);
760 if (r < 0 || r == line->cl_Pid) {
761 EndJob(file->cf_User, line);
763 file->cf_Running = 1;
766 file->cf_Running = 1;
771 nStillRunning += file->cf_Running;
773 return nStillRunning;
777 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
779 ForkJob(const char *user, CronLine * line, int mailFd,
780 const char *prog, const char *cmd, const char *arg,
781 const char *mail_filename)
783 /* Fork as the user in question and run program */
789 /* Change running state to the user in question */
791 if (ChangeUser(user) < 0) {
794 #if ENABLE_DEBUG_CROND_OPTION
796 crondlog("\005Child Running %s\n", prog);
801 xmove_fd(mailFd, mail_filename ? 1 : 0);
804 execl(prog, prog, cmd, arg, NULL);
805 crondlog("\024cannot exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
807 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
814 crondlog("\024cannot fork\n");
817 unlink(mail_filename);
819 } else if (mail_filename) {
820 /* PARENT, FORK SUCCESS
821 * rename mail-file based on pid of process
825 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
826 rename(mail_filename, mailFile2); // TODO: xrename?
829 * Close the mail file descriptor.. we can't just leave it open in
830 * a structure, closing it later, because we might run out of descriptors
838 static void RunJob(const char *user, CronLine * line)
844 line->cl_MailFlag = 0;
846 /* open mail file - owner root so nobody can screw with it. */
848 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
849 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
852 line->cl_MailFlag = 1;
853 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
855 line->cl_MailPos = lseek(mailFd, 0, SEEK_CUR);
857 crondlog("\024cannot create mail file user %s file %s, output to /dev/null\n", user, mailFile);
860 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
864 * EndJob - called when job terminates and when mail terminates
867 static void EndJob(const char *user, CronLine * line)
875 if (line->cl_Pid <= 0) {
881 * End of job and no mail file
882 * End of sendmail job
885 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
888 if (line->cl_MailFlag != 1) {
891 line->cl_MailFlag = 0;
894 * End of primary job - check for mail file. If size has increased and
895 * the file is still valid, we sendmail it.
898 mailFd = open(mailFile, O_RDONLY);
904 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid
905 || sbuf.st_nlink != 0 || sbuf.st_size == line->cl_MailPos
906 || !S_ISREG(sbuf.st_mode)
911 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
914 /* crond without sendmail */
916 static void RunJob(const char *user, CronLine * line)
918 /* Fork as the user in question and run program */
924 /* Change running state to the user in question */
926 if (ChangeUser(user) < 0) {
929 #if ENABLE_DEBUG_CROND_OPTION
931 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
935 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
936 crondlog("\024cannot exec, user %s cmd %s -c %s\n", user,
937 DEFAULT_SHELL, line->cl_Shell);
939 } else if (pid < 0) {
941 crondlog("\024cannot, user %s\n", user);
946 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */