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