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 *),
50 Debug(DPROC, ("[%d] do_command(%s, (%s,%d,%d))\n",
51 getpid(), e->cmd, u->name, e->uid, e->gid))
53 /* fork to become asynchronous -- parent process is done immediately,
54 * and continues to run the normal cron code, which means return to
55 * tick(). the child and grandchild don't leave this function, alive.
57 * vfork() is unsuitable, since we have much to do, and the parent
58 * needs to be able to run off and fork other processes.
62 log_it("CRON",getpid(),"error","can't fork");
68 Debug(DPROC, ("[%d] child process done, exiting\n", getpid()))
75 Debug(DPROC, ("[%d] main process returning to work\n", getpid()))
84 int stdin_pipe[2], stdout_pipe[2];
85 register char *input_data;
86 char *usernm, *mailto;
88 # if defined(LOGIN_CAP)
93 Debug(DPROC, ("[%d] child_process('%s')\n", getpid(), e->cmd))
95 /* mark ourselves as different to PS command watchers by upshifting
96 * our program name. This has no effect on some kernels.
98 setproctitle("running job");
100 /* discover some useful and important environment settings
102 usernm = env_get("LOGNAME", e->envp);
103 mailto = env_get("MAILTO", e->envp);
106 /* use PAM to see if the user's account is available,
107 * i.e., not locked or expired or whatever. skip this
108 * for system tasks from /etc/crontab -- they can run
111 if (strcmp(u->name, SYS_NAME)) { /* not equal */
112 pam_handle_t *pamh = NULL;
114 struct pam_conv pamc = {
115 .conv = openpam_nullconv,
119 Debug(DPROC, ("[%d] checking account with PAM\n", getpid()))
121 /* u->name keeps crontab owner name while LOGNAME is the name
122 * of user to run command on behalf of. they should be the
123 * same for a task from a per-user crontab.
125 if (strcmp(u->name, usernm)) {
126 log_it(usernm, getpid(), "username ambiguity", u->name);
130 pam_err = pam_start("cron", usernm, &pamc, &pamh);
131 if (pam_err != PAM_SUCCESS) {
132 log_it("CRON", getpid(), "error", "can't start PAM");
136 pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
137 /* Expired password shouldn't prevent the job from running. */
138 if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD) {
139 log_it(usernm, getpid(), "USER", "account unavailable");
143 pam_end(pamh, pam_err);
148 /* our parent is watching for our death by catching SIGCHLD. we
149 * do not care to watch for our children's deaths this way -- we
150 * use wait() explicitly. so we have to disable the signal (which
151 * was inherited from the parent).
153 (void) signal(SIGCHLD, SIG_DFL);
155 /* on system-V systems, we are ignoring SIGCLD. we have to stop
156 * ignoring it now or the wait() in cron_pclose() won't work.
157 * because of this, we have to wait() for our children here, as well.
159 (void) signal(SIGCLD, SIG_DFL);
162 /* create some pipes to talk to our future child
164 if (pipe(stdin_pipe) != 0 || pipe(stdout_pipe) != 0) {
165 log_it("CRON", getpid(), "error", "can't pipe");
169 /* since we are a forked process, we can diddle the command string
170 * we were passed -- nobody else is going to use it again, right?
172 * if a % is present in the command, previous characters are the
173 * command, and subsequent characters are the additional input to
174 * the command. Subsequent %'s will be transformed into newlines,
175 * but that happens later.
177 * If there are escaped %'s, remove the escape character.
180 register int escaped = FALSE;
184 for (input_data = p = e->cmd; (ch = *input_data);
189 if (ch == '%' || ch == '\\')
199 *input_data++ = '\0';
206 /* fork again, this time so we can exec the user's command.
210 log_it("CRON",getpid(),"error","can't vfork");
214 Debug(DPROC, ("[%d] grandchild process Vfork()'ed\n",
217 if (e->uid == ROOT_UID)
221 sleep(random() % Jitter);
224 /* write a log message. we've waited this long to do it
225 * because it was not until now that we knew the PID that
226 * the actual user command shell was going to get and the
227 * PID is part of the log message.
230 char *x = mkprints((u_char *)e->cmd, strlen(e->cmd));
232 log_it(usernm, getpid(), "CMD", x);
236 /* that's the last thing we'll log. close the log files.
242 /* get new pgrp, void tty, etc.
246 /* close the pipe ends that we won't use. this doesn't affect
247 * the parent, who has to read and write them; it keeps the
248 * kernel from recording us as a potential client TWICE --
249 * which would keep it from sending SIGPIPE in otherwise
250 * appropriate circumstances.
252 close(stdin_pipe[WRITE_PIPE]);
253 close(stdout_pipe[READ_PIPE]);
255 /* grandchild process. make std{in,out} be the ends of
256 * pipes opened by our daddy; make stderr go to stdout.
258 close(STDIN); dup2(stdin_pipe[READ_PIPE], STDIN);
259 close(STDOUT); dup2(stdout_pipe[WRITE_PIPE], STDOUT);
260 close(STDERR); dup2(STDOUT, STDERR);
262 /* close the pipes we just dup'ed. The resources will remain.
264 close(stdin_pipe[READ_PIPE]);
265 close(stdout_pipe[WRITE_PIPE]);
267 /* set our login universe. Do this in the grandchild
268 * so that the child can invoke /usr/lib/sendmail
273 # if defined(LOGIN_CAP)
274 /* Set user's entire context, but skip the environment
275 * as cron provides a separate interface for this
277 if ((pwd = getpwnam(usernm)) == NULL)
278 pwd = getpwuid(e->uid);
281 pwd->pw_gid = e->gid;
282 if (e->class != NULL)
283 lc = login_getclass(e->class);
286 setusercontext(lc, pwd, e->uid,
287 LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETENV)) == 0)
290 /* fall back to the old method */
293 /* set our directory, uid and gid. Set gid first,
294 * since once we set uid, we've lost root privileges.
296 if (setgid(e->gid) != 0) {
297 log_it(usernm, getpid(),
298 "error", "setgid failed");
302 if (initgroups(usernm, e->gid) != 0) {
303 log_it(usernm, getpid(),
304 "error", "initgroups failed");
308 if (setlogin(usernm) != 0) {
309 log_it(usernm, getpid(),
310 "error", "setlogin failed");
313 if (setuid(e->uid) != 0) {
314 log_it(usernm, getpid(),
315 "error", "setuid failed");
318 /* we aren't root after this..*/
319 #if defined(LOGIN_CAP)
324 chdir(env_get("HOME", e->envp));
329 char *shell = env_get("SHELL", e->envp);
332 if (DebugFlags & DTEST) {
334 "debug DTEST is on, not exec'ing command.\n");
336 "\tcmd='%s' shell='%s'\n", e->cmd, shell);
339 # endif /*DEBUGGING*/
340 execle(shell, shell, "-c", e->cmd, (char *)0, e->envp);
341 warn("execl: couldn't exec `%s'", shell);
352 /* middle process, child of original cron, parent of process running
353 * the user's command.
356 Debug(DPROC, ("[%d] child continues, closing pipes\n", getpid()))
358 /* close the ends of the pipe that will only be referenced in the
359 * grandchild process...
361 close(stdin_pipe[READ_PIPE]);
362 close(stdout_pipe[WRITE_PIPE]);
365 * write, to the pipe connected to child's stdin, any input specified
366 * after a % in the crontab entry. while we copy, convert any
367 * additional %'s to newlines. when done, if some characters were
368 * written and the last one wasn't a newline, write a newline.
370 * Note that if the input data won't fit into one pipe buffer (2K
371 * or 4K on most BSD systems), and the child doesn't read its stdin,
372 * we would block here. thus we must fork again.
375 if (*input_data && fork() == 0) {
376 register FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w");
377 register int need_newline = FALSE;
378 register int escaped = FALSE;
382 warn("fdopen failed in child2");
386 Debug(DPROC, ("[%d] child2 sending data to grandchild\n", getpid()))
388 /* close the pipe we don't use, since we inherited it and
389 * are part of its reference count now.
391 close(stdout_pipe[READ_PIPE]);
396 * \x -> \x for all x != %
398 while ((ch = *input_data++)) {
407 if (!(escaped = (ch == '\\'))) {
409 need_newline = (ch != '\n');
417 /* close the pipe, causing an EOF condition. fclose causes
418 * stdin_pipe[WRITE_PIPE] to be closed, too.
422 Debug(DPROC, ("[%d] child2 done sending to grandchild\n", getpid()))
426 /* close the pipe to the grandkiddie's stdin, since its wicked uncle
427 * ernie back there has it open and will close it when he's done.
429 close(stdin_pipe[WRITE_PIPE]);
434 * read output from the grandchild. it's stderr has been redirected to
435 * it's stdout, which has been redirected to our pipe. if there is any
436 * output, we'll be mailing it to the user whose crontab this is...
437 * when the grandchild exits, we'll get EOF.
440 Debug(DPROC, ("[%d] child reading output from grandchild\n", getpid()))
443 register FILE *in = fdopen(stdout_pipe[READ_PIPE], "r");
447 warn("fdopen failed in child");
454 register int bytes = 1;
458 ("[%d] got data (%x:%c) from grandchild\n",
461 /* get name of recipient. this is MAILTO if set to a
462 * valid local username; USER otherwise.
464 if (mailto == NULL) {
465 /* MAILTO not present, set to USER,
466 * unless globally overriden.
473 if (mailto && *mailto == '\0')
476 /* if we are supposed to be mailing, MAILTO will
477 * be non-NULL. only in this case should we set
478 * up the mail command and subjects and stuff...
483 auto char mailcmd[MAX_COMMAND];
484 auto char hostname[MAXHOSTNAMELEN];
486 (void) gethostname(hostname, MAXHOSTNAMELEN);
487 (void) snprintf(mailcmd, sizeof(mailcmd),
489 if (!(mail = cron_popen(mailcmd, "w", e))) {
491 (void) _exit(ERROR_EXIT);
493 fprintf(mail, "From: %s (Cron Daemon)\n", usernm);
494 fprintf(mail, "To: %s\n", mailto);
495 fprintf(mail, "Subject: Cron <%s@%s> %s\n",
496 usernm, first_word(hostname, "."),
498 # if defined(MAIL_DATE)
499 fprintf(mail, "Date: %s\n",
500 arpadate(&TargetTime));
501 # endif /* MAIL_DATE */
502 for (env = e->envp; *env; env++)
503 fprintf(mail, "X-Cron-Env: <%s>\n",
507 /* this was the first char from the pipe
512 /* we have to read the input pipe no matter whether
513 * we mail or not, but obviously we only write to
514 * mail pipe if we ARE mailing.
517 while (EOF != (ch = getc(in))) {
523 /* only close pipe if we opened it -- i.e., we're
528 Debug(DPROC, ("[%d] closing pipe to mail\n",
530 /* Note: the pclose will probably see
531 * the termination of the grandchild
532 * in addition to the mail process, since
533 * it (the grandchild) is likely to exit
534 * after closing its stdout.
536 status = cron_pclose(mail);
539 /* if there was output and we could not mail it,
540 * log the facts so the poor user can figure out
543 if (mailto && status) {
544 char buf[MAX_TEMPSTR];
546 snprintf(buf, sizeof(buf),
547 "mailed %d byte%s of output but got status 0x%04x\n",
548 bytes, (bytes==1)?"":"s",
550 log_it(usernm, getpid(), "MAIL", buf);
553 } /*if data from grandchild*/
555 Debug(DPROC, ("[%d] got EOF from grandchild\n", getpid()))
557 fclose(in); /* also closes stdout_pipe[READ_PIPE] */
560 /* wait for children to die.
562 for (; children > 0; children--)
567 Debug(DPROC, ("[%d] waiting for grandchild #%d to finish\n",
571 Debug(DPROC, ("[%d] no more grandchildren--mail written?\n",
575 Debug(DPROC, ("[%d] grandchild #%d finished, status=%04x",
576 getpid(), pid, WEXITSTATUS(waiter)))
577 if (WIFSIGNALED(waiter) && WCOREDUMP(waiter))
578 Debug(DPROC, (", dumped core"))
589 /* Dynix (Sequent) hack to put the user associated with
590 * the passed user structure into the ATT universe if
591 * necessary. We have to dig the gecos info out of
592 * the user's password entry to see if the magic
593 * "universe(att)" string is present.
600 p = getpwuid(u->uid);
608 for (i = 0; i < 4; i++)
610 if ((s = strchr(s, ',')) == NULL)
614 if (strcmp(s, "universe(att)"))
617 (void) universe(U_ATT);