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");
206 #if defined(__uClinux__)
208 /* reexec for vfork() do continue parent */
209 vfork_daemon_rexec(ac, av, "-f");
214 (void)startlogger(); /* need if syslog mode selected */
217 * main loop - synchronize to 1 second after the minute, minimum sleep
221 log("\011%s " VERSION " dillon, started, log level %d\n", bb_applet_name,
227 time_t t1 = time(NULL);
231 short sleep_time = 60;
234 sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time));
240 * The file 'cron.update' is checked to determine new cron
241 * jobs. The directory is rescanned once an hour to deal
244 * check for disparity. Disparities over an hour either way
245 * result in resynchronization. A reverse-indexed disparity
246 * less then an hour causes us to effectively sleep until we
247 * match the original time (i.e. no re-execution of jobs that
248 * have just been run). A forward-indexed disparity less then
249 * an hour causes intermediate jobs to be run, but only once
252 * when running jobs, the inequality used is greater but not
253 * equal to t1, and less then or equal to t2.
261 #ifdef FEATURE_DEBUG_OPT
263 log("\005Wakeup dt=%d\n", dt);
265 if (dt < -60*60 || dt > 60*60) {
267 log("\111time disparity of %d minutes detected\n", dt / 60);
284 #if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL)
289 fdprintf(int fd, const char *ctl, ...)
294 vdprintf(fd, ctl, va);
301 ChangeUser(const char *user)
306 * Obtain password entry and change privilages
309 if ((pas = getpwnam(user)) == 0) {
310 log("\011failed to get uid for %s", user);
313 setenv("USER", pas->pw_name, 1);
314 setenv("HOME", pas->pw_dir, 1);
315 setenv("SHELL", def_sh, 1);
318 * Change running state to the user in question
321 if (initgroups(user, pas->pw_gid) < 0) {
322 log("\011initgroups failed: %s %m", user);
325 /* drop all priviledges */
326 if (setgid(pas->pw_gid) < 0) {
327 log("\011setgid failed: %s %d", user, pas->pw_gid);
330 if (setuid(pas->pw_uid) < 0) {
331 log("\011setuid failed: %s %d", user, pas->pw_uid);
334 if (chdir(pas->pw_dir) < 0) {
335 log("\011chdir failed: %s: %m", pas->pw_dir);
336 if (chdir(TMPDIR) < 0) {
337 log("\011chdir failed: %s: %m", TMPDIR);
348 openlog(bb_applet_name, LOG_CONS|LOG_PID, LOG_CRON);
349 #ifdef FEATURE_DEBUG_OPT
350 else { /* test logfile */
353 if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0)
356 bb_perror_msg("Failed to open log file '%s' reason", LogFile);
362 static const char * const DowAry[] = {
381 static const char * const MonAry[] = {
411 ParseField(char *user, char *ary, int modvalue, int off,
412 const char * const *names, char *ptr)
421 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
425 * Handle numeric digit or symbol or '*'
429 n1 = 0; /* everything will be filled */
433 } else if (*ptr >= '0' && *ptr <= '9') {
435 n1 = strtol(ptr, &ptr, 10) + off;
437 n2 = strtol(ptr, &ptr, 10) + off;
442 for (i = 0; names[i]; ++i) {
443 if (strncmp(ptr, names[i], strlen(names[i])) == 0) {
448 ptr += strlen(names[i]);
458 * handle optional range '-'
462 log("\111failed user %s parsing %s\n", user, base);
465 if (*ptr == '-' && n2 < 0) {
471 * collapse single-value ranges, handle skipmark, and fill
472 * in the character array appropriately.
479 skip = strtol(ptr + 1, &ptr, 10);
482 * fill array, using a failsafe is the easiest way to prevent
492 n1 = (n1 + 1) % modvalue;
495 ary[n1 % modvalue] = 1;
498 } while (n1 != n2 && --failsafe);
501 log("\111failed user %s parsing %s\n", user, base);
512 if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') {
513 log("\111failed user %s parsing %s\n", user, base);
517 while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')
520 #ifdef FEATURE_DEBUG_OPT
524 for (i = 0; i < modvalue; ++i)
525 log("\005%d", ary[i]);
534 FixDayDow(CronLine *line)
540 for (i = 0; i < arysize(line->cl_Dow); ++i) {
541 if (line->cl_Dow[i] == 0) {
546 for (i = 0; i < arysize(line->cl_Days); ++i) {
547 if (line->cl_Days[i] == 0) {
552 if (weekUsed && !daysUsed) {
553 memset(line->cl_Days, 0, sizeof(line->cl_Days));
555 if (daysUsed && !weekUsed) {
556 memset(line->cl_Dow, 0, sizeof(line->cl_Dow));
563 SynchronizeFile(const char *fileName)
565 int maxEntries = MAXLINES;
569 if (strcmp(fileName, "root") == 0)
571 maxLines = maxEntries * 10;
576 DeleteFile(fileName);
578 if ((fi = fopen(fileName, "r")) != NULL) {
581 if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) {
582 CronFile *file = calloc(1, sizeof(CronFile));
585 file->cf_User = strdup(fileName);
586 pline = &file->cf_LineBase;
588 while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) {
593 buf[strlen(buf)-1] = 0;
595 if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t')
598 if (--maxEntries == 0)
601 memset(&line, 0, sizeof(line));
603 #ifdef FEATURE_DEBUG_OPT
605 log("\111User %s Entry %s\n", fileName, buf);
612 ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf);
613 ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr);
614 ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr);
615 ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr);
616 ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr);
626 * fix days and dow - if one is not * and the other
627 * is *, the other is set to 0, and vise-versa
632 *pline = calloc(1, sizeof(CronLine));
639 (*pline)->cl_Shell = strdup(ptr);
641 #ifdef FEATURE_DEBUG_OPT
643 log("\111 Command %s\n", ptr);
647 pline = &((*pline)->cl_Next);
651 file->cf_Next = FileBase;
654 if (maxLines == 0 || maxEntries == 0)
655 log("\111Maximum number of lines reached for user %s\n", fileName);
668 if ((fi = fopen(CRONUPDATE, "r")) != NULL) {
670 while (fgets(buf, sizeof(buf), fi) != NULL) {
671 SynchronizeFile(strtok(buf, " \t\r\n"));
681 * Attempt to delete the database.
687 for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next)
691 DeleteFile(file->cf_User);
695 * Remove cron update file
697 * Re-chdir, in case directory was renamed & deleted, or otherwise
700 * scan directory and add associated users
704 if (chdir(CDir) < 0) {
705 log("\311unable to find %s\n", CDir);
711 if ((dir = opendir("."))) {
712 while ((den = readdir(dir))) {
713 if (strchr(den->d_name, '.') != NULL)
715 if (getpwnam(den->d_name))
716 SynchronizeFile(den->d_name);
718 log("\007ignoring %s\n", den->d_name);
722 log("\311Unable to open current dir!\n");
729 * DeleteFile() - delete user database
731 * Note: multiple entries for same user may exist if we were unable to
732 * completely delete a database due to running processes.
736 DeleteFile(const char *userName)
738 CronFile **pfile = &FileBase;
741 while ((file = *pfile) != NULL) {
742 if (strcmp(userName, file->cf_User) == 0) {
743 CronLine **pline = &file->cf_LineBase;
746 file->cf_Running = 0;
747 file->cf_Deleted = 1;
749 while ((line = *pline) != NULL) {
750 if (line->cl_Pid > 0) {
751 file->cf_Running = 1;
752 pline = &line->cl_Next;
754 *pline = line->cl_Next;
755 free(line->cl_Shell);
759 if (file->cf_Running == 0) {
760 *pfile = file->cf_Next;
764 pfile = &file->cf_Next;
767 pfile = &file->cf_Next;
775 * determine which jobs need to be run. Under normal conditions, the
776 * period is about a minute (one scan). Worst case it will be one
781 TestJobs(time_t t1, time_t t2)
787 * Find jobs > t1 and <= t2
790 for (t = t1 - t1 % 60; t <= t2; t += 60) {
792 struct tm *tp = localtime(&t);
796 for (file = FileBase; file; file = file->cf_Next) {
797 #ifdef FEATURE_DEBUG_OPT
799 log("\005FILE %s:\n", file->cf_User);
801 if (file->cf_Deleted)
803 for (line = file->cf_LineBase; line; line = line->cl_Next) {
804 #ifdef FEATURE_DEBUG_OPT
806 log("\005 LINE %s\n", line->cl_Shell);
808 if (line->cl_Mins[tp->tm_min] &&
809 line->cl_Hrs[tp->tm_hour] &&
810 (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) &&
811 line->cl_Mons[tp->tm_mon]
813 #ifdef FEATURE_DEBUG_OPT
815 log("\005 JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell);
817 if (line->cl_Pid > 0) {
818 log("\010 process already running: %s %s\n",
822 } else if (line->cl_Pid == 0) {
841 for (file = FileBase; file; file = file->cf_Next) {
842 if (file->cf_Ready) {
845 for (line = file->cf_LineBase; line; line = line->cl_Next) {
846 if (line->cl_Pid < 0) {
848 RunJob(file->cf_User, line);
850 log("\010USER %s pid %3d cmd %s\n",
855 if (line->cl_Pid < 0)
857 else if (line->cl_Pid > 0)
858 file->cf_Running = 1;
866 * CheckJobs() - check for job completion
868 * Check for job completion, return number of jobs still running after
877 int nStillRunning = 0;
879 for (file = FileBase; file; file = file->cf_Next) {
880 if (file->cf_Running) {
881 file->cf_Running = 0;
883 for (line = file->cf_LineBase; line; line = line->cl_Next) {
884 if (line->cl_Pid > 0) {
886 int r = wait4(line->cl_Pid, &status, WNOHANG, NULL);
888 if (r < 0 || r == line->cl_Pid) {
889 EndJob(file->cf_User, line);
891 file->cf_Running = 1;
893 file->cf_Running = 1;
898 nStillRunning += file->cf_Running;
900 return(nStillRunning);
904 #ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL
906 ForkJob(const char *user, CronLine *line, int mailFd,
907 const char *prog, const char *cmd, const char *arg, const char *mailf)
910 * Fork as the user in question and run program
921 * Change running state to the user in question
924 if (ChangeUser(user) < 0)
927 #ifdef FEATURE_DEBUG_OPT
929 log("\005Child Running %s\n", prog);
933 dup2(mailFd, mailf != NULL);
934 dup2((mailf ? mailFd : 1), 2);
937 execl(prog, prog, cmd, arg, NULL);
938 log("\024unable to exec, user %s cmd %s %s %s\n", user,
941 fdprintf(1, "Exec failed: %s -c %s\n", prog, arg);
943 } else if (pid < 0) {
947 log("\024couldn't fork, user %s\n", user);
953 * PARENT, FORK SUCCESS
955 * rename mail-file based on pid of process
959 snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d",
961 rename(mailf, mailFile2);
964 * Close the mail file descriptor.. we can't just leave it open in
965 * a structure, closing it later, because we might run out of descriptors
973 RunJob(const char *user, CronLine *line)
979 line->cl_MailFlag = 0;
982 * open mail file - owner root so nobody can screw with it.
985 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
987 mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600);
990 line->cl_MailFlag = 1;
991 fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user,
993 line->cl_MailPos = lseek(mailFd, 0, 1);
995 log("\024unable to create mail file user %s file %s, output to /dev/null\n",
999 ForkJob(user, line, mailFd, def_sh, "-c", line->cl_Shell, mailFile);
1003 * EndJob - called when job terminates and when mail terminates
1007 EndJob(const char *user, CronLine *line)
1017 if (line->cl_Pid <= 0) {
1023 * End of job and no mail file
1024 * End of sendmail job
1027 snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d",
1028 user, line->cl_Pid);
1031 if (line->cl_MailFlag != 1)
1034 line->cl_MailFlag = 0;
1037 * End of primary job - check for mail file. If size has increased and
1038 * the file is still valid, we sendmail it.
1041 mailFd = open(mailFile, O_RDONLY);
1047 if (fstat(mailFd, &sbuf) < 0 ||
1048 sbuf.st_uid != DaemonUid ||
1049 sbuf.st_nlink != 0 ||
1050 sbuf.st_size == line->cl_MailPos ||
1051 !S_ISREG(sbuf.st_mode)
1056 ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL);
1059 /* crond whithout sendmail */
1062 RunJob(const char *user, CronLine *line)
1065 * Fork as the user in question and run program
1075 * Change running state to the user in question
1078 if (ChangeUser(user) < 0)
1081 #ifdef FEATURE_DEBUG_OPT
1083 log("\005Child Running %s\n", def_sh);
1086 execl(def_sh, def_sh, "-c", line->cl_Shell, NULL);
1087 log("\024unable to exec, user %s cmd %s -c %s\n", user,
1088 def_sh, line->cl_Shell);
1090 } else if (pid < 0) {
1094 log("\024couldn't fork, user %s\n", user);
1099 #endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */