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"
27 #include <sys/ioctl.h>
30 #include <sys/resource.h>
34 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
37 #define CRONTABS "/var/spool/cron/crontabs"
40 #define TMPDIR "/var/spool/cron"
43 #define SENDMAIL "/usr/sbin/sendmail"
46 #define SENDMAIL_ARGS "-ti", "oem"
49 #define CRONUPDATE "cron.update"
52 #define MAXLINES 256 /* max lines in non-root crontabs */
55 typedef struct CronFile {
56 struct CronFile *cf_Next;
57 struct CronLine *cf_LineBase;
58 char *cf_User; /* username */
59 int cf_Ready; /* bool: one or more jobs ready */
60 int cf_Running; /* bool: one or more jobs running */
61 int cf_Deleted; /* marked for deletion, ignore */
64 typedef struct CronLine {
65 struct CronLine *cl_Next;
66 char *cl_Shell; /* shell command */
67 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
68 int cl_MailFlag; /* running pid is for mail */
69 int cl_MailPos; /* 'empty file' size */
70 char cl_Mins[60]; /* 0-59 */
71 char cl_Hrs[24]; /* 0-23 */
72 char cl_Days[32]; /* 1-31 */
73 char cl_Mons[12]; /* 0-11 */
74 char cl_Dow[7]; /* 0-6, beginning sunday */
83 #if ENABLE_DEBUG_CROND_OPTION
84 static short DebugOpt;
87 static short LogLevel = 8;
88 static const char *LogFile;
89 static const char *CDir = CRONTABS;
91 static void startlogger(void);
93 static void CheckUpdates(void);
94 static void SynchronizeDir(void);
95 static int TestJobs(time_t t1, time_t t2);
96 static void RunJobs(void);
97 static int CheckJobs(void);
99 static void RunJob(const char *user, CronLine * line);
101 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
102 static void EndJob(const char *user, CronLine * line);
104 #define EndJob(user, line) line->cl_Pid = 0
107 static void DeleteFile(const char *userName);
109 static CronFile *FileBase;
112 static void crondlog(const char *ctl, ...)
116 int level = (int) (ctl[0] & 0xf);
117 int type = level == 20 ?
118 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
123 if (level >= LogLevel) {
125 #if ENABLE_DEBUG_CROND_OPTION
127 vfprintf(stderr, fmt, va);
131 vsyslog(type, fmt, va);
133 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
135 vdprintf(logfd, fmt, va);
137 #if ENABLE_DEBUG_CROND_OPTION
139 bb_perror_msg("Can't open log file");
150 int crond_main(int ac, char **av)
153 char *lopt, *Lopt, *copt;
155 #if ENABLE_DEBUG_CROND_OPTION
158 bb_opt_complementally = "f-b:b-f:S-L:L-S:d-l";
160 bb_opt_complementally = "f-b:b-f:S-L:L-S";
163 opterr = 0; /* disable getopt 'errors' message. */
164 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
165 #if ENABLE_DEBUG_CROND_OPTION
168 , &lopt, &Lopt, &copt
169 #if ENABLE_DEBUG_CROND_OPTION
174 LogLevel = atoi(lopt);
186 #if ENABLE_DEBUG_CROND_OPTION
188 DebugOpt = atoi(dopt);
198 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
199 * version - his died. ;(
202 * close stdin and stdout, stderr.
203 * close unused descriptors - don't need.
204 * optional detach from controlling terminal
209 /* reexec for vfork() do continue parent */
210 vfork_daemon_rexec(1, 0, ac, av, "-f");
216 (void) startlogger(); /* need if syslog mode selected */
219 * main loop - synchronize to 1 second after the minute, minimum sleep
223 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
224 bb_applet_name, LogLevel);
229 time_t t1 = time(NULL);
233 short sleep_time = 60;
236 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
242 * The file 'cron.update' is checked to determine new cron
243 * jobs. The directory is rescanned once an hour to deal
246 * check for disparity. Disparities over an hour either way
247 * result in resynchronization. A reverse-indexed disparity
248 * less then an hour causes us to effectively sleep until we
249 * match the original time (i.e. no re-execution of jobs that
250 * have just been run). A forward-indexed disparity less then
251 * an hour causes intermediate jobs to be run, but only once
254 * when running jobs, the inequality used is greater but not
255 * equal to t1, and less then or equal to t2.
263 #if ENABLE_DEBUG_CROND_OPTION
265 crondlog("\005Wakeup dt=%d\n", dt);
267 if (dt < -60 * 60 || dt > 60 * 60) {
269 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
274 if (CheckJobs() > 0) {
283 bb_fflush_stdout_and_exit(EXIT_SUCCESS); /* not reached */
286 static int ChangeUser(const char *user)
292 * Obtain password entry and change privileges
294 pas = getpwnam(user);
296 crondlog("\011failed to get uid for %s", user);
299 setenv("USER", pas->pw_name, 1);
300 setenv("HOME", pas->pw_dir, 1);
301 setenv("SHELL", DEFAULT_SHELL, 1);
304 * Change running state to the user in question
306 err_msg = change_identity_e2str(pas);
308 crondlog("\011%s for user %s", err_msg, user);
311 if (chdir(pas->pw_dir) < 0) {
312 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
313 if (chdir(TMPDIR) < 0) {
314 crondlog("\011chdir failed: %s: %m", TMPDIR);
318 return (pas->pw_uid);
321 static void startlogger(void)
324 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
326 #if ENABLE_DEBUG_CROND_OPTION
327 else { /* test logfile */
330 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
333 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
340 static const char *const DowAry[] = {
359 static const char *const MonAry[] = {
388 static char *ParseField(char *user, char *ary, int modvalue, int off,
389 const char *const *names, char *ptr)
399 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
402 /* Handle numeric digit or symbol or '*' */
405 n1 = 0; /* everything will be filled */
409 } else if (*ptr >= '0' && *ptr <= '9') {
411 n1 = strtol(ptr, &ptr, 10) + off;
413 n2 = strtol(ptr, &ptr, 10) + off;
419 for (i = 0; names[i]; ++i) {
420 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
425 ptr += strlen(names[i]);
435 /* handle optional range '-' */
438 crondlog("\111failed user %s parsing %s\n", user, base);
441 if (*ptr == '-' && n2 < 0) {
447 * collapse single-value ranges, handle skipmark, and fill
448 * in the character array appropriately.
455 skip = strtol(ptr + 1, &ptr, 10);
458 * fill array, using a failsafe is the easiest way to prevent
468 n1 = (n1 + 1) % modvalue;
471 ary[n1 % modvalue] = 1;
475 while (n1 != n2 && --failsafe);
478 crondlog("\111failed user %s parsing %s\n", user, base);
490 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
491 crondlog("\111failed user %s parsing %s\n", user, base);
495 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
498 #if ENABLE_DEBUG_CROND_OPTION
502 for (i = 0; i < modvalue; ++i) {
503 crondlog("\005%d", ary[i]);
512 static void FixDayDow(CronLine * line)
518 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
519 if (line->cl_Dow[i] == 0) {
524 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
525 if (line->cl_Days[i] == 0) {
530 if (weekUsed && !daysUsed) {
531 memset(line->cl_Days, 0, sizeof(line->cl_Days));
533 if (daysUsed && !weekUsed) {
534 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
540 static void SynchronizeFile(const char *fileName)
542 int maxEntries = MAXLINES;
546 if (strcmp(fileName, "root") == 0) {
549 maxLines = maxEntries * 10;
554 DeleteFile(fileName);
556 fi = fopen(fileName, "r");
560 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
561 CronFile *file = calloc(1, sizeof(CronFile));
564 file->cf_User = strdup(fileName);
565 pline = &file->cf_LineBase;
567 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
572 if (buf[0] == 0 || buf[0] == '#') {
575 if (--maxEntries == 0) {
578 memset(&line, 0, sizeof(line));
580 #if ENABLE_DEBUG_CROND_OPTION
582 crondlog("\111User %s Entry %s\n", fileName, buf);
586 /* parse date ranges */
587 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
588 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
589 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
590 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
591 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
599 * fix days and dow - if one is not * and the other
600 * is *, the other is set to 0, and vise-versa
605 *pline = calloc(1, sizeof(CronLine));
609 (*pline)->cl_Shell = strdup(ptr);
611 #if ENABLE_DEBUG_CROND_OPTION
613 crondlog("\111 Command %s\n", ptr);
617 pline = &((*pline)->cl_Next);
621 file->cf_Next = FileBase;
624 if (maxLines == 0 || maxEntries == 0) {
625 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
633 static void CheckUpdates(void)
638 fi = fopen(CRONUPDATE, "r");
641 while (fgets(buf, sizeof(buf), fi) != NULL) {
642 SynchronizeFile(strtok(buf, " \t\r\n"));
648 static void SynchronizeDir(void)
650 /* Attempt to delete the database. */
655 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
659 DeleteFile(file->cf_User);
663 * Remove cron update file
665 * Re-chdir, in case directory was renamed & deleted, or otherwise
668 * scan directory and add associated users
672 if (chdir(CDir) < 0) {
673 crondlog("\311unable to find %s\n", CDir);
676 DIR *dir = opendir(".");
680 while ((den = readdir(dir))) {
681 if (strchr(den->d_name, '.') != NULL) {
684 if (getpwnam(den->d_name)) {
685 SynchronizeFile(den->d_name);
687 crondlog("\007ignoring %s\n", den->d_name);
692 crondlog("\311Unable to open current dir!\n");
699 * DeleteFile() - delete user database
701 * Note: multiple entries for same user may exist if we were unable to
702 * completely delete a database due to running processes.
705 static void DeleteFile(const char *userName)
707 CronFile **pfile = &FileBase;
710 while ((file = *pfile) != NULL) {
711 if (strcmp(userName, file->cf_User) == 0) {
712 CronLine **pline = &file->cf_LineBase;
715 file->cf_Running = 0;
716 file->cf_Deleted = 1;
718 while ((line = *pline) != NULL) {
719 if (line->cl_Pid > 0) {
720 file->cf_Running = 1;
721 pline = &line->cl_Next;
723 *pline = line->cl_Next;
724 free(line->cl_Shell);
728 if (file->cf_Running == 0) {
729 *pfile = file->cf_Next;
733 pfile = &file->cf_Next;
736 pfile = &file->cf_Next;
744 * determine which jobs need to be run. Under normal conditions, the
745 * period is about a minute (one scan). Worst case it will be one
749 static int TestJobs(time_t t1, time_t t2)
754 /* Find jobs > t1 and <= t2 */
756 for (t = t1 - t1 % 60; t <= t2; t += 60) {
758 struct tm *tp = localtime(&t);
762 for (file = FileBase; file; file = file->cf_Next) {
763 #if ENABLE_DEBUG_CROND_OPTION
765 crondlog("\005FILE %s:\n", file->cf_User);
767 if (file->cf_Deleted)
769 for (line = file->cf_LineBase; line; line = line->cl_Next) {
770 #if ENABLE_DEBUG_CROND_OPTION
772 crondlog("\005 LINE %s\n", line->cl_Shell);
774 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
775 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
776 && line->cl_Mons[tp->tm_mon]) {
777 #if ENABLE_DEBUG_CROND_OPTION
779 crondlog("\005 JobToDo: %d %s\n",
780 line->cl_Pid, line->cl_Shell);
783 if (line->cl_Pid > 0) {
784 crondlog("\010 process already running: %s %s\n",
785 file->cf_User, line->cl_Shell);
786 } else if (line->cl_Pid == 0) {
799 static void RunJobs(void)
804 for (file = FileBase; file; file = file->cf_Next) {
805 if (file->cf_Ready) {
808 for (line = file->cf_LineBase; line; line = line->cl_Next) {
809 if (line->cl_Pid < 0) {
811 RunJob(file->cf_User, line);
813 crondlog("\010USER %s pid %3d cmd %s\n",
814 file->cf_User, line->cl_Pid, line->cl_Shell);
815 if (line->cl_Pid < 0) {
818 else if (line->cl_Pid > 0) {
819 file->cf_Running = 1;
828 * CheckJobs() - check for job completion
830 * Check for job completion, return number of jobs still running after
834 static int CheckJobs(void)
838 int nStillRunning = 0;
840 for (file = FileBase; file; file = file->cf_Next) {
841 if (file->cf_Running) {
842 file->cf_Running = 0;
844 for (line = file->cf_LineBase; line; line = line->cl_Next) {
845 if (line->cl_Pid > 0) {
847 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
849 if (r < 0 || r == line->cl_Pid) {
850 EndJob(file->cf_User, line);
852 file->cf_Running = 1;
855 file->cf_Running = 1;
860 nStillRunning += file->cf_Running;
862 return (nStillRunning);
866 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
868 ForkJob(const char *user, CronLine * line, int mailFd,
869 const char *prog, const char *cmd, const char *arg, const char *mailf)
871 /* Fork as the user in question and run program */
878 /* Change running state to the user in question */
880 if (ChangeUser(user) < 0) {
883 #if ENABLE_DEBUG_CROND_OPTION
885 crondlog("\005Child Running %s\n", prog);
890 dup2(mailFd, mailf != NULL);
891 dup2((mailf ? mailFd : 1), 2);
894 execl(prog, prog, cmd, arg, NULL);
895 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
897 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
900 } else if (pid < 0) {
902 crondlog("\024couldn't fork, user %s\n", user);
908 /* PARENT, FORK SUCCESS
909 * rename mail-file based on pid of process
913 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
914 rename(mailf, mailFile2);
917 * Close the mail file descriptor.. we can't just leave it open in
918 * a structure, closing it later, because we might run out of descriptors
926 static void RunJob(const char *user, CronLine * line)
932 line->cl_MailFlag = 0;
934 /* open mail file - owner root so nobody can screw with it. */
936 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
937 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
940 line->cl_MailFlag = 1;
941 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
943 line->cl_MailPos = lseek(mailFd, 0, 1);
945 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
948 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
952 * EndJob - called when job terminates and when mail terminates
955 static void EndJob(const char *user, CronLine * line)
963 if (line->cl_Pid <= 0) {
969 * End of job and no mail file
970 * End of sendmail job
973 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
976 if (line->cl_MailFlag != 1) {
979 line->cl_MailFlag = 0;
982 * End of primary job - check for mail file. If size has increased and
983 * the file is still valid, we sendmail it.
986 mailFd = open(mailFile, O_RDONLY);
992 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
993 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
997 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1000 /* crond without sendmail */
1002 static void RunJob(const char *user, CronLine * line)
1004 /* Fork as the user in question and run program */
1010 /* Change running state to the user in question */
1012 if (ChangeUser(user) < 0) {
1015 #if ENABLE_DEBUG_CROND_OPTION
1017 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1021 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1022 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1023 DEFAULT_SHELL, line->cl_Shell);
1025 } else if (pid < 0) {
1027 crondlog("\024couldn't fork, user %s\n", user);
1032 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */