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