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 short DebugOpt;
71 static short 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)
137 char *lopt, *Lopt, *copt;
139 #if ENABLE_DEBUG_CROND_OPTION
142 bb_opt_complementally = "f-b:b-f:S-L:L-S:d-l";
144 bb_opt_complementally = "f-b:b-f:S-L:L-S";
147 opterr = 0; /* disable getopt 'errors' message. */
148 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
149 #if ENABLE_DEBUG_CROND_OPTION
152 , &lopt, &Lopt, &copt
153 #if ENABLE_DEBUG_CROND_OPTION
158 LogLevel = atoi(lopt);
170 #if ENABLE_DEBUG_CROND_OPTION
172 DebugOpt = atoi(dopt);
182 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
183 * version - his died. ;(
186 * close stdin and stdout, stderr.
187 * close unused descriptors - don't need.
188 * optional detach from controlling terminal
193 /* reexec for vfork() do continue parent */
194 vfork_daemon_rexec(1, 0, ac, av, "-f");
200 (void) startlogger(); /* need if syslog mode selected */
203 * main loop - synchronize to 1 second after the minute, minimum sleep
207 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
208 bb_applet_name, LogLevel);
213 time_t t1 = time(NULL);
217 short sleep_time = 60;
220 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
226 * The file 'cron.update' is checked to determine new cron
227 * jobs. The directory is rescanned once an hour to deal
230 * check for disparity. Disparities over an hour either way
231 * result in resynchronization. A reverse-indexed disparity
232 * less then an hour causes us to effectively sleep until we
233 * match the original time (i.e. no re-execution of jobs that
234 * have just been run). A forward-indexed disparity less then
235 * an hour causes intermediate jobs to be run, but only once
238 * when running jobs, the inequality used is greater but not
239 * equal to t1, and less then or equal to t2.
247 #if ENABLE_DEBUG_CROND_OPTION
249 crondlog("\005Wakeup dt=%d\n", dt);
251 if (dt < -60 * 60 || dt > 60 * 60) {
253 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
258 if (CheckJobs() > 0) {
267 bb_fflush_stdout_and_exit(EXIT_SUCCESS); /* not reached */
270 static int ChangeUser(const char *user)
276 * Obtain password entry and change privileges
278 pas = getpwnam(user);
280 crondlog("\011failed to get uid for %s", user);
283 setenv("USER", pas->pw_name, 1);
284 setenv("HOME", pas->pw_dir, 1);
285 setenv("SHELL", DEFAULT_SHELL, 1);
288 * Change running state to the user in question
290 err_msg = change_identity_e2str(pas);
292 crondlog("\011%s for user %s", err_msg, user);
295 if (chdir(pas->pw_dir) < 0) {
296 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
297 if (chdir(TMPDIR) < 0) {
298 crondlog("\011chdir failed: %s: %m", TMPDIR);
302 return (pas->pw_uid);
305 static void startlogger(void)
308 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
310 #if ENABLE_DEBUG_CROND_OPTION
311 else { /* test logfile */
314 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
317 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
324 static const char *const DowAry[] = {
343 static const char *const MonAry[] = {
372 static char *ParseField(char *user, char *ary, int modvalue, int off,
373 const char *const *names, char *ptr)
383 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
386 /* Handle numeric digit or symbol or '*' */
389 n1 = 0; /* everything will be filled */
393 } else if (*ptr >= '0' && *ptr <= '9') {
395 n1 = strtol(ptr, &ptr, 10) + off;
397 n2 = strtol(ptr, &ptr, 10) + off;
403 for (i = 0; names[i]; ++i) {
404 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
409 ptr += strlen(names[i]);
419 /* handle optional range '-' */
422 crondlog("\111failed user %s parsing %s\n", user, base);
425 if (*ptr == '-' && n2 < 0) {
431 * collapse single-value ranges, handle skipmark, and fill
432 * in the character array appropriately.
439 skip = strtol(ptr + 1, &ptr, 10);
442 * fill array, using a failsafe is the easiest way to prevent
452 n1 = (n1 + 1) % modvalue;
455 ary[n1 % modvalue] = 1;
459 while (n1 != n2 && --failsafe);
462 crondlog("\111failed user %s parsing %s\n", user, base);
474 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
475 crondlog("\111failed user %s parsing %s\n", user, base);
479 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
482 #if ENABLE_DEBUG_CROND_OPTION
486 for (i = 0; i < modvalue; ++i) {
487 crondlog("\005%d", ary[i]);
496 static void FixDayDow(CronLine * line)
502 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
503 if (line->cl_Dow[i] == 0) {
508 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
509 if (line->cl_Days[i] == 0) {
514 if (weekUsed && !daysUsed) {
515 memset(line->cl_Days, 0, sizeof(line->cl_Days));
517 if (daysUsed && !weekUsed) {
518 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
524 static void SynchronizeFile(const char *fileName)
526 int maxEntries = MAXLINES;
530 if (strcmp(fileName, "root") == 0) {
533 maxLines = maxEntries * 10;
538 DeleteFile(fileName);
540 fi = fopen(fileName, "r");
544 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
545 CronFile *file = calloc(1, sizeof(CronFile));
548 file->cf_User = strdup(fileName);
549 pline = &file->cf_LineBase;
551 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
556 if (buf[0] == 0 || buf[0] == '#') {
559 if (--maxEntries == 0) {
562 memset(&line, 0, sizeof(line));
564 #if ENABLE_DEBUG_CROND_OPTION
566 crondlog("\111User %s Entry %s\n", fileName, buf);
570 /* parse date ranges */
571 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
572 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
573 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
574 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
575 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
583 * fix days and dow - if one is not * and the other
584 * is *, the other is set to 0, and vise-versa
589 *pline = calloc(1, sizeof(CronLine));
593 (*pline)->cl_Shell = strdup(ptr);
595 #if ENABLE_DEBUG_CROND_OPTION
597 crondlog("\111 Command %s\n", ptr);
601 pline = &((*pline)->cl_Next);
605 file->cf_Next = FileBase;
608 if (maxLines == 0 || maxEntries == 0) {
609 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
617 static void CheckUpdates(void)
622 fi = fopen(CRONUPDATE, "r");
625 while (fgets(buf, sizeof(buf), fi) != NULL) {
626 SynchronizeFile(strtok(buf, " \t\r\n"));
632 static void SynchronizeDir(void)
634 /* Attempt to delete the database. */
639 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
643 DeleteFile(file->cf_User);
647 * Remove cron update file
649 * Re-chdir, in case directory was renamed & deleted, or otherwise
652 * scan directory and add associated users
656 if (chdir(CDir) < 0) {
657 crondlog("\311unable to find %s\n", CDir);
660 DIR *dir = opendir(".");
664 while ((den = readdir(dir))) {
665 if (strchr(den->d_name, '.') != NULL) {
668 if (getpwnam(den->d_name)) {
669 SynchronizeFile(den->d_name);
671 crondlog("\007ignoring %s\n", den->d_name);
676 crondlog("\311Unable to open current dir!\n");
683 * DeleteFile() - delete user database
685 * Note: multiple entries for same user may exist if we were unable to
686 * completely delete a database due to running processes.
689 static void DeleteFile(const char *userName)
691 CronFile **pfile = &FileBase;
694 while ((file = *pfile) != NULL) {
695 if (strcmp(userName, file->cf_User) == 0) {
696 CronLine **pline = &file->cf_LineBase;
699 file->cf_Running = 0;
700 file->cf_Deleted = 1;
702 while ((line = *pline) != NULL) {
703 if (line->cl_Pid > 0) {
704 file->cf_Running = 1;
705 pline = &line->cl_Next;
707 *pline = line->cl_Next;
708 free(line->cl_Shell);
712 if (file->cf_Running == 0) {
713 *pfile = file->cf_Next;
717 pfile = &file->cf_Next;
720 pfile = &file->cf_Next;
728 * determine which jobs need to be run. Under normal conditions, the
729 * period is about a minute (one scan). Worst case it will be one
733 static int TestJobs(time_t t1, time_t t2)
738 /* Find jobs > t1 and <= t2 */
740 for (t = t1 - t1 % 60; t <= t2; t += 60) {
742 struct tm *tp = localtime(&t);
746 for (file = FileBase; file; file = file->cf_Next) {
747 #if ENABLE_DEBUG_CROND_OPTION
749 crondlog("\005FILE %s:\n", file->cf_User);
751 if (file->cf_Deleted)
753 for (line = file->cf_LineBase; line; line = line->cl_Next) {
754 #if ENABLE_DEBUG_CROND_OPTION
756 crondlog("\005 LINE %s\n", line->cl_Shell);
758 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
759 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
760 && line->cl_Mons[tp->tm_mon]) {
761 #if ENABLE_DEBUG_CROND_OPTION
763 crondlog("\005 JobToDo: %d %s\n",
764 line->cl_Pid, line->cl_Shell);
767 if (line->cl_Pid > 0) {
768 crondlog("\010 process already running: %s %s\n",
769 file->cf_User, line->cl_Shell);
770 } else if (line->cl_Pid == 0) {
783 static void RunJobs(void)
788 for (file = FileBase; file; file = file->cf_Next) {
789 if (file->cf_Ready) {
792 for (line = file->cf_LineBase; line; line = line->cl_Next) {
793 if (line->cl_Pid < 0) {
795 RunJob(file->cf_User, line);
797 crondlog("\010USER %s pid %3d cmd %s\n",
798 file->cf_User, line->cl_Pid, line->cl_Shell);
799 if (line->cl_Pid < 0) {
802 else if (line->cl_Pid > 0) {
803 file->cf_Running = 1;
812 * CheckJobs() - check for job completion
814 * Check for job completion, return number of jobs still running after
818 static int CheckJobs(void)
822 int nStillRunning = 0;
824 for (file = FileBase; file; file = file->cf_Next) {
825 if (file->cf_Running) {
826 file->cf_Running = 0;
828 for (line = file->cf_LineBase; line; line = line->cl_Next) {
829 if (line->cl_Pid > 0) {
831 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
833 if (r < 0 || r == line->cl_Pid) {
834 EndJob(file->cf_User, line);
836 file->cf_Running = 1;
839 file->cf_Running = 1;
844 nStillRunning += file->cf_Running;
846 return (nStillRunning);
850 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
852 ForkJob(const char *user, CronLine * line, int mailFd,
853 const char *prog, const char *cmd, const char *arg, const char *mailf)
855 /* Fork as the user in question and run program */
862 /* Change running state to the user in question */
864 if (ChangeUser(user) < 0) {
867 #if ENABLE_DEBUG_CROND_OPTION
869 crondlog("\005Child Running %s\n", prog);
874 dup2(mailFd, mailf != NULL);
875 dup2((mailf ? mailFd : 1), 2);
878 execl(prog, prog, cmd, arg, NULL);
879 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
881 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
884 } else if (pid < 0) {
886 crondlog("\024couldn't fork, user %s\n", user);
892 /* PARENT, FORK SUCCESS
893 * rename mail-file based on pid of process
897 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
898 rename(mailf, mailFile2);
901 * Close the mail file descriptor.. we can't just leave it open in
902 * a structure, closing it later, because we might run out of descriptors
910 static void RunJob(const char *user, CronLine * line)
916 line->cl_MailFlag = 0;
918 /* open mail file - owner root so nobody can screw with it. */
920 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
921 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
924 line->cl_MailFlag = 1;
925 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
927 line->cl_MailPos = lseek(mailFd, 0, 1);
929 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
932 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
936 * EndJob - called when job terminates and when mail terminates
939 static void EndJob(const char *user, CronLine * line)
947 if (line->cl_Pid <= 0) {
953 * End of job and no mail file
954 * End of sendmail job
957 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
960 if (line->cl_MailFlag != 1) {
963 line->cl_MailFlag = 0;
966 * End of primary job - check for mail file. If size has increased and
967 * the file is still valid, we sendmail it.
970 mailFd = open(mailFile, O_RDONLY);
976 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
977 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
981 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
984 /* crond without sendmail */
986 static void RunJob(const char *user, CronLine * line)
988 /* Fork as the user in question and run program */
994 /* Change running state to the user in question */
996 if (ChangeUser(user) < 0) {
999 #if ENABLE_DEBUG_CROND_OPTION
1001 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1005 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1006 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1007 DEFAULT_SHELL, line->cl_Shell);
1009 } else if (pid < 0) {
1011 crondlog("\024couldn't fork, user %s\n", user);
1016 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */