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