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