1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)deliver.c	8.31 (Berkeley) 10/15/93";
11 #endif /* not lint */
12 
13 #include "sendmail.h"
14 #include <netdb.h>
15 #include <errno.h>
16 #ifdef NAMED_BIND
17 #include <arpa/nameser.h>
18 #include <resolv.h>
19 
20 extern int	h_errno;
21 #endif
22 
23 /*
24 **  SENDALL -- actually send all the messages.
25 **
26 **	Parameters:
27 **		e -- the envelope to send.
28 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
29 **			the current e->e_sendmode.
30 **
31 **	Returns:
32 **		none.
33 **
34 **	Side Effects:
35 **		Scans the send lists and sends everything it finds.
36 **		Delivers any appropriate error messages.
37 **		If we are running in a non-interactive mode, takes the
38 **			appropriate action.
39 */
40 
41 sendall(e, mode)
42 	ENVELOPE *e;
43 	char mode;
44 {
45 	register ADDRESS *q;
46 	char *owner;
47 	int otherowners;
48 	register ENVELOPE *ee;
49 	ENVELOPE *splitenv = NULL;
50 	bool announcequeueup;
51 
52 	/*
53 	**  If we have had global, fatal errors, don't bother sending
54 	**  the message at all if we are in SMTP mode.  Local errors
55 	**  (e.g., a single address failing) will still cause the other
56 	**  addresses to be sent.
57 	*/
58 
59 	if (bitset(EF_FATALERRS, e->e_flags) && OpMode == MD_SMTP)
60 	{
61 		e->e_flags |= EF_CLRQUEUE;
62 		return;
63 	}
64 
65 	/* determine actual delivery mode */
66 	if (mode == SM_DEFAULT)
67 	{
68 		mode = e->e_sendmode;
69 		if (mode != SM_VERIFY &&
70 		    shouldqueue(e->e_msgpriority, e->e_ctime))
71 			mode = SM_QUEUE;
72 		announcequeueup = mode == SM_QUEUE;
73 	}
74 	else
75 		announcequeueup = FALSE;
76 
77 	if (tTd(13, 1))
78 	{
79 		printf("\n===== SENDALL: mode %c, id %s, e_from ",
80 			mode, e->e_id);
81 		printaddr(&e->e_from, FALSE);
82 		printf("sendqueue:\n");
83 		printaddr(e->e_sendqueue, TRUE);
84 	}
85 
86 	/*
87 	**  Do any preprocessing necessary for the mode we are running.
88 	**	Check to make sure the hop count is reasonable.
89 	**	Delete sends to the sender in mailing lists.
90 	*/
91 
92 	CurEnv = e;
93 
94 	if (e->e_hopcount > MaxHopCount)
95 	{
96 		errno = 0;
97 		syserr("554 too many hops %d (%d max): from %s via %s, to %s",
98 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
99 			RealHostName, e->e_sendqueue->q_paddr);
100 		return;
101 	}
102 
103 	/*
104 	**  Do sender deletion.
105 	**
106 	**	If the sender has the QQUEUEUP flag set, skip this.
107 	**	This can happen if the name server is hosed when you
108 	**	are trying to send mail.  The result is that the sender
109 	**	is instantiated in the queue as a recipient.
110 	*/
111 
112 	if (!bitset(EF_METOO, e->e_flags) &&
113 	    !bitset(QQUEUEUP, e->e_from.q_flags))
114 	{
115 		if (tTd(13, 5))
116 		{
117 			printf("sendall: QDONTSEND ");
118 			printaddr(&e->e_from, FALSE);
119 		}
120 		e->e_from.q_flags |= QDONTSEND;
121 		(void) recipient(&e->e_from, &e->e_sendqueue, e);
122 	}
123 
124 	/*
125 	**  Handle alias owners.
126 	**
127 	**	We scan up the q_alias chain looking for owners.
128 	**	We discard owners that are the same as the return path.
129 	*/
130 
131 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
132 	{
133 		register struct address *a;
134 
135 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
136 			continue;
137 		if (a != NULL)
138 			q->q_owner = a->q_owner;
139 
140 		if (q->q_owner != NULL &&
141 		    !bitset(QDONTSEND, q->q_flags) &&
142 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
143 			q->q_owner = NULL;
144 	}
145 
146 	owner = "";
147 	otherowners = 1;
148 	while (owner != NULL && otherowners > 0)
149 	{
150 		owner = NULL;
151 		otherowners = 0;
152 
153 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
154 		{
155 			if (bitset(QDONTSEND, q->q_flags))
156 				continue;
157 
158 			if (q->q_owner != NULL)
159 			{
160 				if (owner == NULL)
161 					owner = q->q_owner;
162 				else if (owner != q->q_owner)
163 				{
164 					if (strcmp(owner, q->q_owner) == 0)
165 					{
166 						/* make future comparisons cheap */
167 						q->q_owner = owner;
168 					}
169 					else
170 					{
171 						otherowners++;
172 					}
173 					owner = q->q_owner;
174 				}
175 			}
176 			else
177 			{
178 				otherowners++;
179 			}
180 		}
181 
182 		if (owner != NULL && otherowners > 0)
183 		{
184 			extern HDR *copyheader();
185 			extern ADDRESS *copyqueue();
186 
187 			/*
188 			**  Split this envelope into two.
189 			*/
190 
191 			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
192 			*ee = *e;
193 			ee->e_id = NULL;
194 			(void) queuename(ee, '\0');
195 
196 			if (tTd(13, 1))
197 				printf("sendall: split %s into %s\n",
198 					e->e_id, ee->e_id);
199 
200 			ee->e_header = copyheader(e->e_header);
201 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
202 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
203 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS);
204 			setsender(owner, ee, NULL, TRUE);
205 			if (tTd(13, 5))
206 			{
207 				printf("sendall(split): QDONTSEND ");
208 				printaddr(&ee->e_from, FALSE);
209 			}
210 			ee->e_from.q_flags |= QDONTSEND;
211 			ee->e_dfp = NULL;
212 			ee->e_xfp = NULL;
213 			ee->e_lockfp = NULL;
214 			ee->e_df = NULL;
215 			ee->e_errormode = EM_MAIL;
216 			ee->e_sibling = splitenv;
217 			splitenv = ee;
218 
219 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
220 				if (q->q_owner == owner)
221 					q->q_flags |= QDONTSEND;
222 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
223 				if (q->q_owner != owner)
224 					q->q_flags |= QDONTSEND;
225 
226 			if (e->e_df != NULL && mode != SM_VERIFY)
227 			{
228 				ee->e_dfp = NULL;
229 				ee->e_df = queuename(ee, 'd');
230 				ee->e_df = newstr(ee->e_df);
231 				if (link(e->e_df, ee->e_df) < 0)
232 				{
233 					syserr("sendall: link(%s, %s)",
234 						e->e_df, ee->e_df);
235 				}
236 			}
237 
238 			if (mode != SM_VERIFY)
239 				openxscript(ee);
240 #ifdef LOG
241 			if (LogLevel > 4)
242 				syslog(LOG_INFO, "%s: clone %s",
243 					ee->e_id, e->e_id);
244 #endif
245 		}
246 	}
247 
248 	if (owner != NULL)
249 	{
250 		setsender(owner, e, NULL, TRUE);
251 		if (tTd(13, 5))
252 		{
253 			printf("sendall(owner): QDONTSEND ");
254 			printaddr(&e->e_from, FALSE);
255 		}
256 		e->e_from.q_flags |= QDONTSEND;
257 		e->e_errormode = EM_MAIL;
258 	}
259 
260 # ifdef QUEUE
261 	if ((mode == SM_QUEUE || mode == SM_FORK ||
262 	     (mode != SM_VERIFY && SuperSafe)) &&
263 	    !bitset(EF_INQUEUE, e->e_flags))
264 	{
265 		/* be sure everything is instantiated in the queue */
266 		queueup(e, TRUE, announcequeueup);
267 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
268 			queueup(ee, TRUE, announcequeueup);
269 	}
270 #endif /* QUEUE */
271 
272 	if (splitenv != NULL)
273 	{
274 		if (tTd(13, 1))
275 		{
276 			printf("\nsendall: Split queue; remaining queue:\n");
277 			printaddr(e->e_sendqueue, TRUE);
278 		}
279 
280 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
281 		{
282 			CurEnv = ee;
283 			sendenvelope(ee, mode);
284 		}
285 
286 		CurEnv = e;
287 	}
288 	sendenvelope(e, mode);
289 
290 	for (; splitenv != NULL; splitenv = splitenv->e_sibling)
291 		dropenvelope(splitenv);
292 }
293 
294 sendenvelope(e, mode)
295 	register ENVELOPE *e;
296 	char mode;
297 {
298 	bool oldverbose;
299 	int pid;
300 	register ADDRESS *q;
301 	char *qf;
302 	char *id;
303 
304 	/*
305 	**  If we have had global, fatal errors, don't bother sending
306 	**  the message at all if we are in SMTP mode.  Local errors
307 	**  (e.g., a single address failing) will still cause the other
308 	**  addresses to be sent.
309 	*/
310 
311 	if (bitset(EF_FATALERRS, e->e_flags) && OpMode == MD_SMTP)
312 	{
313 		e->e_flags |= EF_CLRQUEUE;
314 		return;
315 	}
316 
317 	oldverbose = Verbose;
318 	switch (mode)
319 	{
320 	  case SM_VERIFY:
321 		Verbose = TRUE;
322 		break;
323 
324 	  case SM_QUEUE:
325   queueonly:
326 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
327 		return;
328 
329 	  case SM_FORK:
330 		if (e->e_xfp != NULL)
331 			(void) fflush(e->e_xfp);
332 
333 # ifndef HASFLOCK
334 		/*
335 		**  Since fcntl locking has the interesting semantic that
336 		**  the lock is owned by a process, not by an open file
337 		**  descriptor, we have to flush this to the queue, and
338 		**  then restart from scratch in the child.
339 		*/
340 
341 		/* save id for future use */
342 		id = e->e_id;
343 
344 		/* now drop the envelope in the parent */
345 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
346 		e->e_flags &= ~EF_FATALERRS;
347 		dropenvelope(e);
348 
349 		/* and reacquire in the child */
350 		(void) dowork(id, TRUE, FALSE, e);
351 
352 		return;
353 
354 # else /* HASFLOCK */
355 
356 		pid = fork();
357 		if (pid < 0)
358 		{
359 			goto queueonly;
360 		}
361 		else if (pid > 0)
362 		{
363 			/* be sure we leave the temp files to our child */
364 			/* can't call unlockqueue to avoid unlink of xfp */
365 			if (e->e_lockfp != NULL)
366 				(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
367 			e->e_lockfp = NULL;
368 
369 			/* close any random open files in the envelope */
370 			closexscript(e);
371 			if (e->e_dfp != NULL)
372 				(void) xfclose(e->e_dfp, "sendenvelope", e->e_df);
373 			e->e_dfp = NULL;
374 			e->e_id = e->e_df = NULL;
375 			return;
376 		}
377 
378 		/* double fork to avoid zombies */
379 		if (fork() > 0)
380 			exit(EX_OK);
381 
382 		/* be sure we are immune from the terminal */
383 		disconnect(1, e);
384 
385 		/*
386 		**  Close any cached connections.
387 		**
388 		**	We don't send the QUIT protocol because the parent
389 		**	still knows about the connection.
390 		**
391 		**	This should only happen when delivering an error
392 		**	message.
393 		*/
394 
395 		mci_flush(FALSE, NULL);
396 
397 # endif /* HASFLOCK */
398 
399 		break;
400 	}
401 
402 	/*
403 	**  Run through the list and send everything.
404 	**
405 	**	Set EF_GLOBALERRS so that error messages during delivery
406 	**	result in returned mail.
407 	*/
408 
409 	e->e_nsent = 0;
410 	e->e_flags |= EF_GLOBALERRS;
411 
412 	/* now run through the queue */
413 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
414 	{
415 #ifdef XDEBUG
416 		char wbuf[MAXNAME + 20];
417 
418 		(void) sprintf(wbuf, "sendall(%s)", q->q_paddr);
419 		checkfd012(wbuf);
420 #endif
421 		if (mode == SM_VERIFY)
422 		{
423 			e->e_to = q->q_paddr;
424 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
425 			{
426 				message("deliverable: mailer %s, host %s, user %s",
427 					q->q_mailer->m_name,
428 					q->q_host,
429 					q->q_user);
430 			}
431 		}
432 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
433 		{
434 # ifdef QUEUE
435 			/*
436 			**  Checkpoint the send list every few addresses
437 			*/
438 
439 			if (e->e_nsent >= CheckpointInterval)
440 			{
441 				queueup(e, TRUE, FALSE);
442 				e->e_nsent = 0;
443 			}
444 # endif /* QUEUE */
445 			(void) deliver(e, q);
446 		}
447 	}
448 	Verbose = oldverbose;
449 
450 #ifdef XDEBUG
451 	checkfd012("end of sendenvelope");
452 #endif
453 
454 	if (mode == SM_FORK)
455 		finis();
456 }
457 /*
458 **  DOFORK -- do a fork, retrying a couple of times on failure.
459 **
460 **	This MUST be a macro, since after a vfork we are running
461 **	two processes on the same stack!!!
462 **
463 **	Parameters:
464 **		none.
465 **
466 **	Returns:
467 **		From a macro???  You've got to be kidding!
468 **
469 **	Side Effects:
470 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
471 **			pid of child in parent, zero in child.
472 **			-1 on unrecoverable error.
473 **
474 **	Notes:
475 **		I'm awfully sorry this looks so awful.  That's
476 **		vfork for you.....
477 */
478 
479 # define NFORKTRIES	5
480 
481 # ifndef FORK
482 # define FORK	fork
483 # endif
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 		if (i > 0)\
495 			sleep((unsigned) NFORKTRIES - i);\
496 	}\
497 }
498 /*
499 **  DOFORK -- simple fork interface to DOFORK.
500 **
501 **	Parameters:
502 **		none.
503 **
504 **	Returns:
505 **		pid of child in parent.
506 **		zero in child.
507 **		-1 on error.
508 **
509 **	Side Effects:
510 **		returns twice, once in parent and once in child.
511 */
512 
513 dofork()
514 {
515 	register int pid;
516 
517 	DOFORK(fork);
518 	return (pid);
519 }
520 /*
521 **  DELIVER -- Deliver a message to a list of addresses.
522 **
523 **	This routine delivers to everyone on the same host as the
524 **	user on the head of the list.  It is clever about mailers
525 **	that don't handle multiple users.  It is NOT guaranteed
526 **	that it will deliver to all these addresses however -- so
527 **	deliver should be called once for each address on the
528 **	list.
529 **
530 **	Parameters:
531 **		e -- the envelope to deliver.
532 **		firstto -- head of the address list to deliver to.
533 **
534 **	Returns:
535 **		zero -- successfully delivered.
536 **		else -- some failure, see ExitStat for more info.
537 **
538 **	Side Effects:
539 **		The standard input is passed off to someone.
540 */
541 
542 deliver(e, firstto)
543 	register ENVELOPE *e;
544 	ADDRESS *firstto;
545 {
546 	char *host;			/* host being sent to */
547 	char *user;			/* user being sent to */
548 	char **pvp;
549 	register char **mvp;
550 	register char *p;
551 	register MAILER *m;		/* mailer for this recipient */
552 	ADDRESS *ctladdr;
553 	register MCI *mci;
554 	register ADDRESS *to = firstto;
555 	bool clever = FALSE;		/* running user smtp to this mailer */
556 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
557 	int rcode;			/* response code */
558 	char *firstsig;			/* signature of firstto */
559 	int pid;
560 	char *curhost;
561 	int mpvect[2];
562 	int rpvect[2];
563 	char *pv[MAXPV+1];
564 	char tobuf[TOBUFSIZE];		/* text line of to people */
565 	char buf[MAXNAME];
566 	char rpathbuf[MAXNAME];		/* translated return path */
567 	extern int checkcompat();
568 	extern FILE *fdopen();
569 	extern char SmtpError[];
570 
571 	errno = 0;
572 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
573 		return (0);
574 
575 #ifdef NAMED_BIND
576 	/* unless interactive, try twice, over a minute */
577 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP) {
578 		_res.retrans = 30;
579 		_res.retry = 2;
580 	}
581 #endif
582 
583 	m = to->q_mailer;
584 	host = to->q_host;
585 	CurEnv = e;			/* just in case */
586 	e->e_statmsg = NULL;
587 	SmtpError[0] = '\0';
588 
589 	if (tTd(10, 1))
590 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
591 			m->m_mno, host, to->q_user);
592 
593 	/*
594 	**  If this mailer is expensive, and if we don't want to make
595 	**  connections now, just mark these addresses and return.
596 	**	This is useful if we want to batch connections to
597 	**	reduce load.  This will cause the messages to be
598 	**	queued up, and a daemon will come along to send the
599 	**	messages later.
600 	**		This should be on a per-mailer basis.
601 	*/
602 
603 	if (NoConnect && bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
604 	{
605 		for (; to != NULL; to = to->q_next)
606 		{
607 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
608 			    to->q_mailer != m)
609 				continue;
610 			to->q_flags |= QQUEUEUP;
611 			e->e_to = to->q_paddr;
612 			message("queued");
613 			if (LogLevel > 8)
614 				logdelivery(m, NULL, "queued", e);
615 		}
616 		e->e_to = NULL;
617 		return (0);
618 	}
619 
620 	/*
621 	**  Do initial argv setup.
622 	**	Insert the mailer name.  Notice that $x expansion is
623 	**	NOT done on the mailer name.  Then, if the mailer has
624 	**	a picky -f flag, we insert it as appropriate.  This
625 	**	code does not check for 'pv' overflow; this places a
626 	**	manifest lower limit of 4 for MAXPV.
627 	**		The from address rewrite is expected to make
628 	**		the address relative to the other end.
629 	*/
630 
631 	/* rewrite from address, using rewriting rules */
632 	rcode = EX_OK;
633 	(void) strcpy(rpathbuf, remotename(e->e_from.q_paddr, m,
634 					   RF_SENDERADDR|RF_CANONICAL,
635 					   &rcode, e));
636 	define('g', rpathbuf, e);		/* translated return path */
637 	define('h', host, e);			/* to host */
638 	Errors = 0;
639 	pvp = pv;
640 	*pvp++ = m->m_argv[0];
641 
642 	/* insert -f or -r flag as appropriate */
643 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
644 	{
645 		if (bitnset(M_FOPT, m->m_flags))
646 			*pvp++ = "-f";
647 		else
648 			*pvp++ = "-r";
649 		*pvp++ = newstr(rpathbuf);
650 	}
651 
652 	/*
653 	**  Append the other fixed parts of the argv.  These run
654 	**  up to the first entry containing "$u".  There can only
655 	**  be one of these, and there are only a few more slots
656 	**  in the pv after it.
657 	*/
658 
659 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
660 	{
661 		/* can't use strchr here because of sign extension problems */
662 		while (*p != '\0')
663 		{
664 			if ((*p++ & 0377) == MACROEXPAND)
665 			{
666 				if (*p == 'u')
667 					break;
668 			}
669 		}
670 
671 		if (*p != '\0')
672 			break;
673 
674 		/* this entry is safe -- go ahead and process it */
675 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
676 		*pvp++ = newstr(buf);
677 		if (pvp >= &pv[MAXPV - 3])
678 		{
679 			syserr("554 Too many parameters to %s before $u", pv[0]);
680 			return (-1);
681 		}
682 	}
683 
684 	/*
685 	**  If we have no substitution for the user name in the argument
686 	**  list, we know that we must supply the names otherwise -- and
687 	**  SMTP is the answer!!
688 	*/
689 
690 	if (*mvp == NULL)
691 	{
692 		/* running SMTP */
693 # ifdef SMTP
694 		clever = TRUE;
695 		*pvp = NULL;
696 # else /* SMTP */
697 		/* oops!  we don't implement SMTP */
698 		syserr("554 SMTP style mailer not implemented");
699 		return (EX_SOFTWARE);
700 # endif /* SMTP */
701 	}
702 
703 	/*
704 	**  At this point *mvp points to the argument with $u.  We
705 	**  run through our address list and append all the addresses
706 	**  we can.  If we run out of space, do not fret!  We can
707 	**  always send another copy later.
708 	*/
709 
710 	tobuf[0] = '\0';
711 	e->e_to = tobuf;
712 	ctladdr = NULL;
713 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
714 	for (; to != NULL; to = to->q_next)
715 	{
716 		/* avoid sending multiple recipients to dumb mailers */
717 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
718 			break;
719 
720 		/* if already sent or not for this host, don't send */
721 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
722 		    to->q_mailer != firstto->q_mailer ||
723 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
724 			continue;
725 
726 		/* avoid overflowing tobuf */
727 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
728 			break;
729 
730 		if (tTd(10, 1))
731 		{
732 			printf("\nsend to ");
733 			printaddr(to, FALSE);
734 		}
735 
736 		/* compute effective uid/gid when sending */
737 		if (to->q_mailer == ProgMailer)
738 			ctladdr = getctladdr(to);
739 
740 		user = to->q_user;
741 		e->e_to = to->q_paddr;
742 		if (tTd(10, 5))
743 		{
744 			printf("deliver: QDONTSEND ");
745 			printaddr(to, FALSE);
746 		}
747 		to->q_flags |= QDONTSEND;
748 
749 		/*
750 		**  Check to see that these people are allowed to
751 		**  talk to each other.
752 		*/
753 
754 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
755 		{
756 			NoReturn = TRUE;
757 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
758 			giveresponse(EX_UNAVAILABLE, m, NULL, e);
759 			continue;
760 		}
761 		rcode = checkcompat(to, e);
762 		if (rcode != EX_OK)
763 		{
764 			markfailure(e, to, rcode);
765 			giveresponse(rcode, m, NULL, e);
766 			continue;
767 		}
768 
769 		/*
770 		**  Strip quote bits from names if the mailer is dumb
771 		**	about them.
772 		*/
773 
774 		if (bitnset(M_STRIPQ, m->m_flags))
775 		{
776 			stripquotes(user);
777 			stripquotes(host);
778 		}
779 
780 		/* hack attack -- delivermail compatibility */
781 		if (m == ProgMailer && *user == '|')
782 			user++;
783 
784 		/*
785 		**  If an error message has already been given, don't
786 		**	bother to send to this address.
787 		**
788 		**	>>>>>>>>>> This clause assumes that the local mailer
789 		**	>> NOTE >> cannot do any further aliasing; that
790 		**	>>>>>>>>>> function is subsumed by sendmail.
791 		*/
792 
793 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
794 			continue;
795 
796 		/* save statistics.... */
797 		markstats(e, to);
798 
799 		/*
800 		**  See if this user name is "special".
801 		**	If the user name has a slash in it, assume that this
802 		**	is a file -- send it off without further ado.  Note
803 		**	that this type of addresses is not processed along
804 		**	with the others, so we fudge on the To person.
805 		*/
806 
807 		if (m == FileMailer)
808 		{
809 			rcode = mailfile(user, getctladdr(to), e);
810 			giveresponse(rcode, m, NULL, e);
811 			if (rcode == EX_OK)
812 				to->q_flags |= QSENT;
813 			continue;
814 		}
815 
816 		/*
817 		**  Address is verified -- add this user to mailer
818 		**  argv, and add it to the print list of recipients.
819 		*/
820 
821 		/* link together the chain of recipients */
822 		to->q_tchain = tochain;
823 		tochain = to;
824 
825 		/* create list of users for error messages */
826 		(void) strcat(tobuf, ",");
827 		(void) strcat(tobuf, to->q_paddr);
828 		define('u', user, e);		/* to user */
829 		p = to->q_home;
830 		if (p == NULL && ctladdr != NULL)
831 			p = ctladdr->q_home;
832 		define('z', p, e);	/* user's home */
833 
834 		/*
835 		**  Expand out this user into argument list.
836 		*/
837 
838 		if (!clever)
839 		{
840 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
841 			*pvp++ = newstr(buf);
842 			if (pvp >= &pv[MAXPV - 2])
843 			{
844 				/* allow some space for trailing parms */
845 				break;
846 			}
847 		}
848 	}
849 
850 	/* see if any addresses still exist */
851 	if (tobuf[0] == '\0')
852 	{
853 		define('g', (char *) NULL, e);
854 		return (0);
855 	}
856 
857 	/* print out messages as full list */
858 	e->e_to = tobuf + 1;
859 
860 	/*
861 	**  Fill out any parameters after the $u parameter.
862 	*/
863 
864 	while (!clever && *++mvp != NULL)
865 	{
866 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
867 		*pvp++ = newstr(buf);
868 		if (pvp >= &pv[MAXPV])
869 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
870 	}
871 	*pvp++ = NULL;
872 
873 	/*
874 	**  Call the mailer.
875 	**	The argument vector gets built, pipes
876 	**	are created as necessary, and we fork & exec as
877 	**	appropriate.
878 	**	If we are running SMTP, we just need to clean up.
879 	*/
880 
881 	if (ctladdr == NULL && m != ProgMailer)
882 		ctladdr = &e->e_from;
883 #ifdef NAMED_BIND
884 	if (ConfigLevel < 2)
885 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
886 #endif
887 
888 	if (tTd(11, 1))
889 	{
890 		printf("openmailer:");
891 		printav(pv);
892 	}
893 	errno = 0;
894 
895 	CurHostName = m->m_mailer;
896 
897 	/*
898 	**  Deal with the special case of mail handled through an IPC
899 	**  connection.
900 	**	In this case we don't actually fork.  We must be
901 	**	running SMTP for this to work.  We will return a
902 	**	zero pid to indicate that we are running IPC.
903 	**  We also handle a debug version that just talks to stdin/out.
904 	*/
905 
906 	curhost = NULL;
907 	SmtpPhase = NULL;
908 	mci = NULL;
909 
910 #ifdef XDEBUG
911 	{
912 		char wbuf[MAXLINE];
913 
914 		/* make absolutely certain 0, 1, and 2 are in use */
915 		sprintf(wbuf, "%s... openmailer(%s)", e->e_to, m->m_name);
916 		checkfd012(wbuf);
917 	}
918 #endif
919 
920 	/* check for Local Person Communication -- not for mortals!!! */
921 	if (strcmp(m->m_mailer, "[LPC]") == 0)
922 	{
923 		mci = (MCI *) xalloc(sizeof *mci);
924 		bzero((char *) mci, sizeof *mci);
925 		mci->mci_in = stdin;
926 		mci->mci_out = stdout;
927 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
928 		mci->mci_mailer = m;
929 	}
930 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
931 		 strcmp(m->m_mailer, "[TCP]") == 0)
932 	{
933 #ifdef DAEMON
934 		register int i;
935 		register u_short port;
936 
937 		CurHostName = pv[1];
938 		curhost = hostsignature(m, pv[1], e);
939 
940 		if (curhost == NULL || curhost[0] == '\0')
941 		{
942 			syserr("null signature");
943 			rcode = EX_OSERR;
944 			goto give_up;
945 		}
946 
947 		if (!clever)
948 		{
949 			syserr("554 non-clever IPC");
950 			rcode = EX_CONFIG;
951 			goto give_up;
952 		}
953 		if (pv[2] != NULL)
954 			port = atoi(pv[2]);
955 		else
956 			port = 0;
957 tryhost:
958 		while (*curhost != '\0')
959 		{
960 			register char *p;
961 			static char hostbuf[MAXNAME];
962 
963 			/* pull the next host from the signature */
964 			p = strchr(curhost, ':');
965 			if (p == NULL)
966 				p = &curhost[strlen(curhost)];
967 			if (p == curhost)
968 			{
969 				syserr("deliver: null host name in signature");
970 				continue;
971 			}
972 			strncpy(hostbuf, curhost, p - curhost);
973 			hostbuf[p - curhost] = '\0';
974 			if (*p != '\0')
975 				p++;
976 			curhost = p;
977 
978 			/* see if we already know that this host is fried */
979 			CurHostName = hostbuf;
980 			mci = mci_get(hostbuf, m);
981 			if (mci->mci_state != MCIS_CLOSED)
982 			{
983 				if (tTd(11, 1))
984 				{
985 					printf("openmailer: ");
986 					mci_dump(mci);
987 				}
988 				CurHostName = mci->mci_host;
989 				break;
990 			}
991 			mci->mci_mailer = m;
992 			if (mci->mci_exitstat != EX_OK)
993 				continue;
994 
995 			/* try the connection */
996 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
997 			message("Connecting to %s (%s)...",
998 				hostbuf, m->m_name);
999 			i = makeconnection(hostbuf, port, mci,
1000 				bitnset(M_SECURE_PORT, m->m_flags));
1001 			mci->mci_exitstat = i;
1002 			mci->mci_errno = errno;
1003 #ifdef NAMED_BIND
1004 			mci->mci_herrno = h_errno;
1005 #endif
1006 			if (i == EX_OK)
1007 			{
1008 				mci->mci_state = MCIS_OPENING;
1009 				mci_cache(mci);
1010 				if (TrafficLogFile != NULL)
1011 					fprintf(TrafficLogFile, "%05d == CONNECT %s\n",
1012 						getpid(), hostbuf);
1013 				break;
1014 			}
1015 			else if (tTd(11, 1))
1016 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1017 					i, errno);
1018 
1019 			/* enter status of this host */
1020 			setstat(i);
1021 
1022 			/* should print some message here for -v mode */
1023 		}
1024 		if (mci == NULL)
1025 		{
1026 			syserr("deliver: no host name");
1027 			rcode = EX_OSERR;
1028 			goto give_up;
1029 		}
1030 		mci->mci_pid = 0;
1031 #else /* no DAEMON */
1032 		syserr("554 openmailer: no IPC");
1033 		if (tTd(11, 1))
1034 			printf("openmailer: NULL\n");
1035 		rcode = EX_UNAVAILABLE;
1036 		goto give_up;
1037 #endif /* DAEMON */
1038 	}
1039 	else
1040 	{
1041 		if (TrafficLogFile != NULL)
1042 		{
1043 			char **av;
1044 
1045 			fprintf(TrafficLogFile, "%05d === EXEC", getpid());
1046 			for (av = pv; *av != NULL; av++)
1047 				fprintf(TrafficLogFile, " %s", *av);
1048 			fprintf(TrafficLogFile, "\n");
1049 		}
1050 
1051 		/* create a pipe to shove the mail through */
1052 		if (pipe(mpvect) < 0)
1053 		{
1054 			syserr("%s... openmailer(%s): pipe (to mailer)",
1055 				e->e_to, m->m_name);
1056 			if (tTd(11, 1))
1057 				printf("openmailer: NULL\n");
1058 			rcode = EX_OSERR;
1059 			goto give_up;
1060 		}
1061 
1062 		/* if this mailer speaks smtp, create a return pipe */
1063 		if (clever && pipe(rpvect) < 0)
1064 		{
1065 			syserr("%s... openmailer(%s): pipe (from mailer)",
1066 				e->e_to, m->m_name);
1067 			(void) close(mpvect[0]);
1068 			(void) close(mpvect[1]);
1069 			if (tTd(11, 1))
1070 				printf("openmailer: NULL\n");
1071 			rcode = EX_OSERR;
1072 			goto give_up;
1073 		}
1074 
1075 		/*
1076 		**  Actually fork the mailer process.
1077 		**	DOFORK is clever about retrying.
1078 		**
1079 		**	Dispose of SIGCHLD signal catchers that may be laying
1080 		**	around so that endmail will get it.
1081 		*/
1082 
1083 		if (e->e_xfp != NULL)
1084 			(void) fflush(e->e_xfp);		/* for debugging */
1085 		(void) fflush(stdout);
1086 # ifdef SIGCHLD
1087 		(void) setsignal(SIGCHLD, SIG_DFL);
1088 # endif /* SIGCHLD */
1089 		DOFORK(FORK);
1090 		/* pid is set by DOFORK */
1091 		if (pid < 0)
1092 		{
1093 			/* failure */
1094 			syserr("%s... openmailer(%s): cannot fork",
1095 				e->e_to, m->m_name);
1096 			(void) close(mpvect[0]);
1097 			(void) close(mpvect[1]);
1098 			if (clever)
1099 			{
1100 				(void) close(rpvect[0]);
1101 				(void) close(rpvect[1]);
1102 			}
1103 			if (tTd(11, 1))
1104 				printf("openmailer: NULL\n");
1105 			rcode = EX_OSERR;
1106 			goto give_up;
1107 		}
1108 		else if (pid == 0)
1109 		{
1110 			int i;
1111 			int saveerrno;
1112 			char **ep;
1113 			char *env[MAXUSERENVIRON];
1114 			extern char **environ;
1115 			extern int DtableSize;
1116 
1117 			/* child -- set up input & exec mailer */
1118 			(void) setsignal(SIGINT, SIG_IGN);
1119 			(void) setsignal(SIGHUP, SIG_IGN);
1120 			(void) setsignal(SIGTERM, SIG_DFL);
1121 
1122 			/* close any other cached connections */
1123 			mci_flush(FALSE, mci);
1124 
1125 			/* reset user and group */
1126 			if (!bitnset(M_RESTR, m->m_flags))
1127 			{
1128 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1129 				{
1130 					(void) initgroups(DefUser, DefGid);
1131 					(void) setuid(DefUid);
1132 				}
1133 				else
1134 				{
1135 					(void) initgroups(ctladdr->q_ruser?
1136 						ctladdr->q_ruser: ctladdr->q_user,
1137 						ctladdr->q_gid);
1138 					(void) setuid(ctladdr->q_uid);
1139 				}
1140 			}
1141 
1142 			if (tTd(11, 2))
1143 				printf("openmailer: running as r/euid=%d/%d\n",
1144 					getuid(), geteuid());
1145 
1146 			/* move into some "safe" directory */
1147 			if (m->m_execdir != NULL)
1148 			{
1149 				char *p, *q;
1150 				char buf[MAXLINE];
1151 
1152 				for (p = m->m_execdir; p != NULL; p = q)
1153 				{
1154 					q = strchr(p, ':');
1155 					if (q != NULL)
1156 						*q = '\0';
1157 					expand(p, buf, &buf[sizeof buf] - 1, e);
1158 					if (q != NULL)
1159 						*q++ = ':';
1160 					if (tTd(11, 20))
1161 						printf("openmailer: trydir %s\n",
1162 							buf);
1163 					if (buf[0] != '\0' && chdir(buf) >= 0)
1164 						break;
1165 				}
1166 			}
1167 
1168 			/* arrange to filter std & diag output of command */
1169 			if (clever)
1170 			{
1171 				(void) close(rpvect[0]);
1172 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1173 				{
1174 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1175 						e->e_to, m->m_name, rpvect[1]);
1176 					_exit(EX_OSERR);
1177 				}
1178 				(void) close(rpvect[1]);
1179 			}
1180 			else if (OpMode == MD_SMTP || HoldErrs)
1181 			{
1182 				/* put mailer output in transcript */
1183 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1184 				{
1185 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1186 						e->e_to, m->m_name,
1187 						fileno(e->e_xfp));
1188 					_exit(EX_OSERR);
1189 				}
1190 			}
1191 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1192 			{
1193 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1194 					e->e_to, m->m_name);
1195 				_exit(EX_OSERR);
1196 			}
1197 
1198 			/* arrange to get standard input */
1199 			(void) close(mpvect[1]);
1200 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1201 			{
1202 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1203 					e->e_to, m->m_name, mpvect[0]);
1204 				_exit(EX_OSERR);
1205 			}
1206 			(void) close(mpvect[0]);
1207 
1208 			/* arrange for all the files to be closed */
1209 			for (i = 3; i < DtableSize; i++)
1210 			{
1211 				register int j;
1212 
1213 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1214 					(void) fcntl(i, F_SETFD, j | 1);
1215 			}
1216 
1217 			/* set up the mailer environment */
1218 			i = 0;
1219 			env[i++] = "AGENT=sendmail";
1220 			for (ep = environ; *ep != NULL; ep++)
1221 			{
1222 				if (strncmp(*ep, "TZ=", 3) == 0)
1223 					env[i++] = *ep;
1224 			}
1225 			env[i++] = NULL;
1226 
1227 			/* try to execute the mailer */
1228 			execve(m->m_mailer, pv, env);
1229 			saveerrno = errno;
1230 			syserr("Cannot exec %s", m->m_mailer);
1231 			if (m == LocalMailer || transienterror(saveerrno))
1232 				_exit(EX_OSERR);
1233 			_exit(EX_UNAVAILABLE);
1234 		}
1235 
1236 		/*
1237 		**  Set up return value.
1238 		*/
1239 
1240 		mci = (MCI *) xalloc(sizeof *mci);
1241 		bzero((char *) mci, sizeof *mci);
1242 		mci->mci_mailer = m;
1243 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1244 		mci->mci_pid = pid;
1245 		(void) close(mpvect[0]);
1246 		mci->mci_out = fdopen(mpvect[1], "w");
1247 		if (clever)
1248 		{
1249 			(void) close(rpvect[1]);
1250 			mci->mci_in = fdopen(rpvect[0], "r");
1251 		}
1252 		else
1253 		{
1254 			mci->mci_flags |= MCIF_TEMP;
1255 			mci->mci_in = NULL;
1256 		}
1257 	}
1258 
1259 	/*
1260 	**  If we are in SMTP opening state, send initial protocol.
1261 	*/
1262 
1263 	if (clever && mci->mci_state != MCIS_CLOSED)
1264 	{
1265 		smtpinit(m, mci, e);
1266 	}
1267 	if (tTd(11, 1))
1268 	{
1269 		printf("openmailer: ");
1270 		mci_dump(mci);
1271 	}
1272 
1273 	if (mci->mci_state != MCIS_OPEN)
1274 	{
1275 		/* couldn't open the mailer */
1276 		rcode = mci->mci_exitstat;
1277 		errno = mci->mci_errno;
1278 #ifdef NAMED_BIND
1279 		h_errno = mci->mci_herrno;
1280 #endif
1281 		if (rcode == EX_OK)
1282 		{
1283 			/* shouldn't happen */
1284 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1285 				rcode, mci->mci_state, firstsig);
1286 			rcode = EX_SOFTWARE;
1287 		}
1288 		else if (rcode == EX_TEMPFAIL && *curhost != '\0')
1289 		{
1290 			/* try next MX site */
1291 			goto tryhost;
1292 		}
1293 	}
1294 	else if (!clever)
1295 	{
1296 		/*
1297 		**  Format and send message.
1298 		*/
1299 
1300 		putfromline(mci->mci_out, m, e);
1301 		(*e->e_puthdr)(mci->mci_out, m, e);
1302 		putline("\n", mci->mci_out, m);
1303 		(*e->e_putbody)(mci->mci_out, m, e, NULL);
1304 
1305 		/* get the exit status */
1306 		rcode = endmailer(mci, e, pv);
1307 	}
1308 	else
1309 #ifdef SMTP
1310 	{
1311 		/*
1312 		**  Send the MAIL FROM: protocol
1313 		*/
1314 
1315 		rcode = smtpmailfrom(m, mci, e);
1316 		if (rcode == EX_OK)
1317 		{
1318 			register char *t = tobuf;
1319 			register int i;
1320 
1321 			/* send the recipient list */
1322 			tobuf[0] = '\0';
1323 			for (to = tochain; to != NULL; to = to->q_tchain)
1324 			{
1325 				e->e_to = to->q_paddr;
1326 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1327 				{
1328 					markfailure(e, to, i);
1329 					giveresponse(i, m, mci, e);
1330 				}
1331 				else
1332 				{
1333 					*t++ = ',';
1334 					for (p = to->q_paddr; *p; *t++ = *p++)
1335 						continue;
1336 					*t = '\0';
1337 				}
1338 			}
1339 
1340 			/* now send the data */
1341 			if (tobuf[0] == '\0')
1342 			{
1343 				rcode = EX_OK;
1344 				e->e_to = NULL;
1345 				if (bitset(MCIF_CACHED, mci->mci_flags))
1346 					smtprset(m, mci, e);
1347 			}
1348 			else
1349 			{
1350 				e->e_to = tobuf + 1;
1351 				rcode = smtpdata(m, mci, e);
1352 			}
1353 
1354 			/* now close the connection */
1355 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1356 				smtpquit(m, mci, e);
1357 		}
1358 		if (rcode != EX_OK && *curhost != '\0')
1359 		{
1360 			/* try next MX site */
1361 			goto tryhost;
1362 		}
1363 	}
1364 #else /* not SMTP */
1365 	{
1366 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1367 		rcode = EX_CONFIG;
1368 		goto give_up;
1369 	}
1370 #endif /* SMTP */
1371 #ifdef NAMED_BIND
1372 	if (ConfigLevel < 2)
1373 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1374 #endif
1375 
1376 	/* arrange a return receipt if requested */
1377 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1378 	    bitnset(M_LOCALMAILER, m->m_flags))
1379 	{
1380 		e->e_flags |= EF_SENDRECEIPT;
1381 		/* do we want to send back more info? */
1382 	}
1383 
1384 	/*
1385 	**  Do final status disposal.
1386 	**	We check for something in tobuf for the SMTP case.
1387 	**	If we got a temporary failure, arrange to queue the
1388 	**		addressees.
1389 	*/
1390 
1391   give_up:
1392 	if (tobuf[0] != '\0')
1393 		giveresponse(rcode, m, mci, e);
1394 	for (to = tochain; to != NULL; to = to->q_tchain)
1395 	{
1396 		if (rcode != EX_OK)
1397 			markfailure(e, to, rcode);
1398 		else
1399 		{
1400 			to->q_flags |= QSENT;
1401 			e->e_nsent++;
1402 			if (e->e_receiptto != NULL &&
1403 			    bitnset(M_LOCALMAILER, m->m_flags))
1404 			{
1405 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1406 					to->q_paddr);
1407 			}
1408 		}
1409 	}
1410 
1411 	/*
1412 	**  Restore state and return.
1413 	*/
1414 
1415 #ifdef XDEBUG
1416 	{
1417 		char wbuf[MAXLINE];
1418 
1419 		/* make absolutely certain 0, 1, and 2 are in use */
1420 		sprintf(wbuf, "%s... end of deliver(%s)",
1421 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1422 			m->m_name);
1423 		checkfd012(wbuf);
1424 	}
1425 #endif
1426 
1427 	errno = 0;
1428 	define('g', (char *) NULL, e);
1429 	return (rcode);
1430 }
1431 /*
1432 **  MARKFAILURE -- mark a failure on a specific address.
1433 **
1434 **	Parameters:
1435 **		e -- the envelope we are sending.
1436 **		q -- the address to mark.
1437 **		rcode -- the code signifying the particular failure.
1438 **
1439 **	Returns:
1440 **		none.
1441 **
1442 **	Side Effects:
1443 **		marks the address (and possibly the envelope) with the
1444 **			failure so that an error will be returned or
1445 **			the message will be queued, as appropriate.
1446 */
1447 
1448 markfailure(e, q, rcode)
1449 	register ENVELOPE *e;
1450 	register ADDRESS *q;
1451 	int rcode;
1452 {
1453 	char buf[MAXLINE];
1454 
1455 	if (rcode == EX_OK)
1456 		return;
1457 	else if (rcode == EX_TEMPFAIL)
1458 		q->q_flags |= QQUEUEUP;
1459 	else if (rcode != EX_IOERR && rcode != EX_OSERR)
1460 		q->q_flags |= QBADADDR;
1461 }
1462 /*
1463 **  ENDMAILER -- Wait for mailer to terminate.
1464 **
1465 **	We should never get fatal errors (e.g., segmentation
1466 **	violation), so we report those specially.  For other
1467 **	errors, we choose a status message (into statmsg),
1468 **	and if it represents an error, we print it.
1469 **
1470 **	Parameters:
1471 **		pid -- pid of mailer.
1472 **		e -- the current envelope.
1473 **		pv -- the parameter vector that invoked the mailer
1474 **			(for error messages).
1475 **
1476 **	Returns:
1477 **		exit code of mailer.
1478 **
1479 **	Side Effects:
1480 **		none.
1481 */
1482 
1483 endmailer(mci, e, pv)
1484 	register MCI *mci;
1485 	register ENVELOPE *e;
1486 	char **pv;
1487 {
1488 	int st;
1489 
1490 	/* close any connections */
1491 	if (mci->mci_in != NULL)
1492 		(void) xfclose(mci->mci_in, pv[0], "mci_in");
1493 	if (mci->mci_out != NULL)
1494 		(void) xfclose(mci->mci_out, pv[0], "mci_out");
1495 	mci->mci_in = mci->mci_out = NULL;
1496 	mci->mci_state = MCIS_CLOSED;
1497 
1498 	/* in the IPC case there is nothing to wait for */
1499 	if (mci->mci_pid == 0)
1500 		return (EX_OK);
1501 
1502 	/* wait for the mailer process to die and collect status */
1503 	st = waitfor(mci->mci_pid);
1504 	if (st == -1)
1505 	{
1506 		syserr("endmailer %s: wait", pv[0]);
1507 		return (EX_SOFTWARE);
1508 	}
1509 
1510 	if (WIFEXITED(st))
1511 	{
1512 		/* normal death -- return status */
1513 		return (WEXITSTATUS(st));
1514 	}
1515 
1516 	/* it died a horrid death */
1517 	syserr("mailer %s died with signal %o", pv[0], st);
1518 
1519 	/* log the arguments */
1520 	if (e->e_xfp != NULL)
1521 	{
1522 		register char **av;
1523 
1524 		fprintf(e->e_xfp, "Arguments:");
1525 		for (av = pv; *av != NULL; av++)
1526 			fprintf(e->e_xfp, " %s", *av);
1527 		fprintf(e->e_xfp, "\n");
1528 	}
1529 
1530 	ExitStat = EX_TEMPFAIL;
1531 	return (EX_TEMPFAIL);
1532 }
1533 /*
1534 **  GIVERESPONSE -- Interpret an error response from a mailer
1535 **
1536 **	Parameters:
1537 **		stat -- the status code from the mailer (high byte
1538 **			only; core dumps must have been taken care of
1539 **			already).
1540 **		m -- the mailer info for this mailer.
1541 **		mci -- the mailer connection info -- can be NULL if the
1542 **			response is given before the connection is made.
1543 **		e -- the current envelope.
1544 **
1545 **	Returns:
1546 **		none.
1547 **
1548 **	Side Effects:
1549 **		Errors may be incremented.
1550 **		ExitStat may be set.
1551 */
1552 
1553 giveresponse(stat, m, mci, e)
1554 	int stat;
1555 	register MAILER *m;
1556 	register MCI *mci;
1557 	ENVELOPE *e;
1558 {
1559 	register const char *statmsg;
1560 	extern char *SysExMsg[];
1561 	register int i;
1562 	extern int N_SysEx;
1563 	char buf[MAXLINE];
1564 
1565 	/*
1566 	**  Compute status message from code.
1567 	*/
1568 
1569 	i = stat - EX__BASE;
1570 	if (stat == 0)
1571 	{
1572 		statmsg = "250 Sent";
1573 		if (e->e_statmsg != NULL)
1574 		{
1575 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1576 			statmsg = buf;
1577 		}
1578 	}
1579 	else if (i < 0 || i > N_SysEx)
1580 	{
1581 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1582 		stat = EX_UNAVAILABLE;
1583 		statmsg = buf;
1584 	}
1585 	else if (stat == EX_TEMPFAIL)
1586 	{
1587 		(void) strcpy(buf, SysExMsg[i] + 1);
1588 #ifdef NAMED_BIND
1589 		if (h_errno == TRY_AGAIN)
1590 			statmsg = errstring(h_errno+E_DNSBASE);
1591 		else
1592 #endif
1593 		{
1594 			if (errno != 0)
1595 				statmsg = errstring(errno);
1596 			else
1597 			{
1598 #ifdef SMTP
1599 				extern char SmtpError[];
1600 
1601 				statmsg = SmtpError;
1602 #else /* SMTP */
1603 				statmsg = NULL;
1604 #endif /* SMTP */
1605 			}
1606 		}
1607 		if (statmsg != NULL && statmsg[0] != '\0')
1608 		{
1609 			(void) strcat(buf, ": ");
1610 			(void) strcat(buf, statmsg);
1611 		}
1612 		statmsg = buf;
1613 	}
1614 #ifdef NAMED_BIND
1615 	else if (stat == EX_NOHOST && h_errno != 0)
1616 	{
1617 		statmsg = errstring(h_errno + E_DNSBASE);
1618 		(void) sprintf(buf, "%s (%s)", SysExMsg[i], statmsg);
1619 		statmsg = buf;
1620 	}
1621 #endif
1622 	else
1623 	{
1624 		statmsg = SysExMsg[i];
1625 		if (*statmsg++ == ':')
1626 		{
1627 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1628 			statmsg = buf;
1629 		}
1630 	}
1631 
1632 	/*
1633 	**  Print the message as appropriate
1634 	*/
1635 
1636 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1637 	{
1638 		extern char MsgBuf[];
1639 
1640 		message(&statmsg[4], errstring(errno));
1641 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1642 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1643 	}
1644 	else
1645 	{
1646 		Errors++;
1647 		usrerr(statmsg, errstring(errno));
1648 	}
1649 
1650 	/*
1651 	**  Final cleanup.
1652 	**	Log a record of the transaction.  Compute the new
1653 	**	ExitStat -- if we already had an error, stick with
1654 	**	that.
1655 	*/
1656 
1657 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1658 		logdelivery(m, mci, &statmsg[4], e);
1659 
1660 	if (stat != EX_TEMPFAIL)
1661 		setstat(stat);
1662 	if (stat != EX_OK)
1663 	{
1664 		if (e->e_message != NULL)
1665 			free(e->e_message);
1666 		e->e_message = newstr(&statmsg[4]);
1667 	}
1668 	errno = 0;
1669 #ifdef NAMED_BIND
1670 	h_errno = 0;
1671 #endif
1672 }
1673 /*
1674 **  LOGDELIVERY -- log the delivery in the system log
1675 **
1676 **	Parameters:
1677 **		m -- the mailer info.  Can be NULL for initial queue.
1678 **		mci -- the mailer connection info -- can be NULL if the
1679 **			log is occuring when no connection is active.
1680 **		stat -- the message to print for the status.
1681 **		e -- the current envelope.
1682 **
1683 **	Returns:
1684 **		none
1685 **
1686 **	Side Effects:
1687 **		none
1688 */
1689 
1690 logdelivery(m, mci, stat, e)
1691 	MAILER *m;
1692 	register MCI *mci;
1693 	char *stat;
1694 	register ENVELOPE *e;
1695 {
1696 # ifdef LOG
1697 	char buf[512];
1698 
1699 	(void) sprintf(buf, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1700 
1701 	if (m != NULL)
1702 	{
1703 		(void) strcat(buf, ", mailer=");
1704 		(void) strcat(buf, m->m_name);
1705 	}
1706 
1707 	if (mci != NULL && mci->mci_host != NULL)
1708 	{
1709 # ifdef DAEMON
1710 		extern SOCKADDR CurHostAddr;
1711 # endif
1712 
1713 		(void) strcat(buf, ", relay=");
1714 		(void) strcat(buf, mci->mci_host);
1715 
1716 # ifdef DAEMON
1717 		(void) strcat(buf, " (");
1718 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
1719 		(void) strcat(buf, ")");
1720 # endif
1721 	}
1722 	else
1723 	{
1724 		char *p = macvalue('h', e);
1725 
1726 		if (p != NULL && p[0] != '\0')
1727 		{
1728 			(void) strcat(buf, ", relay=");
1729 			(void) strcat(buf, p);
1730 		}
1731 	}
1732 
1733 	syslog(LOG_INFO, "%s: to=%s, %s, stat=%s",
1734 	       e->e_id, e->e_to, buf, stat);
1735 # endif /* LOG */
1736 }
1737 /*
1738 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1739 **
1740 **	This can be made an arbitrary message separator by changing $l
1741 **
1742 **	One of the ugliest hacks seen by human eyes is contained herein:
1743 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1744 **	does a well-meaning programmer such as myself have to deal with
1745 **	this kind of antique garbage????
1746 **
1747 **	Parameters:
1748 **		fp -- the file to output to.
1749 **		m -- the mailer describing this entry.
1750 **
1751 **	Returns:
1752 **		none
1753 **
1754 **	Side Effects:
1755 **		outputs some text to fp.
1756 */
1757 
1758 putfromline(fp, m, e)
1759 	register FILE *fp;
1760 	register MAILER *m;
1761 	ENVELOPE *e;
1762 {
1763 	char *template = "\201l\n";
1764 	char buf[MAXLINE];
1765 
1766 	if (bitnset(M_NHDR, m->m_flags))
1767 		return;
1768 
1769 # ifdef UGLYUUCP
1770 	if (bitnset(M_UGLYUUCP, m->m_flags))
1771 	{
1772 		char *bang;
1773 		char xbuf[MAXLINE];
1774 
1775 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1776 		bang = strchr(buf, '!');
1777 		if (bang == NULL)
1778 		{
1779 			errno = 0;
1780 			syserr("554 No ! in UUCP From address! (%s given)", buf);
1781 		}
1782 		else
1783 		{
1784 			*bang++ = '\0';
1785 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1786 			template = xbuf;
1787 		}
1788 	}
1789 # endif /* UGLYUUCP */
1790 	expand(template, buf, &buf[sizeof buf - 1], e);
1791 	putline(buf, fp, m);
1792 }
1793 /*
1794 **  PUTBODY -- put the body of a message.
1795 **
1796 **	Parameters:
1797 **		fp -- file to output onto.
1798 **		m -- a mailer descriptor to control output format.
1799 **		e -- the envelope to put out.
1800 **		separator -- if non-NULL, a message separator that must
1801 **			not be permitted in the resulting message.
1802 **
1803 **	Returns:
1804 **		none.
1805 **
1806 **	Side Effects:
1807 **		The message is written onto fp.
1808 */
1809 
1810 putbody(fp, m, e, separator)
1811 	FILE *fp;
1812 	MAILER *m;
1813 	register ENVELOPE *e;
1814 	char *separator;
1815 {
1816 	char buf[MAXLINE];
1817 
1818 	/*
1819 	**  Output the body of the message
1820 	*/
1821 
1822 	if (e->e_dfp == NULL)
1823 	{
1824 		if (e->e_df != NULL)
1825 		{
1826 			e->e_dfp = fopen(e->e_df, "r");
1827 			if (e->e_dfp == NULL)
1828 				syserr("putbody: Cannot open %s for %s from %s",
1829 				e->e_df, e->e_to, e->e_from.q_paddr);
1830 		}
1831 		else
1832 			putline("<<< No Message Collected >>>", fp, m);
1833 	}
1834 	if (e->e_dfp != NULL)
1835 	{
1836 		rewind(e->e_dfp);
1837 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1838 		{
1839 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1840 			    strncmp(buf, "From ", 5) == 0)
1841 				(void) putc('>', fp);
1842 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
1843 			{
1844 				/* possible separator */
1845 				int sl = strlen(separator);
1846 
1847 				if (strncmp(&buf[2], separator, sl) == 0)
1848 					(void) putc(' ', fp);
1849 			}
1850 			putline(buf, fp, m);
1851 		}
1852 
1853 		if (ferror(e->e_dfp))
1854 		{
1855 			syserr("putbody: %s: read error", e->e_df);
1856 			ExitStat = EX_IOERR;
1857 		}
1858 	}
1859 
1860 	/* some mailers want extra blank line at end of message */
1861 	if (bitnset(M_BLANKEND, m->m_flags) && buf[0] != '\0' && buf[0] != '\n')
1862 		putline("", fp, m);
1863 
1864 	(void) fflush(fp);
1865 	if (ferror(fp) && errno != EPIPE)
1866 	{
1867 		syserr("putbody: write error");
1868 		ExitStat = EX_IOERR;
1869 	}
1870 	errno = 0;
1871 }
1872 /*
1873 **  MAILFILE -- Send a message to a file.
1874 **
1875 **	If the file has the setuid/setgid bits set, but NO execute
1876 **	bits, sendmail will try to become the owner of that file
1877 **	rather than the real user.  Obviously, this only works if
1878 **	sendmail runs as root.
1879 **
1880 **	This could be done as a subordinate mailer, except that it
1881 **	is used implicitly to save messages in ~/dead.letter.  We
1882 **	view this as being sufficiently important as to include it
1883 **	here.  For example, if the system is dying, we shouldn't have
1884 **	to create another process plus some pipes to save the message.
1885 **
1886 **	Parameters:
1887 **		filename -- the name of the file to send to.
1888 **		ctladdr -- the controlling address header -- includes
1889 **			the userid/groupid to be when sending.
1890 **
1891 **	Returns:
1892 **		The exit code associated with the operation.
1893 **
1894 **	Side Effects:
1895 **		none.
1896 */
1897 
1898 mailfile(filename, ctladdr, e)
1899 	char *filename;
1900 	ADDRESS *ctladdr;
1901 	register ENVELOPE *e;
1902 {
1903 	register FILE *f;
1904 	register int pid;
1905 	int mode;
1906 
1907 	if (tTd(11, 1))
1908 	{
1909 		printf("mailfile %s\n  ctladdr=", filename);
1910 		printaddr(ctladdr, FALSE);
1911 	}
1912 
1913 	if (e->e_xfp != NULL)
1914 		fflush(e->e_xfp);
1915 
1916 	/*
1917 	**  Fork so we can change permissions here.
1918 	**	Note that we MUST use fork, not vfork, because of
1919 	**	the complications of calling subroutines, etc.
1920 	*/
1921 
1922 	DOFORK(fork);
1923 
1924 	if (pid < 0)
1925 		return (EX_OSERR);
1926 	else if (pid == 0)
1927 	{
1928 		/* child -- actually write to file */
1929 		struct stat stb;
1930 
1931 		(void) setsignal(SIGINT, SIG_DFL);
1932 		(void) setsignal(SIGHUP, SIG_DFL);
1933 		(void) setsignal(SIGTERM, SIG_DFL);
1934 		(void) umask(OldUmask);
1935 
1936 		if (stat(filename, &stb) < 0)
1937 			stb.st_mode = FileMode;
1938 		mode = stb.st_mode;
1939 
1940 		/* limit the errors to those actually caused in the child */
1941 		errno = 0;
1942 		ExitStat = EX_OK;
1943 
1944 		if (bitset(0111, stb.st_mode))
1945 			exit(EX_CANTCREAT);
1946 		if (ctladdr == NULL)
1947 			ctladdr = &e->e_from;
1948 		else
1949 		{
1950 			/* ignore setuid and setgid bits */
1951 			mode &= ~(S_ISGID|S_ISUID);
1952 		}
1953 
1954 		/* we have to open the dfile BEFORE setuid */
1955 		if (e->e_dfp == NULL && e->e_df != NULL)
1956 		{
1957 			e->e_dfp = fopen(e->e_df, "r");
1958 			if (e->e_dfp == NULL)
1959 			{
1960 				syserr("mailfile: Cannot open %s for %s from %s",
1961 					e->e_df, e->e_to, e->e_from.q_paddr);
1962 			}
1963 		}
1964 
1965 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
1966 		{
1967 			if (ctladdr->q_uid == 0)
1968 			{
1969 				(void) initgroups(DefUser, DefGid);
1970 			}
1971 			else
1972 			{
1973 				(void) initgroups(ctladdr->q_ruser ?
1974 					ctladdr->q_ruser : ctladdr->q_user,
1975 					ctladdr->q_gid);
1976 			}
1977 		}
1978 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
1979 		{
1980 			if (ctladdr->q_uid == 0)
1981 				(void) setuid(DefUid);
1982 			else
1983 				(void) setuid(ctladdr->q_uid);
1984 		}
1985 		FileName = filename;
1986 		LineNumber = 0;
1987 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
1988 		if (f == NULL)
1989 		{
1990 			message("554 cannot open: %s", errstring(errno));
1991 			exit(EX_CANTCREAT);
1992 		}
1993 
1994 		putfromline(f, FileMailer, e);
1995 		(*e->e_puthdr)(f, FileMailer, e);
1996 		putline("\n", f, FileMailer);
1997 		(*e->e_putbody)(f, FileMailer, e, NULL);
1998 		putline("\n", f, FileMailer);
1999 		if (ferror(f))
2000 		{
2001 			message("451 I/O error: %s", errstring(errno));
2002 			setstat(EX_IOERR);
2003 		}
2004 		(void) xfclose(f, "mailfile", filename);
2005 		(void) fflush(stdout);
2006 
2007 		/* reset ISUID & ISGID bits for paranoid systems */
2008 		(void) chmod(filename, (int) stb.st_mode);
2009 		exit(ExitStat);
2010 		/*NOTREACHED*/
2011 	}
2012 	else
2013 	{
2014 		/* parent -- wait for exit status */
2015 		int st;
2016 
2017 		st = waitfor(pid);
2018 		if (WIFEXITED(st))
2019 			return (WEXITSTATUS(st));
2020 		else
2021 		{
2022 			syserr("child died on signal %d", st);
2023 			return (EX_UNAVAILABLE);
2024 		}
2025 		/*NOTREACHED*/
2026 	}
2027 }
2028 /*
2029 **  HOSTSIGNATURE -- return the "signature" for a host.
2030 **
2031 **	The signature describes how we are going to send this -- it
2032 **	can be just the hostname (for non-Internet hosts) or can be
2033 **	an ordered list of MX hosts.
2034 **
2035 **	Parameters:
2036 **		m -- the mailer describing this host.
2037 **		host -- the host name.
2038 **		e -- the current envelope.
2039 **
2040 **	Returns:
2041 **		The signature for this host.
2042 **
2043 **	Side Effects:
2044 **		Can tweak the symbol table.
2045 */
2046 
2047 char *
2048 hostsignature(m, host, e)
2049 	register MAILER *m;
2050 	char *host;
2051 	ENVELOPE *e;
2052 {
2053 	register char *p;
2054 	register STAB *s;
2055 	int i;
2056 	int len;
2057 #ifdef NAMED_BIND
2058 	int nmx;
2059 	auto int rcode;
2060 	char *hp;
2061 	char *endp;
2062 	int oldoptions;
2063 	char *mxhosts[MAXMXHOSTS + 1];
2064 #endif
2065 
2066 	/*
2067 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2068 	*/
2069 
2070 	p = m->m_mailer;
2071 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2072 	{
2073 		/* just an ordinary mailer */
2074 		return host;
2075 	}
2076 
2077 	/*
2078 	**  Look it up in the symbol table.
2079 	*/
2080 
2081 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2082 	if (s->s_hostsig != NULL)
2083 		return s->s_hostsig;
2084 
2085 	/*
2086 	**  Not already there -- create a signature.
2087 	*/
2088 
2089 #ifdef NAMED_BIND
2090 	if (ConfigLevel < 2)
2091 	{
2092 		oldoptions = _res.options;
2093 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2094 	}
2095 
2096 	for (hp = host; hp != NULL; hp = endp)
2097 	{
2098 		endp = strchr(hp, ':');
2099 		if (endp != NULL)
2100 			*endp = '\0';
2101 
2102 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2103 
2104 		if (nmx <= 0)
2105 		{
2106 			register MCI *mci;
2107 			extern int errno;
2108 
2109 			/* update the connection info for this host */
2110 			mci = mci_get(hp, m);
2111 			mci->mci_exitstat = rcode;
2112 			mci->mci_errno = errno;
2113 #ifdef NAMED_BIND
2114 			mci->mci_herrno = h_errno;
2115 #endif
2116 
2117 			/* and return the original host name as the signature */
2118 			nmx = 1;
2119 			mxhosts[0] = hp;
2120 		}
2121 
2122 		len = 0;
2123 		for (i = 0; i < nmx; i++)
2124 		{
2125 			len += strlen(mxhosts[i]) + 1;
2126 		}
2127 		if (s->s_hostsig != NULL)
2128 			len += strlen(s->s_hostsig) + 1;
2129 		p = xalloc(len);
2130 		if (s->s_hostsig != NULL)
2131 		{
2132 			(void) strcpy(p, s->s_hostsig);
2133 			free(s->s_hostsig);
2134 			s->s_hostsig = p;
2135 			p += strlen(p);
2136 			*p++ = ':';
2137 		}
2138 		else
2139 			s->s_hostsig = p;
2140 		for (i = 0; i < nmx; i++)
2141 		{
2142 			if (i != 0)
2143 				*p++ = ':';
2144 			strcpy(p, mxhosts[i]);
2145 			p += strlen(p);
2146 		}
2147 		if (endp != NULL)
2148 			*endp++ = ':';
2149 	}
2150 	makelower(s->s_hostsig);
2151 	if (ConfigLevel < 2)
2152 		_res.options = oldoptions;
2153 #else
2154 	/* not using BIND -- the signature is just the host name */
2155 	s->s_hostsig = host;
2156 #endif
2157 	if (tTd(17, 1))
2158 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2159 	return s->s_hostsig;
2160 }
2161