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