1 /* Copyright 1988,1990,1993,1994 by Paul Vixie
4 * Distribute freely, except: don't remove my name from the source or
5 * documentation (don't take credit for my work), mark your changes (don't
6 * get me blamed for your possible bugs), don't alter or remove this
7 * notice. May be sold if buildable source is provided to buyer. No
8 * warrantee of any kind, express or implied, is included with this
9 * software; use at your own risk, responsibility for damages (if any) to
10 * anyone resulting from the use of this software rests entirely with the
13 * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
14 * I'll try to keep a version up to date. I can be reached as follows:
15 * Paul Vixie <paul@vix.com> uunet!decwrl!vixie!paul
18 #if !defined(lint) && !defined(LINT)
19 static const char rcsid[] =
25 #include <sys/signal.h>
27 # include <sys/universe.h>
32 #if defined(LOGIN_CAP)
33 # include <login_cap.h>
36 # include <security/pam_appl.h>
37 # include <security/openpam.h>
41 static void child_process(entry *, user *),
52 Debug(DPROC, ("[%d] do_command(%s, (%s,%d,%d))\n",
53 getpid(), e->cmd, u->name, e->uid, e->gid))
55 /* fork to become asynchronous -- parent process is done immediately,
56 * and continues to run the normal cron code, which means return to
57 * tick(). the child and grandchild don't leave this function, alive.
59 * vfork() is unsuitable, since we have much to do, and the parent
60 * needs to be able to run off and fork other processes.
62 switch ((pid = fork())) {
64 log_it("CRON",getpid(),"error","can't fork");
65 if (e->flags & INTERVAL)
66 e->lastexit = time(NULL);
72 Debug(DPROC, ("[%d] child process done, exiting\n", getpid()))
77 Debug(DPROC, ("[%d] main process forked child #%d, "
78 "returning to work\n", getpid(), pid))
79 if (e->flags & INTERVAL) {
85 Debug(DPROC, ("[%d] main process returning to work\n", getpid()))
94 int stdin_pipe[2], stdout_pipe[2];
95 register char *input_data;
96 char *usernm, *mailto, *mailfrom;
98 # if defined(LOGIN_CAP)
103 Debug(DPROC, ("[%d] child_process('%s')\n", getpid(), e->cmd))
105 /* mark ourselves as different to PS command watchers by upshifting
106 * our program name. This has no effect on some kernels.
108 setproctitle("running job");
110 /* discover some useful and important environment settings
112 usernm = env_get("LOGNAME", e->envp);
113 mailto = env_get("MAILTO", e->envp);
114 mailfrom = env_get("MAILFROM", e->envp);
117 /* use PAM to see if the user's account is available,
118 * i.e., not locked or expired or whatever. skip this
119 * for system tasks from /etc/crontab -- they can run
122 if (strcmp(u->name, SYS_NAME)) { /* not equal */
123 pam_handle_t *pamh = NULL;
125 struct pam_conv pamc = {
126 .conv = openpam_nullconv,
130 Debug(DPROC, ("[%d] checking account with PAM\n", getpid()))
132 /* u->name keeps crontab owner name while LOGNAME is the name
133 * of user to run command on behalf of. they should be the
134 * same for a task from a per-user crontab.
136 if (strcmp(u->name, usernm)) {
137 log_it(usernm, getpid(), "username ambiguity", u->name);
141 pam_err = pam_start("cron", usernm, &pamc, &pamh);
142 if (pam_err != PAM_SUCCESS) {
143 log_it("CRON", getpid(), "error", "can't start PAM");
147 pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
148 /* Expired password shouldn't prevent the job from running. */
149 if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD) {
150 log_it(usernm, getpid(), "USER", "account unavailable");
154 pam_end(pamh, pam_err);
159 /* our parent is watching for our death by catching SIGCHLD. we
160 * do not care to watch for our children's deaths this way -- we
161 * use wait() explicitly. so we have to disable the signal (which
162 * was inherited from the parent).
164 (void) signal(SIGCHLD, SIG_DFL);
166 /* on system-V systems, we are ignoring SIGCLD. we have to stop
167 * ignoring it now or the wait() in cron_pclose() won't work.
168 * because of this, we have to wait() for our children here, as well.
170 (void) signal(SIGCLD, SIG_DFL);
173 /* create some pipes to talk to our future child
175 if (pipe(stdin_pipe) != 0 || pipe(stdout_pipe) != 0) {
176 log_it("CRON", getpid(), "error", "can't pipe");
180 /* since we are a forked process, we can diddle the command string
181 * we were passed -- nobody else is going to use it again, right?
183 * if a % is present in the command, previous characters are the
184 * command, and subsequent characters are the additional input to
185 * the command. Subsequent %'s will be transformed into newlines,
186 * but that happens later.
188 * If there are escaped %'s, remove the escape character.
191 register int escaped = FALSE;
195 for (input_data = p = e->cmd; (ch = *input_data);
200 if (ch == '%' || ch == '\\')
210 *input_data++ = '\0';
217 /* fork again, this time so we can exec the user's command.
221 log_it("CRON",getpid(),"error","can't vfork");
225 Debug(DPROC, ("[%d] grandchild process Vfork()'ed\n",
228 if (e->uid == ROOT_UID)
232 sleep(random() % Jitter);
235 /* write a log message. we've waited this long to do it
236 * because it was not until now that we knew the PID that
237 * the actual user command shell was going to get and the
238 * PID is part of the log message.
241 char *x = mkprints((u_char *)e->cmd, strlen(e->cmd));
243 log_it(usernm, getpid(), "CMD", x);
247 /* that's the last thing we'll log. close the log files.
253 /* get new pgrp, void tty, etc.
257 /* close the pipe ends that we won't use. this doesn't affect
258 * the parent, who has to read and write them; it keeps the
259 * kernel from recording us as a potential client TWICE --
260 * which would keep it from sending SIGPIPE in otherwise
261 * appropriate circumstances.
263 close(stdin_pipe[WRITE_PIPE]);
264 close(stdout_pipe[READ_PIPE]);
266 /* grandchild process. make std{in,out} be the ends of
267 * pipes opened by our daddy; make stderr go to stdout.
269 close(STDIN); dup2(stdin_pipe[READ_PIPE], STDIN);
270 close(STDOUT); dup2(stdout_pipe[WRITE_PIPE], STDOUT);
271 close(STDERR); dup2(STDOUT, STDERR);
273 /* close the pipes we just dup'ed. The resources will remain.
275 close(stdin_pipe[READ_PIPE]);
276 close(stdout_pipe[WRITE_PIPE]);
278 /* set our login universe. Do this in the grandchild
279 * so that the child can invoke /usr/lib/sendmail
284 # if defined(LOGIN_CAP)
285 /* Set user's entire context, but skip the environment
286 * as cron provides a separate interface for this
288 if ((pwd = getpwnam(usernm)) == NULL)
289 pwd = getpwuid(e->uid);
292 pwd->pw_gid = e->gid;
293 if (e->class != NULL)
294 lc = login_getclass(e->class);
297 setusercontext(lc, pwd, e->uid,
298 LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETENV)) == 0)
301 /* fall back to the old method */
304 /* set our directory, uid and gid. Set gid first,
305 * since once we set uid, we've lost root privileges.
307 if (setgid(e->gid) != 0) {
308 log_it(usernm, getpid(),
309 "error", "setgid failed");
313 if (initgroups(usernm, e->gid) != 0) {
314 log_it(usernm, getpid(),
315 "error", "initgroups failed");
319 if (setlogin(usernm) != 0) {
320 log_it(usernm, getpid(),
321 "error", "setlogin failed");
324 if (setuid(e->uid) != 0) {
325 log_it(usernm, getpid(),
326 "error", "setuid failed");
329 /* we aren't root after this..*/
330 #if defined(LOGIN_CAP)
335 chdir(env_get("HOME", e->envp));
340 char *shell = env_get("SHELL", e->envp);
343 if (DebugFlags & DTEST) {
345 "debug DTEST is on, not exec'ing command.\n");
347 "\tcmd='%s' shell='%s'\n", e->cmd, shell);
350 # endif /*DEBUGGING*/
351 execle(shell, shell, "-c", e->cmd, (char *)NULL,
353 warn("execle: couldn't exec `%s'", shell);
364 /* middle process, child of original cron, parent of process running
365 * the user's command.
368 Debug(DPROC, ("[%d] child continues, closing pipes\n", getpid()))
370 /* close the ends of the pipe that will only be referenced in the
371 * grandchild process...
373 close(stdin_pipe[READ_PIPE]);
374 close(stdout_pipe[WRITE_PIPE]);
377 * write, to the pipe connected to child's stdin, any input specified
378 * after a % in the crontab entry. while we copy, convert any
379 * additional %'s to newlines. when done, if some characters were
380 * written and the last one wasn't a newline, write a newline.
382 * Note that if the input data won't fit into one pipe buffer (2K
383 * or 4K on most BSD systems), and the child doesn't read its stdin,
384 * we would block here. thus we must fork again.
387 if (*input_data && fork() == 0) {
388 register FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w");
389 register int need_newline = FALSE;
390 register int escaped = FALSE;
394 warn("fdopen failed in child2");
398 Debug(DPROC, ("[%d] child2 sending data to grandchild\n", getpid()))
400 /* close the pipe we don't use, since we inherited it and
401 * are part of its reference count now.
403 close(stdout_pipe[READ_PIPE]);
408 * \x -> \x for all x != %
410 while ((ch = *input_data++)) {
419 if (!(escaped = (ch == '\\'))) {
421 need_newline = (ch != '\n');
429 /* close the pipe, causing an EOF condition. fclose causes
430 * stdin_pipe[WRITE_PIPE] to be closed, too.
434 Debug(DPROC, ("[%d] child2 done sending to grandchild\n", getpid()))
438 /* close the pipe to the grandkiddie's stdin, since its wicked uncle
439 * ernie back there has it open and will close it when he's done.
441 close(stdin_pipe[WRITE_PIPE]);
446 * read output from the grandchild. it's stderr has been redirected to
447 * it's stdout, which has been redirected to our pipe. if there is any
448 * output, we'll be mailing it to the user whose crontab this is...
449 * when the grandchild exits, we'll get EOF.
452 Debug(DPROC, ("[%d] child reading output from grandchild\n", getpid()))
455 register FILE *in = fdopen(stdout_pipe[READ_PIPE], "r");
459 warn("fdopen failed in child");
466 register int bytes = 1;
470 ("[%d] got data (%x:%c) from grandchild\n",
473 /* get name of recipient. this is MAILTO if set to a
474 * valid local username; USER otherwise.
476 if (mailto == NULL) {
477 /* MAILTO not present, set to USER,
478 * unless globally overriden.
485 if (mailto && *mailto == '\0')
488 /* if we are supposed to be mailing, MAILTO will
489 * be non-NULL. only in this case should we set
490 * up the mail command and subjects and stuff...
495 auto char mailcmd[MAX_COMMAND];
496 auto char hostname[MAXHOSTNAMELEN];
498 if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
500 hostname[sizeof(hostname) - 1] = '\0';
501 (void) snprintf(mailcmd, sizeof(mailcmd),
503 if (!(mail = cron_popen(mailcmd, "w", e))) {
505 (void) _exit(ERROR_EXIT);
507 if (mailfrom == NULL || *mailfrom == '\0')
508 fprintf(mail, "From: Cron Daemon <%s@%s>\n",
511 fprintf(mail, "From: Cron Daemon <%s>\n",
513 fprintf(mail, "To: %s\n", mailto);
514 fprintf(mail, "Subject: Cron <%s@%s> %s\n",
515 usernm, first_word(hostname, "."),
517 # if defined(MAIL_DATE)
518 fprintf(mail, "Date: %s\n",
519 arpadate(&TargetTime));
520 # endif /* MAIL_DATE */
521 for (env = e->envp; *env; env++)
522 fprintf(mail, "X-Cron-Env: <%s>\n",
526 /* this was the first char from the pipe
531 /* we have to read the input pipe no matter whether
532 * we mail or not, but obviously we only write to
533 * mail pipe if we ARE mailing.
536 while (EOF != (ch = getc(in))) {
542 /* only close pipe if we opened it -- i.e., we're
547 Debug(DPROC, ("[%d] closing pipe to mail\n",
549 /* Note: the pclose will probably see
550 * the termination of the grandchild
551 * in addition to the mail process, since
552 * it (the grandchild) is likely to exit
553 * after closing its stdout.
555 status = cron_pclose(mail);
558 /* if there was output and we could not mail it,
559 * log the facts so the poor user can figure out
562 if (mailto && status) {
563 char buf[MAX_TEMPSTR];
565 snprintf(buf, sizeof(buf),
566 "mailed %d byte%s of output but got status 0x%04x\n",
567 bytes, (bytes==1)?"":"s",
569 log_it(usernm, getpid(), "MAIL", buf);
572 } /*if data from grandchild*/
574 Debug(DPROC, ("[%d] got EOF from grandchild\n", getpid()))
576 fclose(in); /* also closes stdout_pipe[READ_PIPE] */
579 /* wait for children to die.
581 for (; children > 0; children--)
586 Debug(DPROC, ("[%d] waiting for grandchild #%d to finish\n",
590 Debug(DPROC, ("[%d] no more grandchildren--mail written?\n",
594 Debug(DPROC, ("[%d] grandchild #%d finished, status=%04x",
595 getpid(), pid, WEXITSTATUS(waiter)))
596 if (WIFSIGNALED(waiter) && WCOREDUMP(waiter))
597 Debug(DPROC, (", dumped core"))
608 /* Dynix (Sequent) hack to put the user associated with
609 * the passed user structure into the ATT universe if
610 * necessary. We have to dig the gecos info out of
611 * the user's password entry to see if the magic
612 * "universe(att)" string is present.
619 p = getpwuid(u->uid);
627 for (i = 0; i < 4; i++)
629 if ((s = strchr(s, ',')) == NULL)
633 if (strcmp(s, "universe(att)"))
636 (void) universe(U_ATT);