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