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
208 #if defined(__uClinux__)
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 #if ENABLE_DEBUG_CROND_OPTION || ENABLE_FEATURE_CROND_CALL_SENDMAIL
290 static void fdprintf(int fd, const char *ctl, ...)
295 vdprintf(fd, ctl, va);
301 static int ChangeUser(const char *user)
307 * Obtain password entry and change privileges
309 pas = getpwnam(user);
311 crondlog("\011failed to get uid for %s", user);
314 setenv("USER", pas->pw_name, 1);
315 setenv("HOME", pas->pw_dir, 1);
316 setenv("SHELL", DEFAULT_SHELL, 1);
319 * Change running state to the user in question
321 err_msg = change_identity_e2str(pas);
323 crondlog("\011%s for user %s", err_msg, user);
326 if (chdir(pas->pw_dir) < 0) {
327 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
328 if (chdir(TMPDIR) < 0) {
329 crondlog("\011chdir failed: %s: %m", TMPDIR);
333 return (pas->pw_uid);
336 static void startlogger(void)
339 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
341 #if ENABLE_DEBUG_CROND_OPTION
342 else { /* test logfile */
345 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
348 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
355 static const char *const DowAry[] = {
374 static const char *const MonAry[] = {
403 static char *ParseField(char *user, char *ary, int modvalue, int off,
404 const char *const *names, char *ptr)
414 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
417 /* Handle numeric digit or symbol or '*' */
420 n1 = 0; /* everything will be filled */
424 } else if (*ptr >= '0' && *ptr <= '9') {
426 n1 = strtol(ptr, &ptr, 10) + off;
428 n2 = strtol(ptr, &ptr, 10) + off;
434 for (i = 0; names[i]; ++i) {
435 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
440 ptr += strlen(names[i]);
450 /* handle optional range '-' */
453 crondlog("\111failed user %s parsing %s\n", user, base);
456 if (*ptr == '-' && n2 < 0) {
462 * collapse single-value ranges, handle skipmark, and fill
463 * in the character array appropriately.
470 skip = strtol(ptr + 1, &ptr, 10);
473 * fill array, using a failsafe is the easiest way to prevent
483 n1 = (n1 + 1) % modvalue;
486 ary[n1 % modvalue] = 1;
490 while (n1 != n2 && --failsafe);
493 crondlog("\111failed user %s parsing %s\n", user, base);
505 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
506 crondlog("\111failed user %s parsing %s\n", user, base);
510 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
513 #if ENABLE_DEBUG_CROND_OPTION
517 for (i = 0; i < modvalue; ++i) {
518 crondlog("\005%d", ary[i]);
527 static void FixDayDow(CronLine * line)
533 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
534 if (line->cl_Dow[i] == 0) {
539 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
540 if (line->cl_Days[i] == 0) {
545 if (weekUsed && !daysUsed) {
546 memset(line->cl_Days, 0, sizeof(line->cl_Days));
548 if (daysUsed && !weekUsed) {
549 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
555 static void SynchronizeFile(const char *fileName)
557 int maxEntries = MAXLINES;
561 if (strcmp(fileName, "root") == 0) {
564 maxLines = maxEntries * 10;
569 DeleteFile(fileName);
571 fi = fopen(fileName, "r");
575 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
576 CronFile *file = calloc(1, sizeof(CronFile));
579 file->cf_User = strdup(fileName);
580 pline = &file->cf_LineBase;
582 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
587 if (buf[0] == 0 || buf[0] == '#') {
590 if (--maxEntries == 0) {
593 memset(&line, 0, sizeof(line));
595 #if ENABLE_DEBUG_CROND_OPTION
597 crondlog("\111User %s Entry %s\n", fileName, buf);
601 /* parse date ranges */
602 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
603 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
604 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
605 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
606 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
614 * fix days and dow - if one is not * and the other
615 * is *, the other is set to 0, and vise-versa
620 *pline = calloc(1, sizeof(CronLine));
624 (*pline)->cl_Shell = strdup(ptr);
626 #if ENABLE_DEBUG_CROND_OPTION
628 crondlog("\111 Command %s\n", ptr);
632 pline = &((*pline)->cl_Next);
636 file->cf_Next = FileBase;
639 if (maxLines == 0 || maxEntries == 0) {
640 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
648 static void CheckUpdates(void)
653 fi = fopen(CRONUPDATE, "r");
656 while (fgets(buf, sizeof(buf), fi) != NULL) {
657 SynchronizeFile(strtok(buf, " \t\r\n"));
663 static void SynchronizeDir(void)
665 /* Attempt to delete the database. */
670 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
674 DeleteFile(file->cf_User);
678 * Remove cron update file
680 * Re-chdir, in case directory was renamed & deleted, or otherwise
683 * scan directory and add associated users
687 if (chdir(CDir) < 0) {
688 crondlog("\311unable to find %s\n", CDir);
691 DIR *dir = opendir(".");
695 while ((den = readdir(dir))) {
696 if (strchr(den->d_name, '.') != NULL) {
699 if (getpwnam(den->d_name)) {
700 SynchronizeFile(den->d_name);
702 crondlog("\007ignoring %s\n", den->d_name);
707 crondlog("\311Unable to open current dir!\n");
714 * DeleteFile() - delete user database
716 * Note: multiple entries for same user may exist if we were unable to
717 * completely delete a database due to running processes.
720 static void DeleteFile(const char *userName)
722 CronFile **pfile = &FileBase;
725 while ((file = *pfile) != NULL) {
726 if (strcmp(userName, file->cf_User) == 0) {
727 CronLine **pline = &file->cf_LineBase;
730 file->cf_Running = 0;
731 file->cf_Deleted = 1;
733 while ((line = *pline) != NULL) {
734 if (line->cl_Pid > 0) {
735 file->cf_Running = 1;
736 pline = &line->cl_Next;
738 *pline = line->cl_Next;
739 free(line->cl_Shell);
743 if (file->cf_Running == 0) {
744 *pfile = file->cf_Next;
748 pfile = &file->cf_Next;
751 pfile = &file->cf_Next;
759 * determine which jobs need to be run. Under normal conditions, the
760 * period is about a minute (one scan). Worst case it will be one
764 static int TestJobs(time_t t1, time_t t2)
769 /* Find jobs > t1 and <= t2 */
771 for (t = t1 - t1 % 60; t <= t2; t += 60) {
773 struct tm *tp = localtime(&t);
777 for (file = FileBase; file; file = file->cf_Next) {
778 #if ENABLE_DEBUG_CROND_OPTION
780 crondlog("\005FILE %s:\n", file->cf_User);
782 if (file->cf_Deleted)
784 for (line = file->cf_LineBase; line; line = line->cl_Next) {
785 #if ENABLE_DEBUG_CROND_OPTION
787 crondlog("\005 LINE %s\n", line->cl_Shell);
789 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
790 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
791 && line->cl_Mons[tp->tm_mon]) {
792 #if ENABLE_DEBUG_CROND_OPTION
794 crondlog("\005 JobToDo: %d %s\n",
795 line->cl_Pid, line->cl_Shell);
798 if (line->cl_Pid > 0) {
799 crondlog("\010 process already running: %s %s\n",
800 file->cf_User, line->cl_Shell);
801 } else if (line->cl_Pid == 0) {
814 static void RunJobs(void)
819 for (file = FileBase; file; file = file->cf_Next) {
820 if (file->cf_Ready) {
823 for (line = file->cf_LineBase; line; line = line->cl_Next) {
824 if (line->cl_Pid < 0) {
826 RunJob(file->cf_User, line);
828 crondlog("\010USER %s pid %3d cmd %s\n",
829 file->cf_User, line->cl_Pid, line->cl_Shell);
830 if (line->cl_Pid < 0) {
833 else if (line->cl_Pid > 0) {
834 file->cf_Running = 1;
843 * CheckJobs() - check for job completion
845 * Check for job completion, return number of jobs still running after
849 static int CheckJobs(void)
853 int nStillRunning = 0;
855 for (file = FileBase; file; file = file->cf_Next) {
856 if (file->cf_Running) {
857 file->cf_Running = 0;
859 for (line = file->cf_LineBase; line; line = line->cl_Next) {
860 if (line->cl_Pid > 0) {
862 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
864 if (r < 0 || r == line->cl_Pid) {
865 EndJob(file->cf_User, line);
867 file->cf_Running = 1;
870 file->cf_Running = 1;
875 nStillRunning += file->cf_Running;
877 return (nStillRunning);
881 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
883 ForkJob(const char *user, CronLine * line, int mailFd,
884 const char *prog, const char *cmd, const char *arg, const char *mailf)
886 /* Fork as the user in question and run program */
893 /* Change running state to the user in question */
895 if (ChangeUser(user) < 0) {
898 #if ENABLE_DEBUG_CROND_OPTION
900 crondlog("\005Child Running %s\n", prog);
905 dup2(mailFd, mailf != NULL);
906 dup2((mailf ? mailFd : 1), 2);
909 execl(prog, prog, cmd, arg, NULL);
910 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
912 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
915 } else if (pid < 0) {
917 crondlog("\024couldn't fork, user %s\n", user);
923 /* PARENT, FORK SUCCESS
924 * rename mail-file based on pid of process
928 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
929 rename(mailf, mailFile2);
932 * Close the mail file descriptor.. we can't just leave it open in
933 * a structure, closing it later, because we might run out of descriptors
941 static void RunJob(const char *user, CronLine * line)
947 line->cl_MailFlag = 0;
949 /* open mail file - owner root so nobody can screw with it. */
951 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
952 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
955 line->cl_MailFlag = 1;
956 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
958 line->cl_MailPos = lseek(mailFd, 0, 1);
960 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
963 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
967 * EndJob - called when job terminates and when mail terminates
970 static void EndJob(const char *user, CronLine * line)
978 if (line->cl_Pid <= 0) {
984 * End of job and no mail file
985 * End of sendmail job
988 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
991 if (line->cl_MailFlag != 1) {
994 line->cl_MailFlag = 0;
997 * End of primary job - check for mail file. If size has increased and
998 * the file is still valid, we sendmail it.
1001 mailFd = open(mailFile, O_RDONLY);
1007 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
1008 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
1012 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1015 /* crond without sendmail */
1017 static void RunJob(const char *user, CronLine * line)
1019 /* Fork as the user in question and run program */
1025 /* Change running state to the user in question */
1027 if (ChangeUser(user) < 0) {
1030 #if ENABLE_DEBUG_CROND_OPTION
1032 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1036 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1037 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1038 DEFAULT_SHELL, line->cl_Shell);
1040 } else if (pid < 0) {
1042 crondlog("\024couldn't fork, user %s\n", user);
1047 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */