xref: /netbsd-src/external/bsd/cron/dist/do_command.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*	$NetBSD: do_command.c,v 1.7 2015/12/17 22:36:48 christos Exp $	*/
2 
3 /* Copyright 1988,1990,1993,1994 by Paul Vixie
4  * All rights reserved
5  */
6 
7 /*
8  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
9  * Copyright (c) 1997,2000 by Internet Software Consortium, Inc.
10  *
11  * Permission to use, copy, modify, and distribute this software for any
12  * purpose with or without fee is hereby granted, provided that the above
13  * copyright notice and this permission notice appear in all copies.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
16  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
18  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23 #include <sys/cdefs.h>
24 #if !defined(lint) && !defined(LINT)
25 #if 0
26 static char rcsid[] = "Id: do_command.c,v 1.9 2004/01/23 18:56:42 vixie Exp";
27 #else
28 __RCSID("$NetBSD: do_command.c,v 1.7 2015/12/17 22:36:48 christos Exp $");
29 #endif
30 #endif
31 
32 #include "cron.h"
33 #include <unistd.h>
34 
35 static void		child_process(entry *);
36 static int		safe_p(const char *, const char *);
37 
38 void
39 do_command(entry *e, user *u) {
40 	Debug(DPROC, ("[%ld] do_command(%s, (%s,%ld,%ld))\n",
41 		      (long)getpid(), e->cmd, u->name,
42 		      (long)e->pwd->pw_uid, (long)e->pwd->pw_gid));
43 
44 	/* fork to become asynchronous -- parent process is done immediately,
45 	 * and continues to run the normal cron code, which means return to
46 	 * tick().  the child and grandchild don't leave this function, alive.
47 	 *
48 	 * vfork() is unsuitable, since we have much to do, and the parent
49 	 * needs to be able to run off and fork other processes.
50 	 */
51 	switch (fork()) {
52 	case -1:
53 		log_it("CRON", getpid(), "error", "can't fork");
54 		break;
55 	case 0:
56 		/* child process */
57 		acquire_daemonlock(1);
58 		child_process(e);
59 		Debug(DPROC, ("[%ld] child process done, exiting\n",
60 			      (long)getpid()));
61 		_exit(OK_EXIT);
62 		break;
63 	default:
64 		/* parent process */
65 		break;
66 	}
67 	Debug(DPROC, ("[%ld] main process returning to work\n",(long)getpid()));
68 }
69 
70 static void
71 child_process(entry *e) {
72 	int stdin_pipe[2], stdout_pipe[2];
73 	char * volatile input_data;
74 	char *homedir, *usernm, * volatile mailto;
75 	int children = 0;
76 
77 	Debug(DPROC, ("[%ld] child_process('%s')\n", (long)getpid(), e->cmd));
78 
79 	setproctitle("running job");
80 
81 	/* discover some useful and important environment settings
82 	 */
83 	usernm = e->pwd->pw_name;
84 	mailto = env_get("MAILTO", e->envp);
85 
86 	/* our parent is watching for our death by catching SIGCHLD.  we
87 	 * do not care to watch for our children's deaths this way -- we
88 	 * use wait() explicitly.  so we have to reset the signal (which
89 	 * was inherited from the parent).
90 	 */
91 	(void) signal(SIGCHLD, SIG_DFL);
92 
93 	/* create some pipes to talk to our future child
94 	 */
95 	if (pipe(stdin_pipe) == -1) 	/* child's stdin */
96 		log_it("CRON", getpid(), "error", "create child stdin pipe");
97 	if (pipe(stdout_pipe) == -1)	/* child's stdout */
98 		log_it("CRON", getpid(), "error", "create child stdout pipe");
99 
100 	/* since we are a forked process, we can diddle the command string
101 	 * we were passed -- nobody else is going to use it again, right?
102 	 *
103 	 * if a % is present in the command, previous characters are the
104 	 * command, and subsequent characters are the additional input to
105 	 * the command.  An escaped % will have the escape character stripped
106 	 * from it.  Subsequent %'s will be transformed into newlines,
107 	 * but that happens later.
108 	 */
109 	/*local*/{
110 		int escaped = FALSE;
111 		int ch;
112 		char *p;
113 
114 		/* translation:
115 		 *	\% -> %
116 		 *	%  -> end of command, following is command input.
117 		 *	\x -> \x	for all x != %
118 		 */
119 		input_data = p = e->cmd;
120 		while ((ch = *input_data++) != '\0') {
121  			if (escaped) {
122 				if (ch != '%')
123 					*p++ = '\\';
124 			} else {
125 				if (ch == '%') {
126 					break;
127 				}
128 			}
129 
130 			if (!(escaped = (ch == '\\'))) {
131 				*p++ = (char)ch;
132 			}
133 		}
134 		if (ch == '\0') {
135 			/* move pointer back, so that code below
136 			 * won't think we encountered % sequence */
137 			input_data--;
138 		}
139 		if (escaped)
140 			*p++ = '\\';
141 
142 		*p = '\0';
143 	}
144 
145 	/* fork again, this time so we can exec the user's command.
146 	 */
147 	switch (vfork()) {
148 	case -1:
149 		log_it("CRON", getpid(), "error", "can't vfork");
150 		exit(ERROR_EXIT);
151 		/*NOTREACHED*/
152 	case 0:
153 		Debug(DPROC, ("[%ld] grandchild process vfork()'ed\n",
154 			      (long)getpid()));
155 
156 		/* write a log message.  we've waited this long to do it
157 		 * because it was not until now that we knew the PID that
158 		 * the actual user command shell was going to get and the
159 		 * PID is part of the log message.
160 		 */
161 		if ((e->flags & DONT_LOG) == 0) {
162 			char *x = mkprints(e->cmd, strlen(e->cmd));
163 
164 			log_it(usernm, getpid(), "CMD START", x);
165 			free(x);
166 		}
167 
168 		/* that's the last thing we'll log.  close the log files.
169 		 */
170 		log_close();
171 
172 		/* get new pgrp, void tty, etc.
173 		 */
174 		if (setsid() == -1)
175 			syslog(LOG_ERR, "setsid() failure: %m");
176 
177 		/* close the pipe ends that we won't use.  this doesn't affect
178 		 * the parent, who has to read and write them; it keeps the
179 		 * kernel from recording us as a potential client TWICE --
180 		 * which would keep it from sending SIGPIPE in otherwise
181 		 * appropriate circumstances.
182 		 */
183 		(void)close(stdin_pipe[WRITE_PIPE]);
184 		(void)close(stdout_pipe[READ_PIPE]);
185 
186 		/* grandchild process.  make std{in,out} be the ends of
187 		 * pipes opened by our daddy; make stderr go to stdout.
188 		 */
189 		if (stdin_pipe[READ_PIPE] != STDIN) {
190 			(void)dup2(stdin_pipe[READ_PIPE], STDIN);
191 			(void)close(stdin_pipe[READ_PIPE]);
192 		}
193 		if (stdout_pipe[WRITE_PIPE] != STDOUT) {
194 			(void)dup2(stdout_pipe[WRITE_PIPE], STDOUT);
195 			(void)close(stdout_pipe[WRITE_PIPE]);
196 		}
197 		(void)dup2(STDOUT, STDERR);
198 
199 		/* set our directory, uid and gid.  Set gid first, since once
200 		 * we set uid, we've lost root privledges.
201 		 */
202 #ifdef LOGIN_CAP
203 		{
204 #ifdef BSD_AUTH
205 			auth_session_t *as;
206 #endif
207 			login_cap_t *lc;
208 			char *p;
209 
210 			if ((lc = login_getclass(e->pwd->pw_class)) == NULL) {
211 				warnx("unable to get login class for `%s'",
212 				    e->pwd->pw_name);
213 				_exit(ERROR_EXIT);
214 			}
215 			if (setusercontext(lc, e->pwd, e->pwd->pw_uid, LOGIN_SETALL) < 0) {
216 				warnx("setusercontext failed for `%s'",
217 				    e->pwd->pw_name);
218 				_exit(ERROR_EXIT);
219 			}
220 #ifdef BSD_AUTH
221 			as = auth_open();
222 			if (as == NULL || auth_setpwd(as, e->pwd) != 0) {
223 				warn("can't malloc");
224 				_exit(ERROR_EXIT);
225 			}
226 			if (auth_approval(as, lc, usernm, "cron") <= 0) {
227 				warnx("approval failed for `%s'",
228 				    e->pwd->pw_name);
229 				_exit(ERROR_EXIT);
230 			}
231 			auth_close(as);
232 #endif /* BSD_AUTH */
233 			login_close(lc);
234 
235 			/* If no PATH specified in crontab file but
236 			 * we just added one via login.conf, add it to
237 			 * the crontab environment.
238 			 */
239 			if (env_get("PATH", e->envp) == NULL) {
240 				if ((p = getenv("PATH")) != NULL)
241 					e->envp = env_set(e->envp, p);
242 			}
243 		}
244 #else
245 		if (setgid(e->pwd->pw_gid) != 0) {
246 			syslog(LOG_ERR, "setgid(%d) failed for %s: %m",
247 			    e->pwd->pw_gid, e->pwd->pw_name);
248 			_exit(ERROR_EXIT);
249 		}
250 		if (initgroups(usernm, e->pwd->pw_gid) != 0) {
251 			syslog(LOG_ERR, "initgroups(%s, %d) failed for %s: %m",
252 			    usernm, e->pwd->pw_gid, e->pwd->pw_name);
253 			_exit(ERROR_EXIT);
254 		}
255 #if (defined(BSD)) && (BSD >= 199103)
256 		if (setlogin(usernm) < 0) {
257 			syslog(LOG_ERR, "setlogin(%s) failure for %s: %m",
258 			    usernm, e->pwd->pw_name);
259 			_exit(ERROR_EXIT);
260 		}
261 #endif /* BSD */
262 		if (setuid(e->pwd->pw_uid) != 0) {
263 			syslog(LOG_ERR, "setuid(%d) failed for %s: %m",
264 			    e->pwd->pw_uid, e->pwd->pw_name);
265 			_exit(ERROR_EXIT);
266 		}
267 		/* we aren't root after this... */
268 #endif /* LOGIN_CAP */
269 		homedir = env_get("HOME", e->envp);
270 		if (chdir(homedir) != 0) {
271 			syslog(LOG_ERR, "chdir(%s) $HOME failed for %s: %m",
272 			    homedir, e->pwd->pw_name);
273 			_exit(ERROR_EXIT);
274 		}
275 
276 #ifdef USE_SIGCHLD
277 		/* our grandparent is watching for our death by catching
278 		 * SIGCHLD.  the parent is ignoring SIGCHLD's; we want
279 		 * to restore default behaviour.
280 		 */
281 		(void) signal(SIGCHLD, SIG_DFL);
282 #endif
283 		(void) signal(SIGHUP, SIG_DFL);
284 
285 		/*
286 		 * Exec the command.
287 		 */
288 		{
289 			char	*shell = env_get("SHELL", e->envp);
290 
291 # if DEBUGGING
292 			if (DebugFlags & DTEST) {
293 				(void)fprintf(stderr,
294 				"debug DTEST is on, not exec'ing command.\n");
295 				(void)fprintf(stderr,
296 				"\tcmd='%s' shell='%s'\n", e->cmd, shell);
297 				_exit(OK_EXIT);
298 			}
299 # endif /*DEBUGGING*/
300 			(void)execle(shell, shell, "-c", e->cmd, NULL, e->envp);
301 			warn("execl: couldn't exec `%s'", shell);
302 			_exit(ERROR_EXIT);
303 		}
304 		break;
305 	default:
306 		/* parent process */
307 		break;
308 	}
309 
310 	children++;
311 
312 	/* middle process, child of original cron, parent of process running
313 	 * the user's command.
314 	 */
315 
316 	Debug(DPROC, ("[%ld] child continues, closing pipes\n",(long)getpid()));
317 
318 	/* close the ends of the pipe that will only be referenced in the
319 	 * grandchild process...
320 	 */
321 	(void)close(stdin_pipe[READ_PIPE]);
322 	(void)close(stdout_pipe[WRITE_PIPE]);
323 
324 	/*
325 	 * write, to the pipe connected to child's stdin, any input specified
326 	 * after a % in the crontab entry.  while we copy, convert any
327 	 * additional %'s to newlines.  when done, if some characters were
328 	 * written and the last one wasn't a newline, write a newline.
329 	 *
330 	 * Note that if the input data won't fit into one pipe buffer (2K
331 	 * or 4K on most BSD systems), and the child doesn't read its stdin,
332 	 * we would block here.  thus we must fork again.
333 	 */
334 
335 	if (*input_data && fork() == 0) {
336 		FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w");
337 		int need_newline = FALSE;
338 		int escaped = FALSE;
339 		int ch;
340 
341 		Debug(DPROC, ("[%ld] child2 sending data to grandchild\n",
342 			      (long)getpid()));
343 
344 		/* close the pipe we don't use, since we inherited it and
345 		 * are part of its reference count now.
346 		 */
347 		(void)close(stdout_pipe[READ_PIPE]);
348 
349 		/* translation:
350 		 *	\% -> %
351 		 *	%  -> \n
352 		 *	\x -> \x	for all x != %
353 		 */
354 		while ((ch = *input_data++) != '\0') {
355 			if (escaped) {
356 				if (ch != '%')
357 					(void)putc('\\', out);
358 			} else {
359 				if (ch == '%')
360 					ch = '\n';
361 			}
362 
363 			if (!(escaped = (ch == '\\'))) {
364 				(void)putc(ch, out);
365 				need_newline = (ch != '\n');
366 			}
367 		}
368 		if (escaped)
369 			(void)putc('\\', out);
370 		if (need_newline)
371 			(void)putc('\n', out);
372 
373 		/* close the pipe, causing an EOF condition.  fclose causes
374 		 * stdin_pipe[WRITE_PIPE] to be closed, too.
375 		 */
376 		(void)fclose(out);
377 
378 		Debug(DPROC, ("[%ld] child2 done sending to grandchild\n",
379 			      (long)getpid()));
380 		exit(0);
381 	}
382 
383 	/* close the pipe to the grandkiddie's stdin, since its wicked uncle
384 	 * ernie back there has it open and will close it when he's done.
385 	 */
386 	(void)close(stdin_pipe[WRITE_PIPE]);
387 
388 	children++;
389 
390 	/*
391 	 * read output from the grandchild.  it's stderr has been redirected to
392 	 * it's stdout, which has been redirected to our pipe.  if there is any
393 	 * output, we'll be mailing it to the user whose crontab this is...
394 	 * when the grandchild exits, we'll get EOF.
395 	 */
396 
397 	Debug(DPROC, ("[%ld] child reading output from grandchild\n",
398 		      (long)getpid()));
399 
400 	/*local*/{
401 		FILE	*in = fdopen(stdout_pipe[READ_PIPE], "r");
402 		int	ch = getc(in);
403 
404 		if (ch != EOF) {
405 			FILE	*mail = NULL;
406 			int	bytes = 1;
407 			int	status = 0;
408 
409 			Debug(DPROC|DEXT,
410 			      ("[%ld] got data (%x:%c) from grandchild\n",
411 			       (long)getpid(), ch, ch));
412 
413 			/* get name of recipient.  this is MAILTO if set to a
414 			 * valid local username; USER otherwise.
415 			 */
416 			if (mailto) {
417 				/* MAILTO was present in the environment
418 				 */
419 				if (!*mailto) {
420 					/* ... but it's empty. set to NULL
421 					 */
422 					mailto = NULL;
423 				}
424 			} else {
425 				/* MAILTO not present, set to USER.
426 				 */
427 				mailto = usernm;
428 			}
429 
430 			/* if we are supposed to be mailing, MAILTO will
431 			 * be non-NULL.  only in this case should we set
432 			 * up the mail command and subjects and stuff...
433 			 */
434 
435 			if (mailto && safe_p(usernm, mailto)) {
436 				char	**env;
437 				char	mailcmd[MAX_COMMAND];
438 				char	hostname[MAXHOSTNAMELEN + 1];
439 
440 				(void)gethostname(hostname, MAXHOSTNAMELEN);
441 				if (strlens(MAILFMT, MAILARG, NULL) + 1
442 				    >= sizeof mailcmd) {
443 					warnx("mailcmd too long");
444 					(void) _exit(ERROR_EXIT);
445 				}
446 				(void)snprintf(mailcmd, sizeof(mailcmd),
447 				    MAILFMT, MAILARG);
448 				if (!(mail = cron_popen(mailcmd, "w", e->pwd))) {
449 					warn("cannot run `%s'", mailcmd);
450 					(void) _exit(ERROR_EXIT);
451 				}
452 				(void)fprintf(mail,
453 				    "From: root (Cron Daemon)\n");
454 				(void)fprintf(mail, "To: %s\n", mailto);
455 				(void)fprintf(mail,
456 				    "Subject: Cron <%s@%s> %s\n",
457 				    usernm, hostname, e->cmd);
458 				(void)fprintf(mail,
459 				    "Auto-Submitted: auto-generated\n");
460 #ifdef MAIL_DATE
461 				(void)fprintf(mail, "Date: %s\n",
462 					arpadate(&StartTime));
463 #endif /*MAIL_DATE*/
464 				for (env = e->envp;  *env;  env++)
465 					(void)fprintf(mail,
466 					    "X-Cron-Env: <%s>\n", *env);
467 				(void)fprintf(mail, "\n");
468 
469 				/* this was the first char from the pipe
470 				 */
471 				(void)putc(ch, mail);
472 			}
473 
474 			/* we have to read the input pipe no matter whether
475 			 * we mail or not, but obviously we only write to
476 			 * mail pipe if we ARE mailing.
477 			 */
478 
479 			while (EOF != (ch = getc(in))) {
480 				bytes++;
481 				if (mailto)
482 					(void)putc(ch, mail);
483 			}
484 
485 			/* only close pipe if we opened it -- i.e., we're
486 			 * mailing...
487 			 */
488 
489 			if (mailto) {
490 				Debug(DPROC, ("[%ld] closing pipe to mail\n",
491 					      (long)getpid()));
492 				/* Note: the pclose will probably see
493 				 * the termination of the grandchild
494 				 * in addition to the mail process, since
495 				 * it (the grandchild) is likely to exit
496 				 * after closing its stdout.
497 				 */
498 				status = cron_pclose(mail);
499 			}
500 
501 			/* if there was output and we could not mail it,
502 			 * log the facts so the poor user can figure out
503 			 * what's going on.
504 			 */
505 			if (mailto && status) {
506 				char buf[MAX_TEMPSTR];
507 
508 				(void)snprintf(buf, sizeof(buf),
509 			"mailed %d byte%s of output but got status 0x%04x\n",
510 					bytes, (bytes==1)?"":"s",
511 					status);
512 				log_it(usernm, getpid(), "MAIL", buf);
513 			}
514 
515 		} /*if data from grandchild*/
516 
517 		Debug(DPROC, ("[%ld] got EOF from grandchild\n",
518 			      (long)getpid()));
519 
520 		(void)fclose(in);	/* also closes stdout_pipe[READ_PIPE] */
521 	}
522 
523 	/* wait for children to die.
524 	 */
525 	for (; children > 0; children--) {
526 		WAIT_T waiter;
527 		PID_T pid;
528 
529 		Debug(DPROC, ("[%ld] waiting for grandchild #%d to finish\n",
530 			      (long)getpid(), children));
531 		while ((pid = wait(&waiter)) < OK && errno == EINTR)
532 			;
533 		if (pid < OK) {
534 			Debug(DPROC,
535 			      ("[%ld] no more grandchildren--mail written?\n",
536 			       (long)getpid()));
537 			break;
538 		}
539 		Debug(DPROC, ("[%ld] grandchild #%ld finished, status=%04x",
540 			      (long)getpid(), (long)pid, WEXITSTATUS(waiter)));
541 		if (WIFSIGNALED(waiter) && WCOREDUMP(waiter))
542 			Debug(DPROC, (", dumped core"));
543 		Debug(DPROC, ("\n"));
544 	}
545 
546 	/* Log the time when we finished deadling with the job */
547 	/*local*/{
548 		char *x = mkprints(e->cmd, strlen(e->cmd));
549 
550 		log_it(usernm, getpid(), "CMD FINISH", x);
551 		free(x);
552 	}
553 }
554 
555 static int
556 safe_p(const char *usernm, const char *s) {
557 	static const char safe_delim[] = "@!:%-.,";     /* conservative! */
558 	const char *t;
559 	int ch, first;
560 
561 	for (t = s, first = 1; (ch = *t++) != '\0'; first = 0) {
562 		if (isascii(ch) && isprint(ch) &&
563 		    (isalnum(ch) || (!first && strchr(safe_delim, ch))))
564 			continue;
565 		log_it(usernm, getpid(), "UNSAFE", s);
566 		return (FALSE);
567 	}
568 	return (TRUE);
569 }
570