xref: /freebsd/usr.sbin/cron/cron/do_command.c (revision 53071ed1c96db7f89defc99c95b0ad1031d48f45)
1 /* Copyright 1988,1990,1993,1994 by Paul Vixie
2  * All rights reserved
3  *
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
11  * user.
12  *
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
16  */
17 
18 #if !defined(lint) && !defined(LINT)
19 static const char rcsid[] =
20   "$FreeBSD$";
21 #endif
22 
23 
24 #include "cron.h"
25 #include <sys/signal.h>
26 #if defined(sequent)
27 # include <sys/universe.h>
28 #endif
29 #if defined(SYSLOG)
30 # include <syslog.h>
31 #endif
32 #if defined(LOGIN_CAP)
33 # include <login_cap.h>
34 #endif
35 #ifdef PAM
36 # include <security/pam_appl.h>
37 # include <security/openpam.h>
38 #endif
39 
40 
41 static void		child_process(entry *, user *),
42 			do_univ(user *);
43 
44 static WAIT_T		wait_on_child(PID_T, const char *);
45 
46 extern char	*environ;
47 
48 void
49 do_command(e, u)
50 	entry	*e;
51 	user	*u;
52 {
53 	pid_t pid;
54 
55 	Debug(DPROC, ("[%d] do_command(%s, (%s,%d,%d))\n",
56 		getpid(), e->cmd, u->name, e->uid, e->gid))
57 
58 	/* fork to become asynchronous -- parent process is done immediately,
59 	 * and continues to run the normal cron code, which means return to
60 	 * tick().  the child and grandchild don't leave this function, alive.
61 	 *
62 	 * vfork() is unsuitable, since we have much to do, and the parent
63 	 * needs to be able to run off and fork other processes.
64 	 */
65 	switch ((pid = fork())) {
66 	case -1:
67 		log_it("CRON",getpid(),"error","can't fork");
68 		if (e->flags & INTERVAL)
69 			e->lastexit = time(NULL);
70 		break;
71 	case 0:
72 		/* child process */
73 		pidfile_close(pfh);
74 		child_process(e, u);
75 		Debug(DPROC, ("[%d] child process done, exiting\n", getpid()))
76 		_exit(OK_EXIT);
77 		break;
78 	default:
79 		/* parent process */
80 		Debug(DPROC, ("[%d] main process forked child #%d, "
81 		    "returning to work\n", getpid(), pid))
82 		if (e->flags & INTERVAL) {
83 			e->lastexit = 0;
84 			e->child = pid;
85 		}
86 		break;
87 	}
88 	Debug(DPROC, ("[%d] main process returning to work\n", getpid()))
89 }
90 
91 
92 static void
93 child_process(e, u)
94 	entry	*e;
95 	user	*u;
96 {
97 	int		stdin_pipe[2], stdout_pipe[2];
98 	register char	*input_data;
99 	char		*usernm, *mailto, *mailfrom;
100 	PID_T		jobpid, stdinjob, mailpid;
101 	register FILE	*mail;
102 	register int	bytes = 1;
103 	int		status = 0;
104 # if defined(LOGIN_CAP)
105 	struct passwd	*pwd;
106 	login_cap_t *lc;
107 # endif
108 
109 	Debug(DPROC, ("[%d] child_process('%s')\n", getpid(), e->cmd))
110 
111 	/* mark ourselves as different to PS command watchers by upshifting
112 	 * our program name.  This has no effect on some kernels.
113 	 */
114 	setproctitle("running job");
115 
116 	/* discover some useful and important environment settings
117 	 */
118 	usernm = env_get("LOGNAME", e->envp);
119 	mailto = env_get("MAILTO", e->envp);
120 	mailfrom = env_get("MAILFROM", e->envp);
121 
122 #ifdef PAM
123 	/* use PAM to see if the user's account is available,
124 	 * i.e., not locked or expired or whatever.  skip this
125 	 * for system tasks from /etc/crontab -- they can run
126 	 * as any user.
127 	 */
128 	if (strcmp(u->name, SYS_NAME)) {	/* not equal */
129 		pam_handle_t *pamh = NULL;
130 		int pam_err;
131 		struct pam_conv pamc = {
132 			.conv = openpam_nullconv,
133 			.appdata_ptr = NULL
134 		};
135 
136 		Debug(DPROC, ("[%d] checking account with PAM\n", getpid()))
137 
138 		/* u->name keeps crontab owner name while LOGNAME is the name
139 		 * of user to run command on behalf of.  they should be the
140 		 * same for a task from a per-user crontab.
141 		 */
142 		if (strcmp(u->name, usernm)) {
143 			log_it(usernm, getpid(), "username ambiguity", u->name);
144 			exit(ERROR_EXIT);
145 		}
146 
147 		pam_err = pam_start("cron", usernm, &pamc, &pamh);
148 		if (pam_err != PAM_SUCCESS) {
149 			log_it("CRON", getpid(), "error", "can't start PAM");
150 			exit(ERROR_EXIT);
151 		}
152 
153 		pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
154 		/* Expired password shouldn't prevent the job from running. */
155 		if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD) {
156 			log_it(usernm, getpid(), "USER", "account unavailable");
157 			exit(ERROR_EXIT);
158 		}
159 
160 		pam_end(pamh, pam_err);
161 	}
162 #endif
163 
164 #ifdef USE_SIGCHLD
165 	/* our parent is watching for our death by catching SIGCHLD.  we
166 	 * do not care to watch for our children's deaths this way -- we
167 	 * use wait() explicitly.  so we have to disable the signal (which
168 	 * was inherited from the parent).
169 	 */
170 	(void) signal(SIGCHLD, SIG_DFL);
171 #else
172 	/* on system-V systems, we are ignoring SIGCLD.  we have to stop
173 	 * ignoring it now or the wait() in cron_pclose() won't work.
174 	 * because of this, we have to wait() for our children here, as well.
175 	 */
176 	(void) signal(SIGCLD, SIG_DFL);
177 #endif /*BSD*/
178 
179 	/* create some pipes to talk to our future child
180 	 */
181 	if (pipe(stdin_pipe) != 0 || pipe(stdout_pipe) != 0) {
182 		log_it("CRON", getpid(), "error", "can't pipe");
183 		exit(ERROR_EXIT);
184 	}
185 
186 	/* since we are a forked process, we can diddle the command string
187 	 * we were passed -- nobody else is going to use it again, right?
188 	 *
189 	 * if a % is present in the command, previous characters are the
190 	 * command, and subsequent characters are the additional input to
191 	 * the command.  Subsequent %'s will be transformed into newlines,
192 	 * but that happens later.
193 	 *
194 	 * If there are escaped %'s, remove the escape character.
195 	 */
196 	/*local*/{
197 		register int escaped = FALSE;
198 		register int ch;
199 		register char *p;
200 
201 		for (input_data = p = e->cmd; (ch = *input_data);
202 		     input_data++, p++) {
203 			if (p != input_data)
204 			    *p = ch;
205 			if (escaped) {
206 				if (ch == '%' || ch == '\\')
207 					*--p = ch;
208 				escaped = FALSE;
209 				continue;
210 			}
211 			if (ch == '\\') {
212 				escaped = TRUE;
213 				continue;
214 			}
215 			if (ch == '%') {
216 				*input_data++ = '\0';
217 				break;
218 			}
219 		}
220 		*p = '\0';
221 	}
222 
223 	/* fork again, this time so we can exec the user's command.
224 	 */
225 	switch (jobpid = vfork()) {
226 	case -1:
227 		log_it("CRON",getpid(),"error","can't vfork");
228 		exit(ERROR_EXIT);
229 		/*NOTREACHED*/
230 	case 0:
231 		Debug(DPROC, ("[%d] grandchild process Vfork()'ed\n",
232 			      getpid()))
233 
234 		if (e->uid == ROOT_UID)
235 			Jitter = RootJitter;
236 		if (Jitter != 0) {
237 			srandom(getpid());
238 			sleep(random() % Jitter);
239 		}
240 
241 		/* write a log message.  we've waited this long to do it
242 		 * because it was not until now that we knew the PID that
243 		 * the actual user command shell was going to get and the
244 		 * PID is part of the log message.
245 		 */
246 		if ((e->flags & DONT_LOG) == 0) {
247 			char *x = mkprints((u_char *)e->cmd, strlen(e->cmd));
248 
249 			log_it(usernm, getpid(), "CMD", x);
250 			free(x);
251 		}
252 
253 		/* that's the last thing we'll log.  close the log files.
254 		 */
255 #ifdef SYSLOG
256 		closelog();
257 #endif
258 
259 		/* get new pgrp, void tty, etc.
260 		 */
261 		(void) setsid();
262 
263 		/* close the pipe ends that we won't use.  this doesn't affect
264 		 * the parent, who has to read and write them; it keeps the
265 		 * kernel from recording us as a potential client TWICE --
266 		 * which would keep it from sending SIGPIPE in otherwise
267 		 * appropriate circumstances.
268 		 */
269 		close(stdin_pipe[WRITE_PIPE]);
270 		close(stdout_pipe[READ_PIPE]);
271 
272 		/* grandchild process.  make std{in,out} be the ends of
273 		 * pipes opened by our daddy; make stderr go to stdout.
274 		 */
275 		close(STDIN);	dup2(stdin_pipe[READ_PIPE], STDIN);
276 		close(STDOUT);	dup2(stdout_pipe[WRITE_PIPE], STDOUT);
277 		close(STDERR);	dup2(STDOUT, STDERR);
278 
279 		/* close the pipes we just dup'ed.  The resources will remain.
280 		 */
281 		close(stdin_pipe[READ_PIPE]);
282 		close(stdout_pipe[WRITE_PIPE]);
283 
284 		/* set our login universe.  Do this in the grandchild
285 		 * so that the child can invoke /usr/lib/sendmail
286 		 * without surprises.
287 		 */
288 		do_univ(u);
289 
290 		environ = NULL;
291 
292 # if defined(LOGIN_CAP)
293 		/* Set user's entire context, but note that PATH will
294 		 * be overridden later
295 		 */
296 		if ((pwd = getpwnam(usernm)) == NULL)
297 			pwd = getpwuid(e->uid);
298 		lc = NULL;
299 		if (pwd != NULL) {
300 			pwd->pw_gid = e->gid;
301 			if (e->class != NULL)
302 				lc = login_getclass(e->class);
303 		}
304 		if (pwd &&
305 		    setusercontext(lc, pwd, e->uid,
306 			    LOGIN_SETALL) == 0)
307 			(void) endpwent();
308 		else {
309 			/* fall back to the old method */
310 			(void) endpwent();
311 # endif
312 			/* set our directory, uid and gid.  Set gid first,
313 			 * since once we set uid, we've lost root privileges.
314 			 */
315 			if (setgid(e->gid) != 0) {
316 				log_it(usernm, getpid(),
317 				    "error", "setgid failed");
318 				exit(ERROR_EXIT);
319 			}
320 # if defined(BSD)
321 			if (initgroups(usernm, e->gid) != 0) {
322 				log_it(usernm, getpid(),
323 				    "error", "initgroups failed");
324 				exit(ERROR_EXIT);
325 			}
326 # endif
327 			if (setlogin(usernm) != 0) {
328 				log_it(usernm, getpid(),
329 				    "error", "setlogin failed");
330 				exit(ERROR_EXIT);
331 			}
332 			if (setuid(e->uid) != 0) {
333 				log_it(usernm, getpid(),
334 				    "error", "setuid failed");
335 				exit(ERROR_EXIT);
336 			}
337 			/* we aren't root after this..*/
338 #if defined(LOGIN_CAP)
339 		}
340 		if (lc != NULL)
341 			login_close(lc);
342 #endif
343 		chdir(env_get("HOME", e->envp));
344 
345 		/* exec the command.
346 		 */
347 		{
348 			char	*shell = env_get("SHELL", e->envp);
349 			char	**p;
350 
351 			/* Apply the environment from the entry, overriding existing
352 			 * values (this will always set PATH, LOGNAME, etc.) putenv
353 			 * should not fail unless malloc does.
354 			 */
355 			for (p = e->envp; *p; ++p) {
356 				if (putenv(*p) != 0) {
357 					warn("putenv");
358 					_exit(ERROR_EXIT);
359 				}
360 			}
361 
362 # if DEBUGGING
363 			if (DebugFlags & DTEST) {
364 				fprintf(stderr,
365 				"debug DTEST is on, not exec'ing command.\n");
366 				fprintf(stderr,
367 				"\tcmd='%s' shell='%s'\n", e->cmd, shell);
368 				_exit(OK_EXIT);
369 			}
370 # endif /*DEBUGGING*/
371 			execl(shell, shell, "-c", e->cmd, (char *)NULL);
372 			warn("execl: couldn't exec `%s'", shell);
373 			_exit(ERROR_EXIT);
374 		}
375 		break;
376 	default:
377 		/* parent process */
378 		break;
379 	}
380 
381 	/* middle process, child of original cron, parent of process running
382 	 * the user's command.
383 	 */
384 
385 	Debug(DPROC, ("[%d] child continues, closing pipes\n", getpid()))
386 
387 	/* close the ends of the pipe that will only be referenced in the
388 	 * grandchild process...
389 	 */
390 	close(stdin_pipe[READ_PIPE]);
391 	close(stdout_pipe[WRITE_PIPE]);
392 
393 	/*
394 	 * write, to the pipe connected to child's stdin, any input specified
395 	 * after a % in the crontab entry.  while we copy, convert any
396 	 * additional %'s to newlines.  when done, if some characters were
397 	 * written and the last one wasn't a newline, write a newline.
398 	 *
399 	 * Note that if the input data won't fit into one pipe buffer (2K
400 	 * or 4K on most BSD systems), and the child doesn't read its stdin,
401 	 * we would block here.  thus we must fork again.
402 	 */
403 
404 	if (*input_data && (stdinjob = fork()) == 0) {
405 		register FILE	*out = fdopen(stdin_pipe[WRITE_PIPE], "w");
406 		register int	need_newline = FALSE;
407 		register int	escaped = FALSE;
408 		register int	ch;
409 
410 		if (out == NULL) {
411 			warn("fdopen failed in child2");
412 			_exit(ERROR_EXIT);
413 		}
414 
415 		Debug(DPROC, ("[%d] child2 sending data to grandchild\n", getpid()))
416 
417 		/* close the pipe we don't use, since we inherited it and
418 		 * are part of its reference count now.
419 		 */
420 		close(stdout_pipe[READ_PIPE]);
421 
422 		/* translation:
423 		 *	\% -> %
424 		 *	%  -> \n
425 		 *	\x -> \x	for all x != %
426 		 */
427 		while ((ch = *input_data++)) {
428 			if (escaped) {
429 				if (ch != '%')
430 					putc('\\', out);
431 			} else {
432 				if (ch == '%')
433 					ch = '\n';
434 			}
435 
436 			if (!(escaped = (ch == '\\'))) {
437 				putc(ch, out);
438 				need_newline = (ch != '\n');
439 			}
440 		}
441 		if (escaped)
442 			putc('\\', out);
443 		if (need_newline)
444 			putc('\n', out);
445 
446 		/* close the pipe, causing an EOF condition.  fclose causes
447 		 * stdin_pipe[WRITE_PIPE] to be closed, too.
448 		 */
449 		fclose(out);
450 
451 		Debug(DPROC, ("[%d] child2 done sending to grandchild\n", getpid()))
452 		exit(0);
453 	}
454 
455 	/* close the pipe to the grandkiddie's stdin, since its wicked uncle
456 	 * ernie back there has it open and will close it when he's done.
457 	 */
458 	close(stdin_pipe[WRITE_PIPE]);
459 
460 	/*
461 	 * read output from the grandchild.  it's stderr has been redirected to
462 	 * it's stdout, which has been redirected to our pipe.  if there is any
463 	 * output, we'll be mailing it to the user whose crontab this is...
464 	 * when the grandchild exits, we'll get EOF.
465 	 */
466 
467 	Debug(DPROC, ("[%d] child reading output from grandchild\n", getpid()))
468 
469 	/*local*/{
470 		register FILE	*in = fdopen(stdout_pipe[READ_PIPE], "r");
471 		register int	ch;
472 
473 		if (in == NULL) {
474 			warn("fdopen failed in child");
475 			_exit(ERROR_EXIT);
476 		}
477 
478 		mail = NULL;
479 
480 		ch = getc(in);
481 		if (ch != EOF) {
482 			Debug(DPROC|DEXT,
483 				("[%d] got data (%x:%c) from grandchild\n",
484 					getpid(), ch, ch))
485 
486 			/* get name of recipient.  this is MAILTO if set to a
487 			 * valid local username; USER otherwise.
488 			 */
489 			if (mailto == NULL) {
490 				/* MAILTO not present, set to USER,
491 				 * unless globally overriden.
492 				 */
493 				if (defmailto)
494 					mailto = defmailto;
495 				else
496 					mailto = usernm;
497 			}
498 			if (mailto && *mailto == '\0')
499 				mailto = NULL;
500 
501 			/* if we are supposed to be mailing, MAILTO will
502 			 * be non-NULL.  only in this case should we set
503 			 * up the mail command and subjects and stuff...
504 			 */
505 
506 			if (mailto) {
507 				register char	**env;
508 				auto char	mailcmd[MAX_COMMAND];
509 				auto char	hostname[MAXHOSTNAMELEN];
510 
511 				if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
512 					hostname[0] = '\0';
513 				hostname[sizeof(hostname) - 1] = '\0';
514 				(void) snprintf(mailcmd, sizeof(mailcmd),
515 					       MAILARGS, MAILCMD);
516 				if (!(mail = cron_popen(mailcmd, "w", e, &mailpid))) {
517 					warn("%s", MAILCMD);
518 					(void) _exit(ERROR_EXIT);
519 				}
520 				if (mailfrom == NULL || *mailfrom == '\0')
521 					fprintf(mail, "From: Cron Daemon <%s@%s>\n",
522 					    usernm, hostname);
523 				else
524 					fprintf(mail, "From: Cron Daemon <%s>\n",
525 					    mailfrom);
526 				fprintf(mail, "To: %s\n", mailto);
527 				fprintf(mail, "Subject: Cron <%s@%s> %s\n",
528 					usernm, first_word(hostname, "."),
529 					e->cmd);
530 # if defined(MAIL_DATE)
531 				fprintf(mail, "Date: %s\n",
532 					arpadate(&TargetTime));
533 # endif /* MAIL_DATE */
534 				for (env = e->envp;  *env;  env++)
535 					fprintf(mail, "X-Cron-Env: <%s>\n",
536 						*env);
537 				fprintf(mail, "\n");
538 
539 				/* this was the first char from the pipe
540 				 */
541 				putc(ch, mail);
542 			}
543 
544 			/* we have to read the input pipe no matter whether
545 			 * we mail or not, but obviously we only write to
546 			 * mail pipe if we ARE mailing.
547 			 */
548 
549 			while (EOF != (ch = getc(in))) {
550 				bytes++;
551 				if (mail)
552 					putc(ch, mail);
553 			}
554 		}
555 		/*if data from grandchild*/
556 
557 		Debug(DPROC, ("[%d] got EOF from grandchild\n", getpid()))
558 
559 		/* also closes stdout_pipe[READ_PIPE] */
560 		fclose(in);
561 	}
562 
563 	/* wait for children to die.
564 	 */
565 	if (jobpid > 0) {
566 		WAIT_T	waiter;
567 
568 		waiter = wait_on_child(jobpid, "grandchild command job");
569 
570 		/* If everything went well, and -n was set, _and_ we have mail,
571 		 * we won't be mailing... so shoot the messenger!
572 		 */
573 		if (WIFEXITED(waiter) && WEXITSTATUS(waiter) == 0
574 		    && (e->flags & MAIL_WHEN_ERR) == MAIL_WHEN_ERR
575 		    && mail) {
576 			Debug(DPROC, ("[%d] %s executed successfully, mail suppressed\n",
577 				getpid(), "grandchild command job"))
578 			kill(mailpid, SIGKILL);
579 			(void)fclose(mail);
580 			mail = NULL;
581 		}
582 
583 
584 		/* only close pipe if we opened it -- i.e., we're
585 		 * mailing...
586 		 */
587 
588 		if (mail) {
589 			Debug(DPROC, ("[%d] closing pipe to mail\n",
590 				getpid()))
591 			/* Note: the pclose will probably see
592 			 * the termination of the grandchild
593 			 * in addition to the mail process, since
594 			 * it (the grandchild) is likely to exit
595 			 * after closing its stdout.
596 			 */
597 			status = cron_pclose(mail);
598 
599 			/* if there was output and we could not mail it,
600 			 * log the facts so the poor user can figure out
601 			 * what's going on.
602 			 */
603 			if (status) {
604 				char buf[MAX_TEMPSTR];
605 
606 				snprintf(buf, sizeof(buf),
607 			"mailed %d byte%s of output but got status 0x%04x\n",
608 					bytes, (bytes==1)?"":"s",
609 					status);
610 				log_it(usernm, getpid(), "MAIL", buf);
611 			}
612 		}
613 	}
614 
615 	if (*input_data && stdinjob > 0)
616 		wait_on_child(stdinjob, "grandchild stdinjob");
617 }
618 
619 static WAIT_T
620 wait_on_child(PID_T childpid, const char *name) {
621 	WAIT_T	waiter;
622 	PID_T	pid;
623 
624 	Debug(DPROC, ("[%d] waiting for %s (%d) to finish\n",
625 		getpid(), name, childpid))
626 
627 #ifdef POSIX
628 	while ((pid = waitpid(childpid, &waiter, 0)) < 0 && errno == EINTR)
629 #else
630 	while ((pid = wait4(childpid, &waiter, 0, NULL)) < 0 && errno == EINTR)
631 #endif
632 		;
633 
634 	if (pid < OK)
635 		return waiter;
636 
637 	Debug(DPROC, ("[%d] %s (%d) finished, status=%04x",
638 		getpid(), name, pid, WEXITSTATUS(waiter)))
639 	if (WIFSIGNALED(waiter) && WCOREDUMP(waiter))
640 		Debug(DPROC, (", dumped core"))
641 	Debug(DPROC, ("\n"))
642 
643 	return waiter;
644 }
645 
646 
647 static void
648 do_univ(u)
649 	user	*u;
650 {
651 #if defined(sequent)
652 /* Dynix (Sequent) hack to put the user associated with
653  * the passed user structure into the ATT universe if
654  * necessary.  We have to dig the gecos info out of
655  * the user's password entry to see if the magic
656  * "universe(att)" string is present.
657  */
658 
659 	struct	passwd	*p;
660 	char	*s;
661 	int	i;
662 
663 	p = getpwuid(u->uid);
664 	(void) endpwent();
665 
666 	if (p == NULL)
667 		return;
668 
669 	s = p->pw_gecos;
670 
671 	for (i = 0; i < 4; i++)
672 	{
673 		if ((s = strchr(s, ',')) == NULL)
674 			return;
675 		s++;
676 	}
677 	if (strcmp(s, "universe(att)"))
678 		return;
679 
680 	(void) universe(U_ATT);
681 #endif
682 }
683