2 * crond -d[#] -c <crondir> -f -b
4 * run as root, but NOT setuid root
6 * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com)
7 * May be distributed under the GNU General Public License
9 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 to be used in busybox
12 #define VERSION "2.3.2"
14 #undef FEATURE_DEBUG_OPT
29 #include <sys/ioctl.h>
32 #include <sys/resource.h>
36 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
39 #define CRONTABS "/var/spool/cron/crontabs"
42 #define TMPDIR "/var/spool/cron"
45 #define SENDMAIL "/usr/sbin/sendmail"
48 #define SENDMAIL_ARGS "-ti", "oem"
51 #define CRONUPDATE "cron.update"
54 #define MAXLINES 256 /* max lines in non-root crontabs */
57 static const char def_sh[] = "/bin/sh";
60 typedef struct CronFile {
61 struct CronFile *cf_Next;
62 struct CronLine *cf_LineBase;
63 char *cf_User; /* username */
64 int cf_Ready; /* bool: one or more jobs ready */
65 int cf_Running; /* bool: one or more jobs running */
66 int cf_Deleted; /* marked for deletion, ignore */
69 typedef struct CronLine {
70 struct CronLine *cl_Next;
71 char *cl_Shell; /* shell command */
72 pid_t cl_Pid; /* running pid, 0, or armed (-1) */
73 int cl_MailFlag; /* running pid is for mail */
74 int cl_MailPos; /* 'empty file' size */
75 char cl_Mins[60]; /* 0-59 */
76 char cl_Hrs[24]; /* 0-23 */
77 char cl_Days[32]; /* 1-31 */
78 char cl_Mons[12]; /* 0-11 */
79 char cl_Dow[7]; /* 0-6, beginning sunday */
88 #ifdef FEATURE_DEBUG_OPT
89 static short DebugOpt;
92 static short LogLevel = 8;
93 static const char *LogFile;
94 static const char *CDir = CRONTABS;
96 static void startlogger(void);
98 static void CheckUpdates(void);
99 static void SynchronizeDir(void);
100 static int TestJobs(time_t t1, time_t t2);
101 static void RunJobs(void);
102 static int CheckJobs(void);
104 static void RunJob(const char *user, CronLine *line);
105 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
106 static void EndJob(const char *user, CronLine *line);
108 #define EndJob(user, line) line->cl_Pid = 0
111 static void DeleteFile(const char *userName);
113 static CronFile *FileBase;
117 log(const char *ctl, ...)
120 int level = (int)(ctl[0] & 0xf);
121 int type = level == 20 ?
122 LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE);
126 if (level >= LogLevel) {
128 #ifdef FEATURE_DEBUG_OPT
129 if (DebugOpt) vfprintf(stderr, ctl, va);
132 if (LogFile == 0) vsyslog(type, ctl, va);
136 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0) {
137 vdprintf(logfd, ctl, va);
139 #ifdef FEATURE_DEBUG_OPT
141 bb_perror_msg("Can't open log file");
152 crond_main(int ac, char **av)
155 char *lopt, *Lopt, *copt;
156 #ifdef FEATURE_DEBUG_OPT
158 bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l";
160 bb_opt_complementaly = "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 #ifdef FEATURE_DEBUG_OPT
168 , &lopt, &Lopt, &copt
169 #ifdef FEATURE_DEBUG_OPT
174 LogLevel = atoi(lopt);
176 if (*Lopt != 0) LogFile = Lopt;
178 if (*copt != 0) CDir = copt;
180 #ifdef FEATURE_DEBUG_OPT
182 DebugOpt = atoi(dopt);
191 if (chdir(CDir) != 0)
192 bb_perror_msg_and_die("%s", CDir);
194 signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original
195 * version - his died. ;(
198 * close stdin and stdout, stderr.
199 * close unused descriptors - don't need.
200 * optional detach from controlling terminal
204 if(daemon(1, 0) < 0) {
205 bb_perror_msg_and_die("daemon");
207 #if defined(__uClinux__)
209 /* reexec for vfork() do continue parent */
210 vfork_daemon_rexec(ac, av, "-f");
215 (void)startlogger(); /* need if syslog mode selected */
218 * main loop - synchronize to 1 second after the minute, minimum sleep
222 log("\011%s " VERSION " dillon, started, log level %d\n", bb_applet_name,
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 #ifdef FEATURE_DEBUG_OPT
264 log("\005Wakeup dt=%d\n", dt);
266 if (dt < -60*60 || dt > 60*60) {
268 log("\111time disparity of %d minutes detected\n", dt / 60);
285 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
290 fdprintf(int fd, const char *ctl, ...)
295 vdprintf(fd, ctl, va);
302 ChangeUser(const char *user)
307 * Obtain password entry and change privilages
310 if ((pas = getpwnam(user)) == 0) {
311 log("\011failed to get uid for %s", user);
314 setenv("USER", pas->pw_name, 1);
315 setenv("HOME", pas->pw_dir, 1);
316 setenv("SHELL", def_sh, 1);
319 * Change running state to the user in question
322 if (initgroups(user, pas->pw_gid) < 0) {
323 log("\011initgroups failed: %s %m", user);
326 /* drop all priviledges */
327 if (setgid(pas->pw_gid) < 0) {
328 log("\011setgid failed: %s %d", user, pas->pw_gid);
331 if (setuid(pas->pw_uid) < 0) {
332 log("\011setuid failed: %s %d", user, pas->pw_uid);
335 if (chdir(pas->pw_dir) < 0) {
336 log("\011chdir failed: %s: %m", pas->pw_dir);
337 if (chdir(TMPDIR) < 0) {
338 log("\011chdir failed: %s: %m", TMPDIR);
349 openlog(bb_applet_name, LOG_CONS|LOG_PID, LOG_CRON);
350 #ifdef FEATURE_DEBUG_OPT
351 else { /* test logfile */
354 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0)
357 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
363 static const char * const DowAry[] = {
382 static const char * const MonAry[] = {
412 ParseField(char *user, char *ary, int modvalue, int off,
413 const char * const *names, char *ptr)
422 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
426 * Handle numeric digit or symbol or '*'
430 n1 = 0; /* everything will be filled */
434 } else if (*ptr >= '0' && *ptr <= '9') {
436 n1 = strtol(ptr, &ptr, 10) + off;
438 n2 = strtol(ptr, &ptr, 10) + off;
443 for (i = 0; names[i]; ++i) {
444 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
449 ptr += strlen(names[i]);
459 * handle optional range '-'
463 log("\111failed user %s parsing %s\n", user, base);
466 if (*ptr == '-' && n2 < 0) {
472 * collapse single-value ranges, handle skipmark, and fill
473 * in the character array appropriately.
480 skip = strtol(ptr + 1, &ptr, 10);
483 * fill array, using a failsafe is the easiest way to prevent
493 n1 = (n1 + 1) % modvalue;
496 ary[n1 % modvalue] = 1;
499 } while (n1 != n2 && --failsafe);
502 log("\111failed user %s parsing %s\n", user, base);
513 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
514 log("\111failed user %s parsing %s\n", user, base);
518 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
521 #ifdef FEATURE_DEBUG_OPT
525 for (i = 0; i < modvalue; ++i)
526 log("\005%d", ary[i]);
535 FixDayDow(CronLine *line)
541 for (i = 0; i < arysize(line->cl_Dow); ++i) {
542 if (line->cl_Dow[i] == 0) {
547 for (i = 0; i < arysize(line->cl_Days); ++i) {
548 if (line->cl_Days[i] == 0) {
553 if (weekUsed && !daysUsed) {
554 memset(line->cl_Days, 0, sizeof(line->cl_Days));
556 if (daysUsed && !weekUsed) {
557 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
564 SynchronizeFile(const char *fileName)
566 int maxEntries = MAXLINES;
570 if (strcmp(fileName, "root") == 0)
572 maxLines = maxEntries * 10;
577 DeleteFile(fileName);
579 if ((fi = fopen(fileName, "r")) != NULL) {
582 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
583 CronFile *file = calloc(1, sizeof(CronFile));
586 file->cf_User = strdup(fileName);
587 pline = &file->cf_LineBase;
589 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
594 buf[strlen(buf)-1] = 0;
596 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
599 if (--maxEntries == 0)
602 memset(&line, 0, sizeof(line));
604 #ifdef FEATURE_DEBUG_OPT
606 log("\111User %s Entry %s\n", fileName, buf);
613 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
614 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
615 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
616 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
617 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
627 * fix days and dow - if one is not * and the other
628 * is *, the other is set to 0, and vise-versa
633 *pline = calloc(1, sizeof(CronLine));
640 (*pline)->cl_Shell = strdup(ptr);
642 #ifdef FEATURE_DEBUG_OPT
644 log("\111 Command %s\n", ptr);
648 pline = &((*pline)->cl_Next);
652 file->cf_Next = FileBase;
655 if (maxLines == 0 || maxEntries == 0)
656 log("\111Maximum number of lines reached for user %s\n", fileName);
669 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
671 while (fgets(buf, sizeof(buf), fi) != NULL) {
672 SynchronizeFile(strtok(buf, " \t\r\n"));
682 * Attempt to delete the database.
688 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
692 DeleteFile(file->cf_User);
696 * Remove cron update file
698 * Re-chdir, in case directory was renamed & deleted, or otherwise
701 * scan directory and add associated users
705 if (chdir(CDir) < 0) {
706 log("\311unable to find %s\n", CDir);
712 if ((dir = opendir("."))) {
713 while ((den = readdir(dir))) {
714 if (strchr(den->d_name, '.') != NULL)
716 if (getpwnam(den->d_name))
717 SynchronizeFile(den->d_name);
719 log("\007ignoring %s\n", den->d_name);
723 log("\311Unable to open current dir!\n");
730 * DeleteFile() - delete user database
732 * Note: multiple entries for same user may exist if we were unable to
733 * completely delete a database due to running processes.
737 DeleteFile(const char *userName)
739 CronFile **pfile = &FileBase;
742 while ((file = *pfile) != NULL) {
743 if (strcmp(userName, file->cf_User) == 0) {
744 CronLine **pline = &file->cf_LineBase;
747 file->cf_Running = 0;
748 file->cf_Deleted = 1;
750 while ((line = *pline) != NULL) {
751 if (line->cl_Pid > 0) {
752 file->cf_Running = 1;
753 pline = &line->cl_Next;
755 *pline = line->cl_Next;
756 free(line->cl_Shell);
760 if (file->cf_Running == 0) {
761 *pfile = file->cf_Next;
765 pfile = &file->cf_Next;
768 pfile = &file->cf_Next;
776 * determine which jobs need to be run. Under normal conditions, the
777 * period is about a minute (one scan). Worst case it will be one
782 TestJobs(time_t t1, time_t t2)
788 * Find jobs > t1 and <= t2
791 for (t = t1 - t1 % 60; t <= t2; t += 60) {
793 struct tm *tp = localtime(&t);
797 for (file = FileBase; file; file = file->cf_Next) {
798 #ifdef FEATURE_DEBUG_OPT
800 log("\005FILE %s:\n", file->cf_User);
802 if (file->cf_Deleted)
804 for (line = file->cf_LineBase; line; line = line->cl_Next) {
805 #ifdef FEATURE_DEBUG_OPT
807 log("\005 LINE %s\n", line->cl_Shell);
809 if (line->cl_Mins[tp->tm_min] &&
810 line->cl_Hrs[tp->tm_hour] &&
811 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
812 line->cl_Mons[tp->tm_mon]
814 #ifdef FEATURE_DEBUG_OPT
816 log("\005 JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
818 if (line->cl_Pid > 0) {
819 log("\010 process already running: %s %s\n",
823 } else if (line->cl_Pid == 0) {
842 for (file = FileBase; file; file = file->cf_Next) {
843 if (file->cf_Ready) {
846 for (line = file->cf_LineBase; line; line = line->cl_Next) {
847 if (line->cl_Pid < 0) {
849 RunJob(file->cf_User, line);
851 log("\010USER %s pid %3d cmd %s\n",
856 if (line->cl_Pid < 0)
858 else if (line->cl_Pid > 0)
859 file->cf_Running = 1;
867 * CheckJobs() - check for job completion
869 * Check for job completion, return number of jobs still running after
878 int nStillRunning = 0;
880 for (file = FileBase; file; file = file->cf_Next) {
881 if (file->cf_Running) {
882 file->cf_Running = 0;
884 for (line = file->cf_LineBase; line; line = line->cl_Next) {
885 if (line->cl_Pid > 0) {
887 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
889 if (r < 0 || r == line->cl_Pid) {
890 EndJob(file->cf_User, line);
892 file->cf_Running = 1;
894 file->cf_Running = 1;
899 nStillRunning += file->cf_Running;
901 return(nStillRunning);
905 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
907 ForkJob(const char *user, CronLine *line, int mailFd,
908 const char *prog, const char *cmd, const char *arg, const char *mailf)
911 * Fork as the user in question and run program
922 * Change running state to the user in question
925 if (ChangeUser(user) < 0)
928 #ifdef FEATURE_DEBUG_OPT
930 log("\005Child Running %s\n", prog);
934 dup2(mailFd, mailf != NULL);
935 dup2((mailf ? mailFd : 1), 2);
938 execl(prog, prog, cmd, arg, NULL);
939 log("\024unable to exec, user %s cmd %s %s %s\n", user,
942 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
944 } else if (pid < 0) {
948 log("\024couldn't fork, user %s\n", user);
954 * PARENT, FORK SUCCESS
956 * rename mail-file based on pid of process
960 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
962 rename(mailf, mailFile2);
965 * Close the mail file descriptor.. we can't just leave it open in
966 * a structure, closing it later, because we might run out of descriptors
974 RunJob(const char *user, CronLine *line)
980 line->cl_MailFlag = 0;
983 * open mail file - owner root so nobody can screw with it.
986 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
988 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
991 line->cl_MailFlag = 1;
992 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
994 line->cl_MailPos = lseek(mailFd, 0, 1);
996 log("\024unable to create mail file user %s file %s, output to /dev/null\n",
1000 ForkJob(user, line, mailFd, def_sh, "-c", line->cl_Shell, mailFile);
1004 * EndJob - called when job terminates and when mail terminates
1008 EndJob(const char *user, CronLine *line)
1018 if (line->cl_Pid <= 0) {
1024 * End of job and no mail file
1025 * End of sendmail job
1028 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1029 user, line->cl_Pid);
1032 if (line->cl_MailFlag != 1)
1035 line->cl_MailFlag = 0;
1038 * End of primary job - check for mail file. If size has increased and
1039 * the file is still valid, we sendmail it.
1042 mailFd = open(mailFile, O_RDONLY);
1048 if (fstat(mailFd, &sbuf) < 0 ||
1049 sbuf.st_uid != DaemonUid ||
1050 sbuf.st_nlink != 0 ||
1051 sbuf.st_size == line->cl_MailPos ||
1052 !S_ISREG(sbuf.st_mode)
1057 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1060 /* crond whithout sendmail */
1063 RunJob(const char *user, CronLine *line)
1066 * Fork as the user in question and run program
1076 * Change running state to the user in question
1079 if (ChangeUser(user) < 0)
1082 #ifdef FEATURE_DEBUG_OPT
1084 log("\005Child Running %s\n", def_sh);
1087 execl(def_sh, def_sh, "-c", line->cl_Shell, NULL);
1088 log("\024unable to exec, user %s cmd %s -c %s\n", user,
1089 def_sh, line->cl_Shell);
1091 } else if (pid < 0) {
1095 log("\024couldn't fork, user %s\n", user);
1100 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */