1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # include <sys/stat.h>
5 
6 SCCSID(@(#)deliver.c	3.145		01/06/83);
7 
8 /*
9 **  DELIVER -- Deliver a message to a list of addresses.
10 **
11 **	This routine delivers to everyone on the same host as the
12 **	user on the head of the list.  It is clever about mailers
13 **	that don't handle multiple users.  It is NOT guaranteed
14 **	that it will deliver to all these addresses however -- so
15 **	deliver should be called once for each address on the
16 **	list.
17 **
18 **	Parameters:
19 **		e -- the envelope to deliver.
20 **		firstto -- head of the address list to deliver to.
21 **
22 **	Returns:
23 **		zero -- successfully delivered.
24 **		else -- some failure, see ExitStat for more info.
25 **
26 **	Side Effects:
27 **		The standard input is passed off to someone.
28 */
29 
30 deliver(e, firstto)
31 	register ENVELOPE *e;
32 	ADDRESS *firstto;
33 {
34 	char *host;			/* host being sent to */
35 	char *user;			/* user being sent to */
36 	char **pvp;
37 	register char **mvp;
38 	register char *p;
39 	register MAILER *m;	/* mailer for this recipient */
40 	extern bool checkcompat();
41 	char *pv[MAXPV+1];
42 	char tobuf[MAXLINE-50];		/* text line of to people */
43 	char buf[MAXNAME];
44 	ADDRESS *ctladdr;
45 	extern ADDRESS *getctladdr();
46 	char tfrombuf[MAXNAME];		/* translated from person */
47 	extern char **prescan();
48 	register ADDRESS *to = firstto;
49 	bool clever = FALSE;		/* running user smtp to this mailer */
50 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
51 	register int rcode;		/* response code */
52 
53 	errno = 0;
54 	if (bitset(QDONTSEND, to->q_flags))
55 		return (0);
56 
57 	m = to->q_mailer;
58 	host = to->q_host;
59 
60 # ifdef DEBUG
61 	if (tTd(10, 1))
62 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
63 			m->m_mno, host, to->q_user);
64 # endif DEBUG
65 
66 	/*
67 	**  If this mailer is expensive, and if we don't want to make
68 	**  connections now, just mark these addresses and return.
69 	**	This is useful if we want to batch connections to
70 	**	reduce load.  This will cause the messages to be
71 	**	queued up, and a daemon will come along to send the
72 	**	messages later.
73 	**		This should be on a per-mailer basis.
74 	*/
75 
76 	if (NoConnect && !QueueRun && bitset(M_EXPENSIVE, m->m_flags) &&
77 	    !Verbose)
78 	{
79 		for (; to != NULL; to = to->q_next)
80 		{
81 			if (bitset(QDONTSEND, to->q_flags) || to->q_mailer != m)
82 				continue;
83 			to->q_flags |= QQUEUEUP|QDONTSEND;
84 			e->e_to = to->q_paddr;
85 			message(Arpa_Info, "queued");
86 			if (LogLevel > 4)
87 				logdelivery("queued");
88 		}
89 		e->e_to = NULL;
90 		return (0);
91 	}
92 
93 	/*
94 	**  Do initial argv setup.
95 	**	Insert the mailer name.  Notice that $x expansion is
96 	**	NOT done on the mailer name.  Then, if the mailer has
97 	**	a picky -f flag, we insert it as appropriate.  This
98 	**	code does not check for 'pv' overflow; this places a
99 	**	manifest lower limit of 4 for MAXPV.
100 	**		The from address rewrite is expected to make
101 	**		the address relative to the other end.
102 	*/
103 
104 	/* rewrite from address, using rewriting rules */
105 	expand("$f", buf, &buf[sizeof buf - 1], e);
106 	mvp = prescan(buf, '\0');
107 	rewrite(mvp, 3);
108 	rewrite(mvp, 1);
109 	rewrite(mvp, m->m_s_rwset);
110 	rewrite(mvp, 4);
111 	cataddr(mvp, tfrombuf, sizeof tfrombuf);
112 
113 	define('g', tfrombuf, e);		/* translated sender address */
114 	define('h', host, e);			/* to host */
115 	Errors = 0;
116 	pvp = pv;
117 	*pvp++ = m->m_argv[0];
118 
119 	/* insert -f or -r flag as appropriate */
120 	if (bitset(M_FOPT|M_ROPT, m->m_flags) && FromFlag)
121 	{
122 		if (bitset(M_FOPT, m->m_flags))
123 			*pvp++ = "-f";
124 		else
125 			*pvp++ = "-r";
126 		expand("$g", buf, &buf[sizeof buf - 1], e);
127 		*pvp++ = newstr(buf);
128 	}
129 
130 	/*
131 	**  Append the other fixed parts of the argv.  These run
132 	**  up to the first entry containing "$u".  There can only
133 	**  be one of these, and there are only a few more slots
134 	**  in the pv after it.
135 	*/
136 
137 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
138 	{
139 		while ((p = index(p, '$')) != NULL)
140 			if (*++p == 'u')
141 				break;
142 		if (p != NULL)
143 			break;
144 
145 		/* this entry is safe -- go ahead and process it */
146 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
147 		*pvp++ = newstr(buf);
148 		if (pvp >= &pv[MAXPV - 3])
149 		{
150 			syserr("Too many parameters to %s before $u", pv[0]);
151 			return (-1);
152 		}
153 	}
154 
155 	/*
156 	**  If we have no substitution for the user name in the argument
157 	**  list, we know that we must supply the names otherwise -- and
158 	**  SMTP is the answer!!
159 	*/
160 
161 	if (*mvp == NULL)
162 	{
163 		/* running SMTP */
164 # ifdef SMTP
165 		clever = TRUE;
166 		*pvp = NULL;
167 # else SMTP
168 		/* oops!  we don't implement SMTP */
169 		syserr("SMTP style mailer");
170 		return (EX_SOFTWARE);
171 # endif SMTP
172 	}
173 
174 	/*
175 	**  At this point *mvp points to the argument with $u.  We
176 	**  run through our address list and append all the addresses
177 	**  we can.  If we run out of space, do not fret!  We can
178 	**  always send another copy later.
179 	*/
180 
181 	tobuf[0] = '\0';
182 	e->e_to = tobuf;
183 	ctladdr = NULL;
184 	for (; to != NULL; to = to->q_next)
185 	{
186 		/* avoid sending multiple recipients to dumb mailers */
187 		if (tobuf[0] != '\0' && !bitset(M_MUSER, m->m_flags))
188 			break;
189 
190 		/* if already sent or not for this host, don't send */
191 		if (bitset(QDONTSEND, to->q_flags) ||
192 		    strcmp(to->q_host, host) != 0 ||
193 		    to->q_mailer != firstto->q_mailer)
194 			continue;
195 
196 		/* avoid overflowing tobuf */
197 		if (sizeof tobuf - (strlen(to->q_paddr) + strlen(tobuf) + 2) < 0)
198 			break;
199 
200 # ifdef DEBUG
201 		if (tTd(10, 1))
202 		{
203 			printf("\nsend to ");
204 			printaddr(to, FALSE);
205 		}
206 # endif DEBUG
207 
208 		/* compute effective uid/gid when sending */
209 		if (to->q_mailer == ProgMailer)
210 			ctladdr = getctladdr(to);
211 
212 		user = to->q_user;
213 		e->e_to = to->q_paddr;
214 		to->q_flags |= QDONTSEND;
215 
216 		/*
217 		**  Check to see that these people are allowed to
218 		**  talk to each other.
219 		*/
220 
221 		if (!checkcompat(to))
222 		{
223 			giveresponse(EX_UNAVAILABLE, m, e);
224 			continue;
225 		}
226 
227 		/*
228 		**  Strip quote bits from names if the mailer is dumb
229 		**	about them.
230 		*/
231 
232 		if (bitset(M_STRIPQ, m->m_flags))
233 		{
234 			stripquotes(user, TRUE);
235 			stripquotes(host, TRUE);
236 		}
237 		else
238 		{
239 			stripquotes(user, FALSE);
240 			stripquotes(host, FALSE);
241 		}
242 
243 		/* hack attack -- delivermail compatibility */
244 		if (m == ProgMailer && *user == '|')
245 			user++;
246 
247 		/*
248 		**  If an error message has already been given, don't
249 		**	bother to send to this address.
250 		**
251 		**	>>>>>>>>>> This clause assumes that the local mailer
252 		**	>> NOTE >> cannot do any further aliasing; that
253 		**	>>>>>>>>>> function is subsumed by sendmail.
254 		*/
255 
256 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
257 			continue;
258 
259 		/* save statistics.... */
260 		markstats(e, to);
261 
262 		/*
263 		**  See if this user name is "special".
264 		**	If the user name has a slash in it, assume that this
265 		**	is a file -- send it off without further ado.  Note
266 		**	that this type of addresses is not processed along
267 		**	with the others, so we fudge on the To person.
268 		*/
269 
270 		if (m == LocalMailer)
271 		{
272 			if (user[0] == '/')
273 			{
274 				rcode = mailfile(user, getctladdr(to));
275 				giveresponse(rcode, m, e);
276 				continue;
277 			}
278 		}
279 
280 		/*
281 		**  Address is verified -- add this user to mailer
282 		**  argv, and add it to the print list of recipients.
283 		*/
284 
285 		/* link together the chain of recipients */
286 		to->q_tchain = tochain;
287 		tochain = to;
288 
289 		/* create list of users for error messages */
290 		(void) strcat(tobuf, ",");
291 		(void) strcat(tobuf, to->q_paddr);
292 		define('u', user, e);		/* to user */
293 		define('z', to->q_home, e);	/* user's home */
294 
295 		/*
296 		**  Expand out this user into argument list.
297 		*/
298 
299 		if (!clever)
300 		{
301 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
302 			*pvp++ = newstr(buf);
303 			if (pvp >= &pv[MAXPV - 2])
304 			{
305 				/* allow some space for trailing parms */
306 				break;
307 			}
308 		}
309 	}
310 
311 	/* see if any addresses still exist */
312 	if (tobuf[0] == '\0')
313 	{
314 		define('g', (char *) NULL, e);
315 		return (0);
316 	}
317 
318 	/* print out messages as full list */
319 	e->e_to = tobuf + 1;
320 
321 	/*
322 	**  Fill out any parameters after the $u parameter.
323 	*/
324 
325 	while (!clever && *++mvp != NULL)
326 	{
327 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
328 		*pvp++ = newstr(buf);
329 		if (pvp >= &pv[MAXPV])
330 			syserr("deliver: pv overflow after $u for %s", pv[0]);
331 	}
332 	*pvp++ = NULL;
333 
334 	/*
335 	**  Call the mailer.
336 	**	The argument vector gets built, pipes
337 	**	are created as necessary, and we fork & exec as
338 	**	appropriate.
339 	**	If we are running SMTP, we just need to clean up.
340 	*/
341 
342 	message(Arpa_Info, "Connecting to %s.%s...", host, m->m_name);
343 
344 	if (ctladdr == NULL)
345 		ctladdr = &e->e_from;
346 # ifdef SMTP
347 	if (clever)
348 	{
349 		/* send the initial SMTP protocol */
350 		rcode = smtpinit(m, pv);
351 
352 		if (rcode == EX_OK)
353 		{
354 			/* send the recipient list */
355 			tobuf[0] = '\0';
356 			for (to = tochain; to != NULL; to = to->q_tchain)
357 			{
358 				int i;
359 
360 				e->e_to = to->q_paddr;
361 				i = smtprcpt(to, m);
362 				if (i != EX_OK)
363 				{
364 					markfailure(e, to, i);
365 					giveresponse(i, m, e);
366 				}
367 				else
368 				{
369 					strcat(tobuf, ",");
370 					strcat(tobuf, to->q_paddr);
371 				}
372 			}
373 
374 			/* now send the data */
375 			if (tobuf[0] == '\0')
376 				e->e_to = NULL;
377 			else
378 			{
379 				e->e_to = tobuf + 1;
380 				rcode = smtpdata(m, e);
381 			}
382 
383 			/* now close the connection */
384 			smtpquit(pv[0], m);
385 		}
386 	}
387 	else
388 # endif SMTP
389 		rcode = sendoff(e, m, pv, ctladdr);
390 
391 	/*
392 	**  Do final status disposal.
393 	**	We check for something in tobuf for the SMTP case.
394 	**	If we got a temporary failure, arrange to queue the
395 	**		addressees.
396 	*/
397 
398 	if (tobuf[0] != '\0')
399 		giveresponse(rcode, m, e);
400 	if (rcode != EX_OK)
401 	{
402 		for (to = tochain; to != NULL; to = to->q_tchain)
403 			markfailure(e, to, rcode);
404 	}
405 
406 	errno = 0;
407 	define('g', (char *) NULL, e);
408 	return (rcode);
409 }
410 /*
411 **  MARKFAILURE -- mark a failure on a specific address.
412 **
413 **	Parameters:
414 **		e -- the envelope we are sending.
415 **		q -- the address to mark.
416 **		rcode -- the code signifying the particular failure.
417 **
418 **	Returns:
419 **		none.
420 **
421 **	Side Effects:
422 **		marks the address (and possibly the envelope) with the
423 **			failure so that an error will be returned or
424 **			the message will be queued, as appropriate.
425 */
426 
427 markfailure(e, q, rcode)
428 	register ENVELOPE *e;
429 	register ADDRESS *q;
430 	int rcode;
431 {
432 	if (rcode == EX_OK)
433 		return;
434 	else if (rcode != EX_TEMPFAIL)
435 		q->q_flags |= QBADADDR;
436 	else if (curtime() > e->e_ctime + TimeOut)
437 	{
438 		extern char *pintvl();
439 		char buf[MAXLINE];
440 
441 		if (!bitset(EF_TIMEOUT, e->e_flags))
442 		{
443 			(void) sprintf(buf, "Cannot send message for %s",
444 				pintvl(TimeOut, FALSE));
445 			if (e->e_message != NULL)
446 				free(e->e_message);
447 			e->e_message = newstr(buf);
448 			message(Arpa_Info, buf);
449 		}
450 		q->q_flags |= QBADADDR;
451 		e->e_flags |= EF_TIMEOUT;
452 	}
453 	else
454 		q->q_flags |= QQUEUEUP;
455 }
456 /*
457 **  DOFORK -- do a fork, retrying a couple of times on failure.
458 **
459 **	This MUST be a macro, since after a vfork we are running
460 **	two processes on the same stack!!!
461 **
462 **	Parameters:
463 **		none.
464 **
465 **	Returns:
466 **		From a macro???  You've got to be kidding!
467 **
468 **	Side Effects:
469 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
470 **			pid of child in parent, zero in child.
471 **			-1 on unrecoverable error.
472 **
473 **	Notes:
474 **		I'm awfully sorry this looks so awful.  That's
475 **		vfork for you.....
476 */
477 
478 # define NFORKTRIES	5
479 # ifdef VMUNIX
480 # define XFORK	vfork
481 # else VMUNIX
482 # define XFORK	fork
483 # endif VMUNIX
484 
485 # define DOFORK(fORKfN) \
486 {\
487 	register int i;\
488 \
489 	for (i = NFORKTRIES; i-- > 0; )\
490 	{\
491 		pid = fORKfN();\
492 		if (pid >= 0)\
493 			break;\
494 		sleep(NFORKTRIES - i);\
495 	}\
496 }
497 /*
498 **  DOFORK -- simple fork interface to DOFORK.
499 **
500 **	Parameters:
501 **		none.
502 **
503 **	Returns:
504 **		pid of child in parent.
505 **		zero in child.
506 **		-1 on error.
507 **
508 **	Side Effects:
509 **		returns twice, once in parent and once in child.
510 */
511 
512 dofork()
513 {
514 	register int pid;
515 
516 	DOFORK(fork);
517 	return (pid);
518 }
519 /*
520 **  SENDOFF -- send off call to mailer & collect response.
521 **
522 **	Parameters:
523 **		e -- the envelope to mail.
524 **		m -- mailer descriptor.
525 **		pvp -- parameter vector to send to it.
526 **		ctladdr -- an address pointer controlling the
527 **			user/groupid etc. of the mailer.
528 **
529 **	Returns:
530 **		exit status of mailer.
531 **
532 **	Side Effects:
533 **		none.
534 */
535 
536 sendoff(e, m, pvp, ctladdr)
537 	register ENVELOPE *e;
538 	MAILER *m;
539 	char **pvp;
540 	ADDRESS *ctladdr;
541 {
542 	auto FILE *mfile;
543 	auto FILE *rfile;
544 	register int i;
545 	int pid;
546 
547 	/*
548 	**  Create connection to mailer.
549 	*/
550 
551 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
552 	if (pid < 0)
553 		return (-1);
554 
555 	/*
556 	**  Format and send message.
557 	*/
558 
559 	putfromline(mfile, m);
560 	(*e->e_puthdr)(mfile, m, e);
561 	putline("\n", mfile, m);
562 	(*e->e_putbody)(mfile, m, e);
563 	(void) fclose(mfile);
564 
565 	i = endmailer(pid, pvp[0]);
566 
567 	/* arrange a return receipt if requested */
568 	if (e->e_receiptto != NULL && bitset(M_LOCAL, m->m_flags))
569 	{
570 		e->e_flags |= EF_SENDRECEIPT;
571 		/* do we want to send back more info? */
572 	}
573 
574 	return (i);
575 }
576 /*
577 **  ENDMAILER -- Wait for mailer to terminate.
578 **
579 **	We should never get fatal errors (e.g., segmentation
580 **	violation), so we report those specially.  For other
581 **	errors, we choose a status message (into statmsg),
582 **	and if it represents an error, we print it.
583 **
584 **	Parameters:
585 **		pid -- pid of mailer.
586 **		name -- name of mailer (for error messages).
587 **
588 **	Returns:
589 **		exit code of mailer.
590 **
591 **	Side Effects:
592 **		none.
593 */
594 
595 endmailer(pid, name)
596 	int pid;
597 	char *name;
598 {
599 	int st;
600 
601 	/* in the IPC case there is nothing to wait for */
602 	if (pid == 0)
603 		return (EX_OK);
604 
605 	/* wait for the mailer process to die and collect status */
606 	st = waitfor(pid);
607 	if (st == -1)
608 	{
609 		syserr("endmailer %s: wait", name);
610 		return (EX_SOFTWARE);
611 	}
612 
613 	/* see if it died a horrid death */
614 	if ((st & 0377) != 0)
615 	{
616 		syserr("endmailer %s: stat %o", name, st);
617 		ExitStat = EX_UNAVAILABLE;
618 		return (EX_UNAVAILABLE);
619 	}
620 
621 	/* normal death -- return status */
622 	st = (st >> 8) & 0377;
623 	return (st);
624 }
625 /*
626 **  OPENMAILER -- open connection to mailer.
627 **
628 **	Parameters:
629 **		m -- mailer descriptor.
630 **		pvp -- parameter vector to pass to mailer.
631 **		ctladdr -- controlling address for user.
632 **		clever -- create a full duplex connection.
633 **		pmfile -- pointer to mfile (to mailer) connection.
634 **		prfile -- pointer to rfile (from mailer) connection.
635 **
636 **	Returns:
637 **		pid of mailer ( > 0 ).
638 **		-1 on error.
639 **		zero on an IPC connection.
640 **
641 **	Side Effects:
642 **		creates a mailer in a subprocess.
643 */
644 
645 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
646 	MAILER *m;
647 	char **pvp;
648 	ADDRESS *ctladdr;
649 	bool clever;
650 	FILE **pmfile;
651 	FILE **prfile;
652 {
653 	int pid;
654 	int mpvect[2];
655 	int rpvect[2];
656 	FILE *mfile;
657 	FILE *rfile;
658 	extern FILE *fdopen();
659 
660 # ifdef DEBUG
661 	if (tTd(11, 1))
662 	{
663 		printf("openmailer:");
664 		printav(pvp);
665 	}
666 # endif DEBUG
667 	errno = 0;
668 
669 	/*
670 	**  Deal with the special case of mail handled through an IPC
671 	**  connection.
672 	**	In this case we don't actually fork.  We must be
673 	**	running SMTP for this to work.  We will return a
674 	**	zero pid to indicate that we are running IPC.
675 	*/
676 
677 	if (strcmp(m->m_mailer, "[IPC]") == 0)
678 	{
679 #ifdef DAEMON
680 		register int i;
681 		register u_short port;
682 
683 		if (!clever)
684 			syserr("non-clever IPC");
685 		if (pvp[2] != NULL)
686 			port = atoi(pvp[2]);
687 		else
688 			port = 0;
689 		i = makeconnection(pvp[1], port, pmfile, prfile);
690 		if (i != EX_OK)
691 		{
692 			ExitStat = i;
693 			return (-1);
694 		}
695 		else
696 			return (0);
697 #else DAEMON
698 		syserr("openmailer: no IPC");
699 		return (-1);
700 #endif DAEMON
701 	}
702 
703 	/* create a pipe to shove the mail through */
704 	if (pipe(mpvect) < 0)
705 	{
706 		syserr("openmailer: pipe (to mailer)");
707 		return (-1);
708 	}
709 
710 #ifdef SMTP
711 	/* if this mailer speaks smtp, create a return pipe */
712 	if (clever && pipe(rpvect) < 0)
713 	{
714 		syserr("openmailer: pipe (from mailer)");
715 		(void) close(mpvect[0]);
716 		(void) close(mpvect[1]);
717 		return (-1);
718 	}
719 #endif SMTP
720 
721 	/*
722 	**  Actually fork the mailer process.
723 	**	DOFORK is clever about retrying.
724 	*/
725 
726 	if (CurEnv->e_xfp != NULL)
727 		(void) fflush(CurEnv->e_xfp);		/* for debugging */
728 	(void) fflush(stdout);
729 	DOFORK(XFORK);
730 	/* pid is set by DOFORK */
731 	if (pid < 0)
732 	{
733 		/* failure */
734 		syserr("openmailer: cannot fork");
735 		(void) close(mpvect[0]);
736 		(void) close(mpvect[1]);
737 #ifdef SMTP
738 		if (clever)
739 		{
740 			(void) close(rpvect[0]);
741 			(void) close(rpvect[1]);
742 		}
743 #endif SMTP
744 		return (-1);
745 	}
746 	else if (pid == 0)
747 	{
748 		/* child -- set up input & exec mailer */
749 		/* make diagnostic output be standard output */
750 		(void) signal(SIGINT, SIG_IGN);
751 		(void) signal(SIGHUP, SIG_IGN);
752 		(void) signal(SIGTERM, SIG_DFL);
753 
754 		/* arrange to filter standard & diag output of command */
755 		if (clever)
756 		{
757 			(void) close(rpvect[0]);
758 			(void) close(1);
759 			(void) dup(rpvect[1]);
760 			(void) close(rpvect[1]);
761 		}
762 		else if (OpMode == MD_SMTP || HoldErrs)
763 		{
764 			/* put mailer output in transcript */
765 			(void) close(1);
766 			(void) dup(fileno(CurEnv->e_xfp));
767 		}
768 		(void) close(2);
769 		(void) dup(1);
770 
771 		/* arrange to get standard input */
772 		(void) close(mpvect[1]);
773 		(void) close(0);
774 		if (dup(mpvect[0]) < 0)
775 		{
776 			syserr("Cannot dup to zero!");
777 			_exit(EX_OSERR);
778 		}
779 		(void) close(mpvect[0]);
780 		if (!bitset(M_RESTR, m->m_flags))
781 		{
782 			if (ctladdr->q_uid == 0)
783 			{
784 				(void) setgid(DefGid);
785 				(void) setuid(DefUid);
786 			}
787 			else
788 			{
789 				(void) setgid(ctladdr->q_gid);
790 				(void) setuid(ctladdr->q_uid);
791 			}
792 		}
793 
794 		/*
795 		**  We have to be careful with vfork - we can't mung up the
796 		**  memory but we don't want the mailer to inherit any extra
797 		**  open files.  Chances are the mailer won't
798 		**  care about an extra file, but then again you never know.
799 		**  Actually, we would like to close(fileno(pwf)), but it's
800 		**  declared static so we can't.  But if we fclose(pwf), which
801 		**  is what endpwent does, it closes it in the parent too and
802 		**  the next getpwnam will be slower.  If you have a weird
803 		**  mailer that chokes on the extra file you should do the
804 		**  endpwent().			-MRH
805 		**
806 		**  Similar comments apply to log.  However, openlog is
807 		**  clever enough to set the FIOCLEX mode on the file,
808 		**  so it will be closed automatically on the exec.
809 		*/
810 
811 		closeall();
812 
813 		/* try to execute the mailer */
814 		execv(m->m_mailer, pvp);
815 
816 		/* syserr fails because log is closed */
817 		/* syserr("Cannot exec %s", m->m_mailer); */
818 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
819 		(void) fflush(stdout);
820 		_exit(EX_UNAVAILABLE);
821 	}
822 
823 	/*
824 	**  Set up return value.
825 	*/
826 
827 	(void) close(mpvect[0]);
828 	mfile = fdopen(mpvect[1], "w");
829 	if (clever)
830 	{
831 		(void) close(rpvect[1]);
832 		rfile = fdopen(rpvect[0], "r");
833 	}
834 
835 	*pmfile = mfile;
836 	*prfile = rfile;
837 
838 	return (pid);
839 }
840 /*
841 **  GIVERESPONSE -- Interpret an error response from a mailer
842 **
843 **	Parameters:
844 **		stat -- the status code from the mailer (high byte
845 **			only; core dumps must have been taken care of
846 **			already).
847 **		m -- the mailer descriptor for this mailer.
848 **
849 **	Returns:
850 **		none.
851 **
852 **	Side Effects:
853 **		Errors may be incremented.
854 **		ExitStat may be set.
855 */
856 
857 /*ARGSUSED*/
858 giveresponse(stat, m, e)
859 	int stat;
860 	register MAILER *m;
861 	ENVELOPE *e;
862 {
863 	register char *statmsg;
864 	extern char *SysExMsg[];
865 	register int i;
866 	extern int N_SysEx;
867 	char buf[MAXLINE];
868 
869 	/*
870 	**  Compute status message from code.
871 	*/
872 
873 	i = stat - EX__BASE;
874 	if (stat == 0)
875 		statmsg = "250 Sent";
876 	else if (i < 0 || i > N_SysEx)
877 	{
878 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
879 		stat = EX_UNAVAILABLE;
880 		statmsg = buf;
881 	}
882 	else if (stat == EX_TEMPFAIL)
883 	{
884 		extern char *sys_errlist[];
885 		extern int sys_nerr;
886 
887 		(void) strcpy(buf, SysExMsg[i]);
888 		if (errno != 0)
889 		{
890 			(void) strcat(buf, ": ");
891 			if (errno > 0 && errno < sys_nerr)
892 				(void) strcat(buf, sys_errlist[errno]);
893 			else
894 			{
895 				char xbuf[30];
896 
897 				(void) sprintf(xbuf, "Error %d", errno);
898 				(void) strcat(buf, xbuf);
899 			}
900 		}
901 		statmsg = buf;
902 	}
903 	else
904 		statmsg = SysExMsg[i];
905 
906 	/*
907 	**  Print the message as appropriate
908 	*/
909 
910 	if (stat == EX_OK || stat == EX_TEMPFAIL)
911 		message(Arpa_Info, &statmsg[4]);
912 	else
913 	{
914 		Errors++;
915 		usrerr(statmsg);
916 	}
917 
918 	/*
919 	**  Final cleanup.
920 	**	Log a record of the transaction.  Compute the new
921 	**	ExitStat -- if we already had an error, stick with
922 	**	that.
923 	*/
924 
925 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
926 		logdelivery(&statmsg[4]);
927 
928 	if (stat != EX_TEMPFAIL)
929 		setstat(stat);
930 	if (stat != EX_OK)
931 	{
932 		if (e->e_message != NULL)
933 			free(e->e_message);
934 		e->e_message = newstr(&statmsg[4]);
935 	}
936 	errno = 0;
937 }
938 /*
939 **  LOGDELIVERY -- log the delivery in the system log
940 **
941 **	Parameters:
942 **		stat -- the message to print for the status
943 **
944 **	Returns:
945 **		none
946 **
947 **	Side Effects:
948 **		none
949 */
950 
951 logdelivery(stat)
952 	char *stat;
953 {
954 	extern char *pintvl();
955 
956 # ifdef LOG
957 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", CurEnv->e_id,
958 	       CurEnv->e_to, pintvl(curtime() - CurEnv->e_ctime, TRUE), stat);
959 # endif LOG
960 }
961 /*
962 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
963 **
964 **	This can be made an arbitrary message separator by changing $l
965 **
966 **	One of the ugliest hacks seen by human eyes is
967 **	contained herein: UUCP wants those stupid
968 **	"emote from <host>" lines.  Why oh why does a
969 **	well-meaning programmer such as myself have to
970 **	deal with this kind of antique garbage????
971 **
972 **	Parameters:
973 **		fp -- the file to output to.
974 **		m -- the mailer describing this entry.
975 **
976 **	Returns:
977 **		none
978 **
979 **	Side Effects:
980 **		outputs some text to fp.
981 */
982 
983 putfromline(fp, m)
984 	register FILE *fp;
985 	register MAILER *m;
986 {
987 	char buf[MAXLINE];
988 
989 	if (bitset(M_NHDR, m->m_flags))
990 		return;
991 
992 # ifdef UGLYUUCP
993 	if (bitset(M_UGLYUUCP, m->m_flags))
994 	{
995 		extern char *macvalue();
996 		char *sys = macvalue('g', CurEnv);
997 		char *bang = index(sys, '!');
998 
999 		if (bang == NULL)
1000 			syserr("No ! in UUCP! (%s)", sys);
1001 		else
1002 		{
1003 			*bang = '\0';
1004 			expand("From $f  $d remote from $g\n", buf,
1005 					&buf[sizeof buf - 1], CurEnv);
1006 			*bang = '!';
1007 		}
1008 	}
1009 	else
1010 # endif UGLYUUCP
1011 		expand("$l\n", buf, &buf[sizeof buf - 1], CurEnv);
1012 	putline(buf, fp, m);
1013 }
1014 /*
1015 **  PUTBODY -- put the body of a message.
1016 **
1017 **	Parameters:
1018 **		fp -- file to output onto.
1019 **		m -- a mailer descriptor to control output format.
1020 **		e -- the envelope to put out.
1021 **
1022 **	Returns:
1023 **		none.
1024 **
1025 **	Side Effects:
1026 **		The message is written onto fp.
1027 */
1028 
1029 putbody(fp, m, e)
1030 	FILE *fp;
1031 	MAILER *m;
1032 	register ENVELOPE *e;
1033 {
1034 	char buf[MAXLINE];
1035 
1036 	/*
1037 	**  Output the body of the message
1038 	*/
1039 
1040 	if (e->e_dfp == NULL)
1041 	{
1042 		if (e->e_df != NULL)
1043 		{
1044 			e->e_dfp = fopen(e->e_df, "r");
1045 			if (e->e_dfp == NULL)
1046 				syserr("Cannot open %s", e->e_df);
1047 		}
1048 		else
1049 			putline("<<< No Message Collected >>>", fp, m);
1050 	}
1051 	if (e->e_dfp != NULL)
1052 	{
1053 		rewind(e->e_dfp);
1054 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1055 			putline(buf, fp, m);
1056 
1057 		if (ferror(e->e_dfp))
1058 		{
1059 			syserr("putbody: read error");
1060 			ExitStat = EX_IOERR;
1061 		}
1062 	}
1063 
1064 	(void) fflush(fp);
1065 	if (ferror(fp) && errno != EPIPE)
1066 	{
1067 		syserr("putbody: write error");
1068 		ExitStat = EX_IOERR;
1069 	}
1070 	errno = 0;
1071 }
1072 /*
1073 **  MAILFILE -- Send a message to a file.
1074 **
1075 **	If the file has the setuid/setgid bits set, but NO execute
1076 **	bits, sendmail will try to become the owner of that file
1077 **	rather than the real user.  Obviously, this only works if
1078 **	sendmail runs as root.
1079 **
1080 **	This could be done as a subordinate mailer, except that it
1081 **	is used implicitly to save messages in ~/dead.letter.  We
1082 **	view this as being sufficiently important as to include it
1083 **	here.  For example, if the system is dying, we shouldn't have
1084 **	to create another process plus some pipes to save the message.
1085 **
1086 **	Parameters:
1087 **		filename -- the name of the file to send to.
1088 **		ctladdr -- the controlling address header -- includes
1089 **			the userid/groupid to be when sending.
1090 **
1091 **	Returns:
1092 **		The exit code associated with the operation.
1093 **
1094 **	Side Effects:
1095 **		none.
1096 */
1097 
1098 mailfile(filename, ctladdr)
1099 	char *filename;
1100 	ADDRESS *ctladdr;
1101 {
1102 	register FILE *f;
1103 	register int pid;
1104 
1105 	/*
1106 	**  Fork so we can change permissions here.
1107 	**	Note that we MUST use fork, not vfork, because of
1108 	**	the complications of calling subroutines, etc.
1109 	*/
1110 
1111 	DOFORK(fork);
1112 
1113 	if (pid < 0)
1114 		return (EX_OSERR);
1115 	else if (pid == 0)
1116 	{
1117 		/* child -- actually write to file */
1118 		struct stat stb;
1119 
1120 		(void) signal(SIGINT, SIG_DFL);
1121 		(void) signal(SIGHUP, SIG_DFL);
1122 		(void) signal(SIGTERM, SIG_DFL);
1123 		umask(OldUmask);
1124 		if (stat(filename, &stb) < 0)
1125 			stb.st_mode = 0666;
1126 		if (bitset(0111, stb.st_mode))
1127 			exit(EX_CANTCREAT);
1128 		if (ctladdr == NULL)
1129 			ctladdr = &CurEnv->e_from;
1130 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1131 		{
1132 			if (ctladdr->q_uid == 0)
1133 				(void) setgid(DefGid);
1134 			else
1135 				(void) setgid(ctladdr->q_gid);
1136 		}
1137 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1138 		{
1139 			if (ctladdr->q_uid == 0)
1140 				(void) setuid(DefUid);
1141 			else
1142 				(void) setuid(ctladdr->q_uid);
1143 		}
1144 		f = dfopen(filename, "a");
1145 		if (f == NULL)
1146 			exit(EX_CANTCREAT);
1147 
1148 		putfromline(f, ProgMailer);
1149 		(*CurEnv->e_puthdr)(f, ProgMailer, CurEnv);
1150 		putline("\n", f, ProgMailer);
1151 		(*CurEnv->e_putbody)(f, ProgMailer, CurEnv);
1152 		putline("\n", f, ProgMailer);
1153 		(void) fclose(f);
1154 		(void) fflush(stdout);
1155 
1156 		/* reset ISUID & ISGID bits for paranoid systems */
1157 		(void) chmod(filename, (int) stb.st_mode);
1158 		exit(EX_OK);
1159 		/*NOTREACHED*/
1160 	}
1161 	else
1162 	{
1163 		/* parent -- wait for exit status */
1164 		int st;
1165 
1166 		st = waitfor(pid);
1167 		if ((st & 0377) != 0)
1168 			return (EX_UNAVAILABLE);
1169 		else
1170 			return ((st >> 8) & 0377);
1171 	}
1172 }
1173 /*
1174 **  SENDALL -- actually send all the messages.
1175 **
1176 **	Parameters:
1177 **		e -- the envelope to send.
1178 **		mode -- the delivery mode to use.
1179 **
1180 **	Returns:
1181 **		none.
1182 **
1183 **	Side Effects:
1184 **		Scans the send lists and sends everything it finds.
1185 **		Delivers any appropriate error messages.
1186 **		If we are running in a non-interactive mode, takes the
1187 **			appropriate action.
1188 */
1189 
1190 sendall(e, mode)
1191 	ENVELOPE *e;
1192 	char mode;
1193 {
1194 	register ADDRESS *q;
1195 	bool oldverbose;
1196 	int pid;
1197 
1198 #ifdef DEBUG
1199 	if (tTd(13, 1))
1200 	{
1201 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1202 		printaddr(e->e_sendqueue, TRUE);
1203 	}
1204 #endif DEBUG
1205 
1206 	/*
1207 	**  Do any preprocessing necessary for the mode we are running.
1208 	**	Check to make sure the hop count is reasonable.
1209 	**	Delete sends to the sender in mailing lists.
1210 	*/
1211 
1212 	CurEnv = e;
1213 
1214 	if (e->e_hopcount > MAXHOP)
1215 	{
1216 		syserr("sendall: too many hops (%d max)", MAXHOP);
1217 		return;
1218 	}
1219 
1220 	if (!MeToo)
1221 	{
1222 		e->e_from.q_flags |= QDONTSEND;
1223 		recipient(&e->e_from, &e->e_sendqueue);
1224 	}
1225 
1226 # ifdef QUEUE
1227 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1228 	     (mode != SM_VERIFY && SuperSafe)) &&
1229 	    !bitset(EF_INQUEUE, e->e_flags))
1230 		queueup(e, TRUE, mode == SM_QUEUE);
1231 #endif QUEUE
1232 
1233 	oldverbose = Verbose;
1234 	switch (mode)
1235 	{
1236 	  case SM_VERIFY:
1237 		Verbose = TRUE;
1238 		break;
1239 
1240 	  case SM_QUEUE:
1241 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1242 		return;
1243 
1244 	  case SM_FORK:
1245 		if (e->e_xfp != NULL)
1246 			(void) fflush(e->e_xfp);
1247 		pid = fork();
1248 		if (pid < 0)
1249 		{
1250 			mode = SM_DELIVER;
1251 			break;
1252 		}
1253 		else if (pid > 0)
1254 		{
1255 			/* be sure we leave the temp files to our child */
1256 			e->e_id = e->e_df = NULL;
1257 			return;
1258 		}
1259 
1260 		/* double fork to avoid zombies */
1261 		if (fork() > 0)
1262 			exit(EX_OK);
1263 
1264 		/* be sure we are immune from the terminal */
1265 		disconnect(FALSE);
1266 
1267 		break;
1268 	}
1269 
1270 	/*
1271 	**  Run through the list and send everything.
1272 	*/
1273 
1274 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1275 	{
1276 		if (mode == SM_VERIFY)
1277 		{
1278 			e->e_to = q->q_paddr;
1279 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1280 				message(Arpa_Info, "deliverable");
1281 		}
1282 		else
1283 			(void) deliver(e, q);
1284 	}
1285 	Verbose = oldverbose;
1286 
1287 	/*
1288 	**  Now run through and check for errors.
1289 	*/
1290 
1291 	if (mode == SM_VERIFY)
1292 		return;
1293 
1294 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1295 	{
1296 		register ADDRESS *qq;
1297 
1298 # ifdef DEBUG
1299 		if (tTd(13, 3))
1300 		{
1301 			printf("Checking ");
1302 			printaddr(q, FALSE);
1303 		}
1304 # endif DEBUG
1305 
1306 		/* only send errors if the message failed */
1307 		if (!bitset(QBADADDR, q->q_flags))
1308 			continue;
1309 
1310 		/* we have an address that failed -- find the parent */
1311 		for (qq = q; qq != NULL; qq = qq->q_alias)
1312 		{
1313 			char obuf[MAXNAME + 6];
1314 			extern char *aliaslookup();
1315 
1316 			/* we can only have owners for local addresses */
1317 			if (!bitset(M_LOCAL, qq->q_mailer->m_flags))
1318 				continue;
1319 
1320 			/* see if the owner list exists */
1321 			(void) strcpy(obuf, "owner-");
1322 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1323 				(void) strcat(obuf, "owner");
1324 			else
1325 				(void) strcat(obuf, qq->q_user);
1326 			if (aliaslookup(obuf) == NULL)
1327 				continue;
1328 
1329 # ifdef DEBUG
1330 			if (tTd(13, 4))
1331 				printf("Errors to %s\n", obuf);
1332 # endif DEBUG
1333 
1334 			/* owner list exists -- add it to the error queue */
1335 			sendtolist(obuf, (ADDRESS *) NULL, &e->e_errorqueue);
1336 			ErrorMode == EM_MAIL;
1337 			break;
1338 		}
1339 
1340 		/* if we did not find an owner, send to the sender */
1341 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1342 			sendtolist(e->e_from.q_paddr, qq, &e->e_errorqueue);
1343 	}
1344 
1345 	if (mode == SM_FORK)
1346 		finis();
1347 }
1348