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)
9 * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002
11 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
17 /* glibc frees previous setenv'ed value when we do next setenv()
18 * of the same variable. uclibc does not do this! */
19 #if (defined(__GLIBC__) && !defined(__UCLIBC__)) /* || OTHER_SAFE_LIBC... */
20 #define SETENV_LEAKS 0
22 #define SETENV_LEAKS 1
26 #define TMPDIR CONFIG_FEATURE_CROND_DIR
27 #define CRONTABS CONFIG_FEATURE_CROND_DIR "/crontabs"
29 #define SENDMAIL "sendmail"
32 #define SENDMAIL_ARGS "-ti", "oem"
35 #define CRONUPDATE "cron.update"
38 #define MAXLINES 256 /* max lines in non-root crontabs */
42 typedef struct CronFile
{
43 struct CronFile
*cf_Next
;
44 struct CronLine
*cf_LineBase
;
45 char *cf_User
; /* username */
46 smallint cf_Ready
; /* bool: one or more jobs ready */
47 smallint cf_Running
; /* bool: one or more jobs running */
48 smallint cf_Deleted
; /* marked for deletion, ignore */
51 typedef struct CronLine
{
52 struct CronLine
*cl_Next
;
53 char *cl_Shell
; /* shell command */
54 pid_t cl_Pid
; /* running pid, 0, or armed (-1) */
55 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
56 int cl_MailPos
; /* 'empty file' size */
57 smallint cl_MailFlag
; /* running pid is for mail */
58 char *cl_MailTo
; /* whom to mail results */
60 /* ordered by size, not in natural order. makes code smaller: */
61 char cl_Dow
[7]; /* 0-6, beginning sunday */
62 char cl_Mons
[12]; /* 0-11 */
63 char cl_Hrs
[24]; /* 0-23 */
64 char cl_Days
[32]; /* 1-31 */
65 char cl_Mins
[60]; /* 0-59 */
79 OPT_d
= (1 << 6) * ENABLE_FEATURE_CROND_D
,
81 #if ENABLE_FEATURE_CROND_D
82 #define DebugOpt (option_mask32 & OPT_d)
89 unsigned LogLevel
; /* = 8; */
91 const char *CDir
; /* = CRONTABS; */
98 #define G (*(struct globals*)&bb_common_bufsiz1)
99 #define LogLevel (G.LogLevel )
100 #define LogFile (G.LogFile )
101 #define CDir (G.CDir )
102 #define FileBase (G.FileBase )
103 #define env_var_user (G.env_var_user )
104 #define env_var_home (G.env_var_home )
105 #define INIT_G() do { \
111 static void CheckUpdates(void);
112 static void SynchronizeDir(void);
113 static int TestJobs(time_t t1
, time_t t2
);
114 static void RunJobs(void);
115 static int CheckJobs(void);
116 static void RunJob(const char *user
, CronLine
*line
);
117 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
118 static void EndJob(const char *user
, CronLine
*line
);
120 #define EndJob(user, line) ((line)->cl_Pid = 0)
122 static void DeleteFile(const char *userName
);
131 /* level >= 20 is "error" */
134 static void crondlog(const char *ctl
, ...)
137 int level
= (ctl
[0] & 0x1f);
140 if (level
>= (int)LogLevel
) {
141 /* Debug mode: all to (non-redirected) stderr, */
142 /* Syslog mode: all to syslog (logmode = LOGMODE_SYSLOG), */
143 if (!DebugOpt
&& LogFile
) {
144 /* Otherwise (log to file): we reopen log file at every write: */
145 int logfd
= open3_or_warn(LogFile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666);
147 xmove_fd(logfd
, STDERR_FILENO
);
149 // TODO: ERR -> error, WARN -> warning, LVL -> info
150 bb_verror_msg(ctl
+ 1, va
, /* strerr: */ NULL
);
157 int crond_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
158 int crond_main(int argc UNUSED_PARAM
, char **argv
)
164 /* "-b after -f is ignored", and so on for every pair a-b */
165 opt_complementary
= "f-b:b-f:S-L:L-S" USE_FEATURE_CROND_D(":d-l")
166 ":l+:d+"; /* -l and -d have numeric param */
167 opt
= getopt32(argv
, "l:L:fbSc:" USE_FEATURE_CROND_D("d:"),
168 &LogLevel
, &LogFile
, &CDir
169 USE_FEATURE_CROND_D(,&LogLevel
));
170 /* both -d N and -l N set the same variable: LogLevel */
172 if (!(opt
& OPT_f
)) {
173 /* close stdin, stdout, stderr.
174 * close unused descriptors - don't need them. */
175 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS
, argv
);
178 if (!DebugOpt
&& LogFile
== NULL
) {
179 /* logging to syslog */
180 openlog(applet_name
, LOG_CONS
| LOG_PID
, LOG_CRON
);
181 logmode
= LOGMODE_SYSLOG
;
185 //signal(SIGHUP, SIG_IGN); /* ? original crond dies on HUP... */
186 xsetenv("SHELL", DEFAULT_SHELL
); /* once, for all future children */
187 crondlog(LVL9
"crond (busybox "BB_VER
") started, log level %d", LogLevel
);
190 /* main loop - synchronize to 1 second after the minute, minimum sleep
193 time_t t1
= time(NULL
);
199 write_pidfile("/var/run/crond.pid");
201 sleep((sleep_time
+ 1) - (time(NULL
) % sleep_time
));
204 dt
= (long)t2
- (long)t1
;
207 * The file 'cron.update' is checked to determine new cron
208 * jobs. The directory is rescanned once an hour to deal
211 * check for disparity. Disparities over an hour either way
212 * result in resynchronization. A reverse-indexed disparity
213 * less then an hour causes us to effectively sleep until we
214 * match the original time (i.e. no re-execution of jobs that
215 * have just been run). A forward-indexed disparity less then
216 * an hour causes intermediate jobs to be run, but only once
219 * when running jobs, the inequality used is greater but not
220 * equal to t1, and less then or equal to t2.
228 crondlog(LVL5
"wakeup dt=%ld", dt
);
229 if (dt
< -60 * 60 || dt
> 60 * 60) {
230 crondlog(WARN9
"time disparity of %d minutes detected", dt
/ 60);
235 if (CheckJobs() > 0) {
244 return 0; /* not reached */
248 /* We set environment *before* vfork (because we want to use vfork),
249 * so we cannot use setenv() - repeated calls to setenv() may leak memory!
250 * Using putenv(), and freeing memory after unsetenv() won't leak */
251 static void safe_setenv(char **pvar_val
, const char *var
, const char *val
)
253 char *var_val
= *pvar_val
;
256 bb_unsetenv(var_val
);
259 *pvar_val
= xasprintf("%s=%s", var
, val
);
264 static void SetEnv(struct passwd
*pas
)
267 safe_setenv(&env_var_user
, "USER", pas
->pw_name
);
268 safe_setenv(&env_var_home
, "HOME", pas
->pw_dir
);
269 /* if we want to set user's shell instead: */
270 /*safe_setenv(env_var_user, "SHELL", pas->pw_shell);*/
272 xsetenv("USER", pas
->pw_name
);
273 xsetenv("HOME", pas
->pw_dir
);
275 /* currently, we use constant one: */
276 /*setenv("SHELL", DEFAULT_SHELL, 1); - done earlier */
279 static void ChangeUser(struct passwd
*pas
)
281 /* careful: we're after vfork! */
282 change_identity(pas
); /* - initgroups, setgid, setuid */
283 if (chdir(pas
->pw_dir
) < 0) {
284 crondlog(LVL9
"can't chdir(%s)", pas
->pw_dir
);
285 if (chdir(TMPDIR
) < 0) {
286 crondlog(DIE9
"can't chdir(%s)", TMPDIR
); /* exits */
291 static const char DowAry
[] ALIGN1
=
292 "sun""mon""tue""wed""thu""fri""sat"
293 /* "Sun""Mon""Tue""Wed""Thu""Fri""Sat" */
296 static const char MonAry
[] ALIGN1
=
297 "jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec"
298 /* "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" */
301 static void ParseField(char *user
, char *ary
, int modvalue
, int off
,
302 const char *names
, char *ptr
)
303 /* 'names' is a pointer to a set of 3-char abbreviations */
309 // this can't happen due to config_read()
316 /* Handle numeric digit or symbol or '*' */
318 n1
= 0; /* everything will be filled */
322 } else if (isdigit(*ptr
)) {
324 n1
= strtol(ptr
, &ptr
, 10) + off
;
326 n2
= strtol(ptr
, &ptr
, 10) + off
;
332 for (i
= 0; names
[i
]; i
+= 3) {
333 /* was using strncmp before... */
334 if (strncasecmp(ptr
, &names
[i
], 3) == 0) {
347 /* handle optional range '-' */
351 if (*ptr
== '-' && n2
< 0) {
357 * collapse single-value ranges, handle skipmark, and fill
358 * in the character array appropriately.
364 skip
= strtol(ptr
+ 1, &ptr
, 10);
368 * fill array, using a failsafe is the easiest way to prevent
377 n1
= (n1
+ 1) % modvalue
;
380 ary
[n1
% modvalue
] = 1;
383 if (--failsafe
== 0) {
399 crondlog(WARN9
"user %s: parse error at %s", user
, base
);
403 if (DebugOpt
&& (LogLevel
<= 5)) { /* like LVL5 */
404 /* can't use crondlog, it inserts '\n' */
406 for (i
= 0; i
< modvalue
; ++i
)
407 fprintf(stderr
, "%d", (unsigned char)ary
[i
]);
412 static void FixDayDow(CronLine
*line
)
418 for (i
= 0; i
< ARRAY_SIZE(line
->cl_Dow
); ++i
) {
419 if (line
->cl_Dow
[i
] == 0) {
424 for (i
= 0; i
< ARRAY_SIZE(line
->cl_Days
); ++i
) {
425 if (line
->cl_Days
[i
] == 0) {
430 if (weekUsed
!= daysUsed
) {
432 memset(line
->cl_Days
, 0, sizeof(line
->cl_Days
));
434 memset(line
->cl_Dow
, 0, sizeof(line
->cl_Dow
));
438 static void SynchronizeFile(const char *fileName
)
440 struct parser_t
*parser
;
444 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
451 DeleteFile(fileName
);
452 parser
= config_open(fileName
);
456 maxLines
= (strcmp(fileName
, "root") == 0) ? 65535 : MAXLINES
;
458 if (fstat(fileno(parser
->fp
), &sbuf
) == 0 && sbuf
.st_uid
== DaemonUid
) {
459 CronFile
*file
= xzalloc(sizeof(CronFile
));
463 file
->cf_User
= xstrdup(fileName
);
464 pline
= &file
->cf_LineBase
;
471 n
= config_read(parser
, tokens
, 6, 1, "# \t", PARSE_NORMAL
| PARSE_KEEP_COPY
);
476 crondlog(LVL5
"user:%s entry:%s", fileName
, parser
->data
);
478 /* check if line is setting MAILTO= */
479 if (0 == strncmp(tokens
[0], "MAILTO=", 7)) {
480 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
482 mailTo
= (tokens
[0][7]) ? xstrdup(&tokens
[0][7]) : NULL
;
483 #endif /* otherwise just ignore such lines */
486 /* check if a minimum of tokens is specified */
489 *pline
= line
= xzalloc(sizeof(*line
));
490 /* parse date ranges */
491 ParseField(file
->cf_User
, line
->cl_Mins
, 60, 0, NULL
, tokens
[0]);
492 ParseField(file
->cf_User
, line
->cl_Hrs
, 24, 0, NULL
, tokens
[1]);
493 ParseField(file
->cf_User
, line
->cl_Days
, 32, 0, NULL
, tokens
[2]);
494 ParseField(file
->cf_User
, line
->cl_Mons
, 12, -1, MonAry
, tokens
[3]);
495 ParseField(file
->cf_User
, line
->cl_Dow
, 7, 0, DowAry
, tokens
[4]);
497 * fix days and dow - if one is not "*" and the other
498 * is "*", the other is set to 0, and vise-versa
501 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
502 /* copy mailto (can be NULL) */
503 line
->cl_MailTo
= xstrdup(mailTo
);
506 line
->cl_Shell
= xstrdup(tokens
[5]);
508 crondlog(LVL5
" command:%s", tokens
[5]);
510 pline
= &line
->cl_Next
;
511 //bb_error_msg("M[%s]F[%s][%s][%s][%s][%s][%s]", mailTo, tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]);
515 file
->cf_Next
= FileBase
;
519 crondlog(WARN9
"user %s: too many lines", fileName
);
522 config_close(parser
);
525 static void CheckUpdates(void)
530 fi
= fopen_for_read(CRONUPDATE
);
533 while (fgets(buf
, sizeof(buf
), fi
) != NULL
) {
534 /* use first word only */
535 SynchronizeFile(strtok(buf
, " \t\r\n"));
541 static void SynchronizeDir(void)
544 /* Attempt to delete the database. */
546 for (file
= FileBase
; file
; file
= file
->cf_Next
) {
547 if (!file
->cf_Deleted
) {
548 DeleteFile(file
->cf_User
);
554 * Remove cron update file
556 * Re-chdir, in case directory was renamed & deleted, or otherwise
559 * scan directory and add associated users
562 if (chdir(CDir
) < 0) {
563 crondlog(DIE9
"can't chdir(%s)", CDir
);
566 DIR *dir
= opendir(".");
570 crondlog(DIE9
"can't chdir(%s)", "."); /* exits */
571 while ((den
= readdir(dir
)) != NULL
) {
572 if (strchr(den
->d_name
, '.') != NULL
) {
575 if (getpwnam(den
->d_name
)) {
576 SynchronizeFile(den
->d_name
);
578 crondlog(LVL7
"ignoring %s", den
->d_name
);
586 * DeleteFile() - delete user database
588 * Note: multiple entries for same user may exist if we were unable to
589 * completely delete a database due to running processes.
591 static void DeleteFile(const char *userName
)
593 CronFile
**pfile
= &FileBase
;
596 while ((file
= *pfile
) != NULL
) {
597 if (strcmp(userName
, file
->cf_User
) == 0) {
598 CronLine
**pline
= &file
->cf_LineBase
;
601 file
->cf_Running
= 0;
602 file
->cf_Deleted
= 1;
604 while ((line
= *pline
) != NULL
) {
605 if (line
->cl_Pid
> 0) {
606 file
->cf_Running
= 1;
607 pline
= &line
->cl_Next
;
609 *pline
= line
->cl_Next
;
610 free(line
->cl_Shell
);
614 if (file
->cf_Running
== 0) {
615 *pfile
= file
->cf_Next
;
619 pfile
= &file
->cf_Next
;
622 pfile
= &file
->cf_Next
;
630 * determine which jobs need to be run. Under normal conditions, the
631 * period is about a minute (one scan). Worst case it will be one
634 static int TestJobs(time_t t1
, time_t t2
)
639 /* Find jobs > t1 and <= t2 */
641 for (t
= t1
- t1
% 60; t
<= t2
; t
+= 60) {
650 for (file
= FileBase
; file
; file
= file
->cf_Next
) {
652 crondlog(LVL5
"file %s:", file
->cf_User
);
653 if (file
->cf_Deleted
)
655 for (line
= file
->cf_LineBase
; line
; line
= line
->cl_Next
) {
657 crondlog(LVL5
" line %s", line
->cl_Shell
);
658 if (line
->cl_Mins
[tp
->tm_min
] && line
->cl_Hrs
[tp
->tm_hour
]
659 && (line
->cl_Days
[tp
->tm_mday
] || line
->cl_Dow
[tp
->tm_wday
])
660 && line
->cl_Mons
[tp
->tm_mon
]
663 crondlog(LVL5
" job: %d %s",
664 (int)line
->cl_Pid
, line
->cl_Shell
);
666 if (line
->cl_Pid
> 0) {
667 crondlog(LVL8
"user %s: process already running: %s",
668 file
->cf_User
, line
->cl_Shell
);
669 } else if (line
->cl_Pid
== 0) {
681 static void RunJobs(void)
686 for (file
= FileBase
; file
; file
= file
->cf_Next
) {
691 for (line
= file
->cf_LineBase
; line
; line
= line
->cl_Next
) {
692 if (line
->cl_Pid
>= 0)
695 RunJob(file
->cf_User
, line
);
696 crondlog(LVL8
"USER %s pid %3d cmd %s",
697 file
->cf_User
, (int)line
->cl_Pid
, line
->cl_Shell
);
698 if (line
->cl_Pid
< 0) {
700 } else if (line
->cl_Pid
> 0) {
701 file
->cf_Running
= 1;
708 * CheckJobs() - check for job completion
710 * Check for job completion, return number of jobs still running after
713 static int CheckJobs(void)
717 int nStillRunning
= 0;
719 for (file
= FileBase
; file
; file
= file
->cf_Next
) {
720 if (file
->cf_Running
) {
721 file
->cf_Running
= 0;
723 for (line
= file
->cf_LineBase
; line
; line
= line
->cl_Next
) {
725 if (line
->cl_Pid
<= 0)
728 r
= waitpid(line
->cl_Pid
, &status
, WNOHANG
);
729 if (r
< 0 || r
== line
->cl_Pid
) {
730 EndJob(file
->cf_User
, line
);
732 file
->cf_Running
= 1;
735 file
->cf_Running
= 1;
739 nStillRunning
+= file
->cf_Running
;
741 return nStillRunning
;
744 #if ENABLE_FEATURE_CROND_CALL_SENDMAIL
746 // TODO: sendmail should be _run-time_ option, not compile-time!
749 ForkJob(const char *user
, CronLine
*line
, int mailFd
,
750 const char *prog
, const char *cmd
, const char *arg
,
751 const char *mail_filename
)
756 /* prepare things before vfork */
757 pas
= getpwnam(user
);
759 crondlog(LVL9
"can't get uid for %s", user
);
767 /* change running state to the user in question */
770 crondlog(LVL5
"child running %s", prog
);
773 xmove_fd(mailFd
, mail_filename
? 1 : 0);
776 /* crond 3.0pl1-100 puts tasks in separate process groups */
778 execlp(prog
, prog
, cmd
, arg
, (char *) NULL
);
779 crondlog(ERR20
"can't exec, user %s cmd %s %s %s", user
, prog
, cmd
, arg
);
781 fdprintf(1, "Exec failed: %s -c %s\n", prog
, arg
);
789 crondlog(ERR20
"can't vfork");
793 unlink(mail_filename
);
795 } else if (mail_filename
) {
796 /* PARENT, FORK SUCCESS
797 * rename mail-file based on pid of process
801 snprintf(mailFile2
, sizeof(mailFile2
), "%s/cron.%s.%d", TMPDIR
, user
, pid
);
802 rename(mail_filename
, mailFile2
); // TODO: xrename?
806 * Close the mail file descriptor.. we can't just leave it open in
807 * a structure, closing it later, because we might run out of descriptors
814 static void RunJob(const char *user
, CronLine
*line
)
820 line
->cl_MailFlag
= 0;
822 if (line
->cl_MailTo
) {
823 /* open mail file - owner root so nobody can screw with it. */
824 snprintf(mailFile
, sizeof(mailFile
), "%s/cron.%s.%d", TMPDIR
, user
, getpid());
825 mailFd
= open(mailFile
, O_CREAT
| O_TRUNC
| O_WRONLY
| O_EXCL
| O_APPEND
, 0600);
828 line
->cl_MailFlag
= 1;
829 fdprintf(mailFd
, "To: %s\nSubject: cron: %s\n\n", line
->cl_MailTo
,
831 line
->cl_MailPos
= lseek(mailFd
, 0, SEEK_CUR
);
833 crondlog(ERR20
"cannot create mail file %s for user %s, "
834 "discarding output", mailFile
, user
);
838 ForkJob(user
, line
, mailFd
, DEFAULT_SHELL
, "-c", line
->cl_Shell
, mailFile
);
842 * EndJob - called when job terminates and when mail terminates
844 static void EndJob(const char *user
, CronLine
*line
)
851 if (line
->cl_Pid
<= 0) {
857 * End of job and no mail file
858 * End of sendmail job
860 snprintf(mailFile
, sizeof(mailFile
), "%s/cron.%s.%d", TMPDIR
, user
, line
->cl_Pid
);
863 if (line
->cl_MailFlag
== 0) {
866 line
->cl_MailFlag
= 0;
869 * End of primary job - check for mail file. If size has increased and
870 * the file is still valid, we sendmail it.
872 mailFd
= open(mailFile
, O_RDONLY
);
878 if (fstat(mailFd
, &sbuf
) < 0 || sbuf
.st_uid
!= DaemonUid
879 || sbuf
.st_nlink
!= 0 || sbuf
.st_size
== line
->cl_MailPos
880 || !S_ISREG(sbuf
.st_mode
)
886 ForkJob(user
, line
, mailFd
, SENDMAIL
, SENDMAIL_ARGS
, NULL
);
889 #else /* crond without sendmail */
891 static void RunJob(const char *user
, CronLine
*line
)
896 /* prepare things before vfork */
897 pas
= getpwnam(user
);
899 crondlog(LVL9
"can't get uid for %s", user
);
904 /* fork as the user in question and run program */
908 /* change running state to the user in question */
911 crondlog(LVL5
"child running %s", DEFAULT_SHELL
);
913 /* crond 3.0pl1-100 puts tasks in separate process groups */
915 execl(DEFAULT_SHELL
, DEFAULT_SHELL
, "-c", line
->cl_Shell
, (char *) NULL
);
916 crondlog(ERR20
"can't exec, user %s cmd %s %s %s", user
,
917 DEFAULT_SHELL
, "-c", line
->cl_Shell
);
922 crondlog(ERR20
"can't vfork");
929 #endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */