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"
28 #include <sys/ioctl.h>
31 #include <sys/resource.h>
33 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
36 #define CRONTABS "/var/spool/cron/crontabs"
39 #define TMPDIR "/var/spool/cron"
42 #define SENDMAIL "/usr/sbin/sendmail"
45 #define SENDMAIL_ARGS "-ti", "oem"
48 #define CRONUPDATE "cron.update"
51 #define MAXLINES 256 /* max lines in non-root crontabs */
54 typedef struct CronFile {
55 struct CronFile *cf_Next;
56 struct CronLine *cf_LineBase;
57 char *cf_User; /* username */
58 int cf_Ready; /* bool: one or more jobs ready */
59 int cf_Running; /* bool: one or more jobs running */
60 int cf_Deleted; /* marked for deletion, ignore */
63 typedef struct CronLine {
64 struct CronLine *cl_Next;
65 char *cl_Shell; /* shell command */
66 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
67 int cl_MailFlag; /* running pid is for mail */
68 int cl_MailPos; /* 'empty file' size */
69 char cl_Mins[60]; /* 0-59 */
70 char cl_Hrs[24]; /* 0-23 */
71 char cl_Days[32]; /* 1-31 */
72 char cl_Mons[12]; /* 0-11 */
73 char cl_Dow[7]; /* 0-6, beginning sunday */
82 #if ENABLE_DEBUG_CROND_OPTION
83 static short DebugOpt;
86 static short LogLevel = 8;
87 static const char *LogFile;
88 static const char *CDir = CRONTABS;
90 static void startlogger(void);
92 static void CheckUpdates(void);
93 static void SynchronizeDir(void);
94 static int TestJobs(time_t t1, time_t t2);
95 static void RunJobs(void);
96 static int CheckJobs(void);
98 static void RunJob(const char *user, CronLine * line);
100 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
101 static void EndJob(const char *user, CronLine * line);
103 #define EndJob(user, line) line->cl_Pid = 0
106 static void DeleteFile(const char *userName);
108 static CronFile *FileBase;
111 static void crondlog(const char *ctl, ...)
115 int level = (int) (ctl[0] & 0xf);
116 int type = level == 20 ?
117 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
122 if (level >= LogLevel) {
124 #if ENABLE_DEBUG_CROND_OPTION
126 vfprintf(stderr, fmt, va);
130 vsyslog(type, fmt, va);
132 int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600);
134 vdprintf(logfd, fmt, va);
136 #if ENABLE_DEBUG_CROND_OPTION
138 bb_perror_msg("Can't open log file");
149 int crond_main(int ac, char **av)
152 char *lopt, *Lopt, *copt;
154 #if ENABLE_DEBUG_CROND_OPTION
157 bb_opt_complementally = "f-b:b-f:S-L:L-S:d-l";
159 bb_opt_complementally = "f-b:b-f:S-L:L-S";
162 opterr = 0; /* disable getopt 'errors' message. */
163 opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:"
164 #if ENABLE_DEBUG_CROND_OPTION
167 , &lopt, &Lopt, &copt
168 #if ENABLE_DEBUG_CROND_OPTION
173 LogLevel = atoi(lopt);
185 #if ENABLE_DEBUG_CROND_OPTION
187 DebugOpt = atoi(dopt);
197 signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original
198 * version - his died. ;(
201 * close stdin and stdout, stderr.
202 * close unused descriptors - don't need.
203 * optional detach from controlling terminal
208 /* reexec for vfork() do continue parent */
209 vfork_daemon_rexec(1, 0, ac, av, "-f");
215 (void) startlogger(); /* need if syslog mode selected */
218 * main loop - synchronize to 1 second after the minute, minimum sleep
222 crondlog("\011%s " VERSION " dillon, started, log level %d\n",
223 bb_applet_name, LogLevel);
228 time_t t1 = time(NULL);
232 short sleep_time = 60;
235 sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time));
241 * The file 'cron.update' is checked to determine new cron
242 * jobs. The directory is rescanned once an hour to deal
245 * check for disparity. Disparities over an hour either way
246 * result in resynchronization. A reverse-indexed disparity
247 * less then an hour causes us to effectively sleep until we
248 * match the original time (i.e. no re-execution of jobs that
249 * have just been run). A forward-indexed disparity less then
250 * an hour causes intermediate jobs to be run, but only once
253 * when running jobs, the inequality used is greater but not
254 * equal to t1, and less then or equal to t2.
262 #if ENABLE_DEBUG_CROND_OPTION
264 crondlog("\005Wakeup dt=%d\n", dt);
266 if (dt < -60 * 60 || dt > 60 * 60) {
268 crondlog("\111time disparity of %d minutes detected\n", dt / 60);
273 if (CheckJobs() > 0) {
282 bb_fflush_stdout_and_exit(EXIT_SUCCESS); /* not reached */
285 static int ChangeUser(const char *user)
291 * Obtain password entry and change privileges
293 pas = getpwnam(user);
295 crondlog("\011failed to get uid for %s", user);
298 setenv("USER", pas->pw_name, 1);
299 setenv("HOME", pas->pw_dir, 1);
300 setenv("SHELL", DEFAULT_SHELL, 1);
303 * Change running state to the user in question
305 err_msg = change_identity_e2str(pas);
307 crondlog("\011%s for user %s", err_msg, user);
310 if (chdir(pas->pw_dir) < 0) {
311 crondlog("\011chdir failed: %s: %m", pas->pw_dir);
312 if (chdir(TMPDIR) < 0) {
313 crondlog("\011chdir failed: %s: %m", TMPDIR);
317 return (pas->pw_uid);
320 static void startlogger(void)
323 openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON);
325 #if ENABLE_DEBUG_CROND_OPTION
326 else { /* test logfile */
329 if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) {
332 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
339 static const char *const DowAry[] = {
358 static const char *const MonAry[] = {
387 static char *ParseField(char *user, char *ary, int modvalue, int off,
388 const char *const *names, char *ptr)
398 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
401 /* Handle numeric digit or symbol or '*' */
404 n1 = 0; /* everything will be filled */
408 } else if (*ptr >= '0' && *ptr <= '9') {
410 n1 = strtol(ptr, &ptr, 10) + off;
412 n2 = strtol(ptr, &ptr, 10) + off;
418 for (i = 0; names[i]; ++i) {
419 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
424 ptr += strlen(names[i]);
434 /* handle optional range '-' */
437 crondlog("\111failed user %s parsing %s\n", user, base);
440 if (*ptr == '-' && n2 < 0) {
446 * collapse single-value ranges, handle skipmark, and fill
447 * in the character array appropriately.
454 skip = strtol(ptr + 1, &ptr, 10);
457 * fill array, using a failsafe is the easiest way to prevent
467 n1 = (n1 + 1) % modvalue;
470 ary[n1 % modvalue] = 1;
474 while (n1 != n2 && --failsafe);
477 crondlog("\111failed user %s parsing %s\n", user, base);
489 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
490 crondlog("\111failed user %s parsing %s\n", user, base);
494 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
497 #if ENABLE_DEBUG_CROND_OPTION
501 for (i = 0; i < modvalue; ++i) {
502 crondlog("\005%d", ary[i]);
511 static void FixDayDow(CronLine * line)
517 for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) {
518 if (line->cl_Dow[i] == 0) {
523 for (i = 0; i < (int)(arysize(line->cl_Days)); ++i) {
524 if (line->cl_Days[i] == 0) {
529 if (weekUsed && !daysUsed) {
530 memset(line->cl_Days, 0, sizeof(line->cl_Days));
532 if (daysUsed && !weekUsed) {
533 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
539 static void SynchronizeFile(const char *fileName)
541 int maxEntries = MAXLINES;
545 if (strcmp(fileName, "root") == 0) {
548 maxLines = maxEntries * 10;
553 DeleteFile(fileName);
555 fi = fopen(fileName, "r");
559 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
560 CronFile *file = calloc(1, sizeof(CronFile));
563 file->cf_User = strdup(fileName);
564 pline = &file->cf_LineBase;
566 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
571 if (buf[0] == 0 || buf[0] == '#') {
574 if (--maxEntries == 0) {
577 memset(&line, 0, sizeof(line));
579 #if ENABLE_DEBUG_CROND_OPTION
581 crondlog("\111User %s Entry %s\n", fileName, buf);
585 /* parse date ranges */
586 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
587 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
588 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
589 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
590 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
598 * fix days and dow - if one is not * and the other
599 * is *, the other is set to 0, and vise-versa
604 *pline = calloc(1, sizeof(CronLine));
608 (*pline)->cl_Shell = strdup(ptr);
610 #if ENABLE_DEBUG_CROND_OPTION
612 crondlog("\111 Command %s\n", ptr);
616 pline = &((*pline)->cl_Next);
620 file->cf_Next = FileBase;
623 if (maxLines == 0 || maxEntries == 0) {
624 crondlog("\111Maximum number of lines reached for user %s\n", fileName);
632 static void CheckUpdates(void)
637 fi = fopen(CRONUPDATE, "r");
640 while (fgets(buf, sizeof(buf), fi) != NULL) {
641 SynchronizeFile(strtok(buf, " \t\r\n"));
647 static void SynchronizeDir(void)
649 /* Attempt to delete the database. */
654 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next);
658 DeleteFile(file->cf_User);
662 * Remove cron update file
664 * Re-chdir, in case directory was renamed & deleted, or otherwise
667 * scan directory and add associated users
671 if (chdir(CDir) < 0) {
672 crondlog("\311unable to find %s\n", CDir);
675 DIR *dir = opendir(".");
679 while ((den = readdir(dir))) {
680 if (strchr(den->d_name, '.') != NULL) {
683 if (getpwnam(den->d_name)) {
684 SynchronizeFile(den->d_name);
686 crondlog("\007ignoring %s\n", den->d_name);
691 crondlog("\311Unable to open current dir!\n");
698 * DeleteFile() - delete user database
700 * Note: multiple entries for same user may exist if we were unable to
701 * completely delete a database due to running processes.
704 static void DeleteFile(const char *userName)
706 CronFile **pfile = &FileBase;
709 while ((file = *pfile) != NULL) {
710 if (strcmp(userName, file->cf_User) == 0) {
711 CronLine **pline = &file->cf_LineBase;
714 file->cf_Running = 0;
715 file->cf_Deleted = 1;
717 while ((line = *pline) != NULL) {
718 if (line->cl_Pid > 0) {
719 file->cf_Running = 1;
720 pline = &line->cl_Next;
722 *pline = line->cl_Next;
723 free(line->cl_Shell);
727 if (file->cf_Running == 0) {
728 *pfile = file->cf_Next;
732 pfile = &file->cf_Next;
735 pfile = &file->cf_Next;
743 * determine which jobs need to be run. Under normal conditions, the
744 * period is about a minute (one scan). Worst case it will be one
748 static int TestJobs(time_t t1, time_t t2)
753 /* Find jobs > t1 and <= t2 */
755 for (t = t1 - t1 % 60; t <= t2; t += 60) {
757 struct tm *tp = localtime(&t);
761 for (file = FileBase; file; file = file->cf_Next) {
762 #if ENABLE_DEBUG_CROND_OPTION
764 crondlog("\005FILE %s:\n", file->cf_User);
766 if (file->cf_Deleted)
768 for (line = file->cf_LineBase; line; line = line->cl_Next) {
769 #if ENABLE_DEBUG_CROND_OPTION
771 crondlog("\005 LINE %s\n", line->cl_Shell);
773 if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] &&
774 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday])
775 && line->cl_Mons[tp->tm_mon]) {
776 #if ENABLE_DEBUG_CROND_OPTION
778 crondlog("\005 JobToDo: %d %s\n",
779 line->cl_Pid, line->cl_Shell);
782 if (line->cl_Pid > 0) {
783 crondlog("\010 process already running: %s %s\n",
784 file->cf_User, line->cl_Shell);
785 } else if (line->cl_Pid == 0) {
798 static void RunJobs(void)
803 for (file = FileBase; file; file = file->cf_Next) {
804 if (file->cf_Ready) {
807 for (line = file->cf_LineBase; line; line = line->cl_Next) {
808 if (line->cl_Pid < 0) {
810 RunJob(file->cf_User, line);
812 crondlog("\010USER %s pid %3d cmd %s\n",
813 file->cf_User, line->cl_Pid, line->cl_Shell);
814 if (line->cl_Pid < 0) {
817 else if (line->cl_Pid > 0) {
818 file->cf_Running = 1;
827 * CheckJobs() - check for job completion
829 * Check for job completion, return number of jobs still running after
833 static int CheckJobs(void)
837 int nStillRunning = 0;
839 for (file = FileBase; file; file = file->cf_Next) {
840 if (file->cf_Running) {
841 file->cf_Running = 0;
843 for (line = file->cf_LineBase; line; line = line->cl_Next) {
844 if (line->cl_Pid > 0) {
846 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
848 if (r < 0 || r == line->cl_Pid) {
849 EndJob(file->cf_User, line);
851 file->cf_Running = 1;
854 file->cf_Running = 1;
859 nStillRunning += file->cf_Running;
861 return (nStillRunning);
865 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
867 ForkJob(const char *user, CronLine * line, int mailFd,
868 const char *prog, const char *cmd, const char *arg, const char *mailf)
870 /* Fork as the user in question and run program */
877 /* Change running state to the user in question */
879 if (ChangeUser(user) < 0) {
882 #if ENABLE_DEBUG_CROND_OPTION
884 crondlog("\005Child Running %s\n", prog);
889 dup2(mailFd, mailf != NULL);
890 dup2((mailf ? mailFd : 1), 2);
893 execl(prog, prog, cmd, arg, NULL);
894 crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg);
896 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
899 } else if (pid < 0) {
901 crondlog("\024couldn't fork, user %s\n", user);
907 /* PARENT, FORK SUCCESS
908 * rename mail-file based on pid of process
912 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid);
913 rename(mailf, mailFile2);
916 * Close the mail file descriptor.. we can't just leave it open in
917 * a structure, closing it later, because we might run out of descriptors
925 static void RunJob(const char *user, CronLine * line)
931 line->cl_MailFlag = 0;
933 /* open mail file - owner root so nobody can screw with it. */
935 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid());
936 mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600);
939 line->cl_MailFlag = 1;
940 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
942 line->cl_MailPos = lseek(mailFd, 0, 1);
944 crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile);
947 ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile);
951 * EndJob - called when job terminates and when mail terminates
954 static void EndJob(const char *user, CronLine * line)
962 if (line->cl_Pid <= 0) {
968 * End of job and no mail file
969 * End of sendmail job
972 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid);
975 if (line->cl_MailFlag != 1) {
978 line->cl_MailFlag = 0;
981 * End of primary job - check for mail file. If size has increased and
982 * the file is still valid, we sendmail it.
985 mailFd = open(mailFile, O_RDONLY);
991 if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 ||
992 sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) {
996 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
999 /* crond without sendmail */
1001 static void RunJob(const char *user, CronLine * line)
1003 /* Fork as the user in question and run program */
1009 /* Change running state to the user in question */
1011 if (ChangeUser(user) < 0) {
1014 #if ENABLE_DEBUG_CROND_OPTION
1016 crondlog("\005Child Running %s\n", DEFAULT_SHELL);
1020 execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
1021 crondlog("\024unable to exec, user %s cmd %s -c %s\n", user,
1022 DEFAULT_SHELL, line->cl_Shell);
1024 } else if (pid < 0) {
1026 crondlog("\024couldn't fork, user %s\n", user);
1031 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */