xref: /netbsd-src/external/bsd/cron/dist/do_command.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: do_command.c,v 1.2 2010/05/06 18:53:17 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.2 2010/05/06 18:53:17 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 *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++ = 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 failed");
247 			_exit(ERROR_EXIT);
248 		}
249 		if (initgroups(usernm, e->pwd->pw_gid) != 0) {
250 			syslog(LOG_ERR, "initgroups failed");
251 			_exit(ERROR_EXIT);
252 		}
253 #if (defined(BSD)) && (BSD >= 199103)
254 		if (setlogin(usernm) < 0) {
255 			syslog(LOG_ERR, "setlogin() failure: %m");
256 			_exit(ERROR_EXIT);
257 		}
258 
259 		setlogin(usernm);
260 #endif /* BSD */
261 		if (setuid(e->pwd->pw_uid) != 0) {
262 			syslog(LOG_ERR, "setuid failed");
263 			_exit(ERROR_EXIT);
264 		}
265 		/* we aren't root after this... */
266 #endif /* LOGIN_CAP */
267 
268 		if (chdir(env_get("HOME", e->envp)) != 0) {
269 			syslog(LOG_ERR, "chdir $HOME failed");
270 			_exit(ERROR_EXIT);
271 		}
272 
273 #ifdef USE_SIGCHLD
274 		/* our grandparent is watching for our death by catching
275 		 * SIGCHLD.  the parent is ignoring SIGCHLD's; we want
276 		 * to restore default behaviour.
277 		 */
278 		(void) signal(SIGCHLD, SIG_DFL);
279 #endif
280 		(void) signal(SIGHUP, SIG_DFL);
281 
282 		/*
283 		 * Exec the command.
284 		 */
285 		{
286 			char	*shell = env_get("SHELL", e->envp);
287 
288 # if DEBUGGING
289 			if (DebugFlags & DTEST) {
290 				(void)fprintf(stderr,
291 				"debug DTEST is on, not exec'ing command.\n");
292 				(void)fprintf(stderr,
293 				"\tcmd='%s' shell='%s'\n", e->cmd, shell);
294 				_exit(OK_EXIT);
295 			}
296 # endif /*DEBUGGING*/
297 			(void)execle(shell, shell, "-c", e->cmd, NULL, e->envp);
298 			warn("execl: couldn't exec `%s'", shell);
299 			_exit(ERROR_EXIT);
300 		}
301 		break;
302 	default:
303 		/* parent process */
304 		break;
305 	}
306 
307 	children++;
308 
309 	/* middle process, child of original cron, parent of process running
310 	 * the user's command.
311 	 */
312 
313 	Debug(DPROC, ("[%ld] child continues, closing pipes\n",(long)getpid()));
314 
315 	/* close the ends of the pipe that will only be referenced in the
316 	 * grandchild process...
317 	 */
318 	(void)close(stdin_pipe[READ_PIPE]);
319 	(void)close(stdout_pipe[WRITE_PIPE]);
320 
321 	/*
322 	 * write, to the pipe connected to child's stdin, any input specified
323 	 * after a % in the crontab entry.  while we copy, convert any
324 	 * additional %'s to newlines.  when done, if some characters were
325 	 * written and the last one wasn't a newline, write a newline.
326 	 *
327 	 * Note that if the input data won't fit into one pipe buffer (2K
328 	 * or 4K on most BSD systems), and the child doesn't read its stdin,
329 	 * we would block here.  thus we must fork again.
330 	 */
331 
332 	if (*input_data && fork() == 0) {
333 		FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w");
334 		int need_newline = FALSE;
335 		int escaped = FALSE;
336 		int ch;
337 
338 		Debug(DPROC, ("[%ld] child2 sending data to grandchild\n",
339 			      (long)getpid()));
340 
341 		/* close the pipe we don't use, since we inherited it and
342 		 * are part of its reference count now.
343 		 */
344 		(void)close(stdout_pipe[READ_PIPE]);
345 
346 		/* translation:
347 		 *	\% -> %
348 		 *	%  -> \n
349 		 *	\x -> \x	for all x != %
350 		 */
351 		while ((ch = *input_data++) != '\0') {
352 			if (escaped) {
353 				if (ch != '%')
354 					(void)putc('\\', out);
355 			} else {
356 				if (ch == '%')
357 					ch = '\n';
358 			}
359 
360 			if (!(escaped = (ch == '\\'))) {
361 				(void)putc(ch, out);
362 				need_newline = (ch != '\n');
363 			}
364 		}
365 		if (escaped)
366 			(void)putc('\\', out);
367 		if (need_newline)
368 			(void)putc('\n', out);
369 
370 		/* close the pipe, causing an EOF condition.  fclose causes
371 		 * stdin_pipe[WRITE_PIPE] to be closed, too.
372 		 */
373 		(void)fclose(out);
374 
375 		Debug(DPROC, ("[%ld] child2 done sending to grandchild\n",
376 			      (long)getpid()));
377 		exit(0);
378 	}
379 
380 	/* close the pipe to the grandkiddie's stdin, since its wicked uncle
381 	 * ernie back there has it open and will close it when he's done.
382 	 */
383 	(void)close(stdin_pipe[WRITE_PIPE]);
384 
385 	children++;
386 
387 	/*
388 	 * read output from the grandchild.  it's stderr has been redirected to
389 	 * it's stdout, which has been redirected to our pipe.  if there is any
390 	 * output, we'll be mailing it to the user whose crontab this is...
391 	 * when the grandchild exits, we'll get EOF.
392 	 */
393 
394 	Debug(DPROC, ("[%ld] child reading output from grandchild\n",
395 		      (long)getpid()));
396 
397 	/*local*/{
398 		FILE	*in = fdopen(stdout_pipe[READ_PIPE], "r");
399 		int	ch = getc(in);
400 
401 		if (ch != EOF) {
402 			FILE	*mail = NULL;
403 			int	bytes = 1;
404 			int	status = 0;
405 
406 			Debug(DPROC|DEXT,
407 			      ("[%ld] got data (%x:%c) from grandchild\n",
408 			       (long)getpid(), ch, ch));
409 
410 			/* get name of recipient.  this is MAILTO if set to a
411 			 * valid local username; USER otherwise.
412 			 */
413 			if (mailto) {
414 				/* MAILTO was present in the environment
415 				 */
416 				if (!*mailto) {
417 					/* ... but it's empty. set to NULL
418 					 */
419 					mailto = NULL;
420 				}
421 			} else {
422 				/* MAILTO not present, set to USER.
423 				 */
424 				mailto = usernm;
425 			}
426 
427 			/* if we are supposed to be mailing, MAILTO will
428 			 * be non-NULL.  only in this case should we set
429 			 * up the mail command and subjects and stuff...
430 			 */
431 
432 			if (mailto && safe_p(usernm, mailto)) {
433 				char	**env;
434 				char	mailcmd[MAX_COMMAND];
435 				char	hostname[MAXHOSTNAMELEN + 1];
436 
437 				(void)gethostname(hostname, MAXHOSTNAMELEN);
438 				if (strlens(MAILFMT, MAILARG, NULL) + 1
439 				    >= sizeof mailcmd) {
440 					warnx("mailcmd too long");
441 					(void) _exit(ERROR_EXIT);
442 				}
443 				(void)snprintf(mailcmd, sizeof(mailcmd),
444 				    MAILFMT, MAILARG);
445 				if (!(mail = cron_popen(mailcmd, "w", e->pwd))) {
446 					warn("cannot run `%s'", mailcmd);
447 					(void) _exit(ERROR_EXIT);
448 				}
449 				(void)fprintf(mail,
450 				    "From: root (Cron Daemon)\n");
451 				(void)fprintf(mail, "To: %s\n", mailto);
452 				(void)fprintf(mail,
453 				    "Subject: Cron <%s@%s> %s\n",
454 				    usernm, first_word(hostname, "."), e->cmd);
455 				(void)fprintf(mail,
456 				    "Auto-Submitted: auto-generated\n");
457 #ifdef MAIL_DATE
458 				(void)fprintf(mail, "Date: %s\n",
459 					arpadate(&StartTime));
460 #endif /*MAIL_DATE*/
461 				for (env = e->envp;  *env;  env++)
462 					(void)fprintf(mail,
463 					    "X-Cron-Env: <%s>\n", *env);
464 				(void)fprintf(mail, "\n");
465 
466 				/* this was the first char from the pipe
467 				 */
468 				(void)putc(ch, mail);
469 			}
470 
471 			/* we have to read the input pipe no matter whether
472 			 * we mail or not, but obviously we only write to
473 			 * mail pipe if we ARE mailing.
474 			 */
475 
476 			while (EOF != (ch = getc(in))) {
477 				bytes++;
478 				if (mailto)
479 					(void)putc(ch, mail);
480 			}
481 
482 			/* only close pipe if we opened it -- i.e., we're
483 			 * mailing...
484 			 */
485 
486 			if (mailto) {
487 				Debug(DPROC, ("[%ld] closing pipe to mail\n",
488 					      (long)getpid()));
489 				/* Note: the pclose will probably see
490 				 * the termination of the grandchild
491 				 * in addition to the mail process, since
492 				 * it (the grandchild) is likely to exit
493 				 * after closing its stdout.
494 				 */
495 				status = cron_pclose(mail);
496 			}
497 
498 			/* if there was output and we could not mail it,
499 			 * log the facts so the poor user can figure out
500 			 * what's going on.
501 			 */
502 			if (mailto && status) {
503 				char buf[MAX_TEMPSTR];
504 
505 				(void)snprintf(buf, sizeof(buf),
506 			"mailed %d byte%s of output but got status 0x%04x\n",
507 					bytes, (bytes==1)?"":"s",
508 					status);
509 				log_it(usernm, getpid(), "MAIL", buf);
510 			}
511 
512 		} /*if data from grandchild*/
513 
514 		Debug(DPROC, ("[%ld] got EOF from grandchild\n",
515 			      (long)getpid()));
516 
517 		(void)fclose(in);	/* also closes stdout_pipe[READ_PIPE] */
518 	}
519 
520 	/* wait for children to die.
521 	 */
522 	for (; children > 0; children--) {
523 		WAIT_T waiter;
524 		PID_T pid;
525 
526 		Debug(DPROC, ("[%ld] waiting for grandchild #%d to finish\n",
527 			      (long)getpid(), children));
528 		while ((pid = wait(&waiter)) < OK && errno == EINTR)
529 			;
530 		if (pid < OK) {
531 			Debug(DPROC,
532 			      ("[%ld] no more grandchildren--mail written?\n",
533 			       (long)getpid()));
534 			break;
535 		}
536 		Debug(DPROC, ("[%ld] grandchild #%ld finished, status=%04x",
537 			      (long)getpid(), (long)pid, WEXITSTATUS(waiter)));
538 		if (WIFSIGNALED(waiter) && WCOREDUMP(waiter))
539 			Debug(DPROC, (", dumped core"));
540 		Debug(DPROC, ("\n"));
541 	}
542 
543 	/* Log the time when we finished deadling with the job */
544 	/*local*/{
545 		char *x = mkprints(e->cmd, strlen(e->cmd));
546 
547 		log_it(usernm, getpid(), "CMD FINISH", x);
548 		free(x);
549 	}
550 }
551 
552 static int
553 safe_p(const char *usernm, const char *s) {
554 	static const char safe_delim[] = "@!:%-.,";     /* conservative! */
555 	const char *t;
556 	int ch, first;
557 
558 	for (t = s, first = 1; (ch = *t++) != '\0'; first = 0) {
559 		if (isascii(ch) && isprint(ch) &&
560 		    (isalnum(ch) || (!first && strchr(safe_delim, ch))))
561 			continue;
562 		log_it(usernm, getpid(), "UNSAFE", s);
563 		return (FALSE);
564 	}
565 	return (TRUE);
566 }
567