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.84.1.3 (Berkeley) 03/05/95";
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 		queueup(e, TRUE, announcequeueup);
102 		e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
103 		syserr("554 too many hops %d (%d max): from %s via %s, to %s",
104 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
105 			RealHostName == NULL ? "localhost" : RealHostName,
106 			e->e_sendqueue->q_paddr);
107 		return;
108 	}
109 
110 	/*
111 	**  Do sender deletion.
112 	**
113 	**	If the sender has the QQUEUEUP flag set, skip this.
114 	**	This can happen if the name server is hosed when you
115 	**	are trying to send mail.  The result is that the sender
116 	**	is instantiated in the queue as a recipient.
117 	*/
118 
119 	if (!bitset(EF_METOO, e->e_flags) &&
120 	    !bitset(QQUEUEUP, e->e_from.q_flags))
121 	{
122 		if (tTd(13, 5))
123 		{
124 			printf("sendall: QDONTSEND ");
125 			printaddr(&e->e_from, FALSE);
126 		}
127 		e->e_from.q_flags |= QDONTSEND;
128 		(void) recipient(&e->e_from, &e->e_sendqueue, e);
129 	}
130 
131 	/*
132 	**  Handle alias owners.
133 	**
134 	**	We scan up the q_alias chain looking for owners.
135 	**	We discard owners that are the same as the return path.
136 	*/
137 
138 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
139 	{
140 		register struct address *a;
141 
142 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
143 			continue;
144 		if (a != NULL)
145 			q->q_owner = a->q_owner;
146 
147 		if (q->q_owner != NULL &&
148 		    !bitset(QDONTSEND, q->q_flags) &&
149 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
150 			q->q_owner = NULL;
151 	}
152 
153 	owner = "";
154 	otherowners = 1;
155 	while (owner != NULL && otherowners > 0)
156 	{
157 		owner = NULL;
158 		otherowners = 0;
159 
160 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
161 		{
162 			if (bitset(QDONTSEND, q->q_flags))
163 				continue;
164 
165 			if (q->q_owner != NULL)
166 			{
167 				if (owner == NULL)
168 					owner = q->q_owner;
169 				else if (owner != q->q_owner)
170 				{
171 					if (strcmp(owner, q->q_owner) == 0)
172 					{
173 						/* make future comparisons cheap */
174 						q->q_owner = owner;
175 					}
176 					else
177 					{
178 						otherowners++;
179 					}
180 					owner = q->q_owner;
181 				}
182 			}
183 			else
184 			{
185 				otherowners++;
186 			}
187 		}
188 
189 		if (owner != NULL && otherowners > 0)
190 		{
191 			extern HDR *copyheader();
192 			extern ADDRESS *copyqueue();
193 
194 			/*
195 			**  Split this envelope into two.
196 			*/
197 
198 			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
199 			*ee = *e;
200 			ee->e_id = NULL;
201 			(void) queuename(ee, '\0');
202 
203 			if (tTd(13, 1))
204 				printf("sendall: split %s into %s\n",
205 					e->e_id, ee->e_id);
206 
207 			ee->e_header = copyheader(e->e_header);
208 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
209 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
210 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT);
211 			ee->e_flags |= EF_NORECEIPT;
212 			setsender(owner, ee, NULL, TRUE);
213 			if (tTd(13, 5))
214 			{
215 				printf("sendall(split): QDONTSEND ");
216 				printaddr(&ee->e_from, FALSE);
217 			}
218 			ee->e_from.q_flags |= QDONTSEND;
219 			ee->e_dfp = NULL;
220 			ee->e_xfp = NULL;
221 			ee->e_df = NULL;
222 			ee->e_errormode = EM_MAIL;
223 			ee->e_sibling = splitenv;
224 			splitenv = ee;
225 
226 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
227 				if (q->q_owner == owner)
228 				{
229 					q->q_flags |= QDONTSEND;
230 					q->q_flags &= ~QQUEUEUP;
231 				}
232 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
233 				if (q->q_owner != owner)
234 				{
235 					q->q_flags |= QDONTSEND;
236 					q->q_flags &= ~QQUEUEUP;
237 				}
238 
239 			if (e->e_df != NULL && mode != SM_VERIFY)
240 			{
241 				ee->e_dfp = NULL;
242 				ee->e_df = queuename(ee, 'd');
243 				ee->e_df = newstr(ee->e_df);
244 				if (link(e->e_df, ee->e_df) < 0)
245 				{
246 					syserr("sendall: link(%s, %s)",
247 						e->e_df, ee->e_df);
248 				}
249 			}
250 #ifdef LOG
251 			if (LogLevel > 4)
252 				syslog(LOG_INFO, "%s: clone %s, owner=%s",
253 					ee->e_id, e->e_id, owner);
254 #endif
255 		}
256 	}
257 
258 	if (owner != NULL)
259 	{
260 		setsender(owner, e, NULL, TRUE);
261 		if (tTd(13, 5))
262 		{
263 			printf("sendall(owner): QDONTSEND ");
264 			printaddr(&e->e_from, FALSE);
265 		}
266 		e->e_from.q_flags |= QDONTSEND;
267 		e->e_errormode = EM_MAIL;
268 		e->e_flags |= EF_NORECEIPT;
269 	}
270 
271 # ifdef QUEUE
272 	if ((mode == SM_QUEUE || mode == SM_FORK ||
273 	     (mode != SM_VERIFY && SuperSafe)) &&
274 	    !bitset(EF_INQUEUE, e->e_flags))
275 	{
276 		/* be sure everything is instantiated in the queue */
277 		queueup(e, TRUE, announcequeueup);
278 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
279 			queueup(ee, TRUE, announcequeueup);
280 	}
281 #endif /* QUEUE */
282 
283 	if (splitenv != NULL)
284 	{
285 		if (tTd(13, 1))
286 		{
287 			printf("\nsendall: Split queue; remaining queue:\n");
288 			printaddr(e->e_sendqueue, TRUE);
289 		}
290 
291 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
292 		{
293 			CurEnv = ee;
294 			if (mode != SM_VERIFY)
295 				openxscript(ee);
296 			sendenvelope(ee, mode);
297 			dropenvelope(ee);
298 		}
299 
300 		CurEnv = e;
301 	}
302 	sendenvelope(e, mode);
303 }
304 
305 sendenvelope(e, mode)
306 	register ENVELOPE *e;
307 	char mode;
308 {
309 	bool oldverbose;
310 	int pid;
311 	register ADDRESS *q;
312 	char *qf;
313 	char *id;
314 
315 	/*
316 	**  If we have had global, fatal errors, don't bother sending
317 	**  the message at all if we are in SMTP mode.  Local errors
318 	**  (e.g., a single address failing) will still cause the other
319 	**  addresses to be sent.
320 	*/
321 
322 	if (bitset(EF_FATALERRS, e->e_flags) &&
323 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
324 	{
325 		e->e_flags |= EF_CLRQUEUE;
326 		return;
327 	}
328 
329 	oldverbose = Verbose;
330 	switch (mode)
331 	{
332 	  case SM_VERIFY:
333 		Verbose = TRUE;
334 		break;
335 
336 	  case SM_QUEUE:
337   queueonly:
338 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
339 		return;
340 
341 	  case SM_FORK:
342 		if (e->e_xfp != NULL)
343 			(void) fflush(e->e_xfp);
344 
345 # if !HASFLOCK
346 		/*
347 		**  Since fcntl locking has the interesting semantic that
348 		**  the lock is owned by a process, not by an open file
349 		**  descriptor, we have to flush this to the queue, and
350 		**  then restart from scratch in the child.
351 		*/
352 
353 		/* save id for future use */
354 		id = e->e_id;
355 
356 		/* now drop the envelope in the parent */
357 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
358 		dropenvelope(e);
359 
360 		/* and reacquire in the child */
361 		(void) dowork(id, TRUE, FALSE, e);
362 
363 		return;
364 
365 # else /* HASFLOCK */
366 
367 		pid = fork();
368 		if (pid < 0)
369 		{
370 			goto queueonly;
371 		}
372 		else if (pid > 0)
373 		{
374 			/* be sure we leave the temp files to our child */
375 			/* can't call unlockqueue to avoid unlink of xfp */
376 			if (e->e_lockfp != NULL)
377 				(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
378 			e->e_lockfp = NULL;
379 
380 			/* close any random open files in the envelope */
381 			closexscript(e);
382 			if (e->e_dfp != NULL)
383 				(void) xfclose(e->e_dfp, "sendenvelope", e->e_df);
384 			e->e_dfp = NULL;
385 			e->e_id = e->e_df = NULL;
386 
387 			/* catch intermediate zombie */
388 			(void) waitfor(pid);
389 			return;
390 		}
391 
392 		/* double fork to avoid zombies */
393 		pid = fork();
394 		if (pid > 0)
395 			exit(EX_OK);
396 
397 		/* be sure we are immune from the terminal */
398 		disconnect(1, e);
399 
400 		/* prevent parent from waiting if there was an error */
401 		if (pid < 0)
402 		{
403 			e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
404 			finis();
405 		}
406 
407 		/*
408 		**  Close any cached connections.
409 		**
410 		**	We don't send the QUIT protocol because the parent
411 		**	still knows about the connection.
412 		**
413 		**	This should only happen when delivering an error
414 		**	message.
415 		*/
416 
417 		mci_flush(FALSE, NULL);
418 
419 # endif /* HASFLOCK */
420 
421 		break;
422 	}
423 
424 	/*
425 	**  Run through the list and send everything.
426 	**
427 	**	Set EF_GLOBALERRS so that error messages during delivery
428 	**	result in returned mail.
429 	*/
430 
431 	e->e_nsent = 0;
432 	e->e_flags |= EF_GLOBALERRS;
433 
434 	/* now run through the queue */
435 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
436 	{
437 #ifdef XDEBUG
438 		char wbuf[MAXNAME + 20];
439 
440 		(void) sprintf(wbuf, "sendall(%s)", q->q_paddr);
441 		checkfd012(wbuf);
442 #endif
443 		if (mode == SM_VERIFY)
444 		{
445 			e->e_to = q->q_paddr;
446 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
447 			{
448 				if (q->q_host != NULL && q->q_host[0] != '\0')
449 					message("deliverable: mailer %s, host %s, user %s",
450 						q->q_mailer->m_name,
451 						q->q_host,
452 						q->q_user);
453 				else
454 					message("deliverable: mailer %s, user %s",
455 						q->q_mailer->m_name,
456 						q->q_user);
457 			}
458 		}
459 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
460 		{
461 # ifdef QUEUE
462 			/*
463 			**  Checkpoint the send list every few addresses
464 			*/
465 
466 			if (e->e_nsent >= CheckpointInterval)
467 			{
468 				queueup(e, TRUE, FALSE);
469 				e->e_nsent = 0;
470 			}
471 # endif /* QUEUE */
472 			(void) deliver(e, q);
473 		}
474 	}
475 	Verbose = oldverbose;
476 
477 #ifdef XDEBUG
478 	checkfd012("end of sendenvelope");
479 #endif
480 
481 	if (mode == SM_FORK)
482 		finis();
483 }
484 /*
485 **  DOFORK -- do a fork, retrying a couple of times on failure.
486 **
487 **	This MUST be a macro, since after a vfork we are running
488 **	two processes on the same stack!!!
489 **
490 **	Parameters:
491 **		none.
492 **
493 **	Returns:
494 **		From a macro???  You've got to be kidding!
495 **
496 **	Side Effects:
497 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
498 **			pid of child in parent, zero in child.
499 **			-1 on unrecoverable error.
500 **
501 **	Notes:
502 **		I'm awfully sorry this looks so awful.  That's
503 **		vfork for you.....
504 */
505 
506 # define NFORKTRIES	5
507 
508 # ifndef FORK
509 # define FORK	fork
510 # endif
511 
512 # define DOFORK(fORKfN) \
513 {\
514 	register int i;\
515 \
516 	for (i = NFORKTRIES; --i >= 0; )\
517 	{\
518 		pid = fORKfN();\
519 		if (pid >= 0)\
520 			break;\
521 		if (i > 0)\
522 			sleep((unsigned) NFORKTRIES - i);\
523 	}\
524 }
525 /*
526 **  DOFORK -- simple fork interface to DOFORK.
527 **
528 **	Parameters:
529 **		none.
530 **
531 **	Returns:
532 **		pid of child in parent.
533 **		zero in child.
534 **		-1 on error.
535 **
536 **	Side Effects:
537 **		returns twice, once in parent and once in child.
538 */
539 
540 dofork()
541 {
542 	register int pid;
543 
544 	DOFORK(fork);
545 	return (pid);
546 }
547 /*
548 **  DELIVER -- Deliver a message to a list of addresses.
549 **
550 **	This routine delivers to everyone on the same host as the
551 **	user on the head of the list.  It is clever about mailers
552 **	that don't handle multiple users.  It is NOT guaranteed
553 **	that it will deliver to all these addresses however -- so
554 **	deliver should be called once for each address on the
555 **	list.
556 **
557 **	Parameters:
558 **		e -- the envelope to deliver.
559 **		firstto -- head of the address list to deliver to.
560 **
561 **	Returns:
562 **		zero -- successfully delivered.
563 **		else -- some failure, see ExitStat for more info.
564 **
565 **	Side Effects:
566 **		The standard input is passed off to someone.
567 */
568 
569 deliver(e, firstto)
570 	register ENVELOPE *e;
571 	ADDRESS *firstto;
572 {
573 	char *host;			/* host being sent to */
574 	char *user;			/* user being sent to */
575 	char **pvp;
576 	register char **mvp;
577 	register char *p;
578 	register MAILER *m;		/* mailer for this recipient */
579 	ADDRESS *ctladdr;
580 	register MCI *mci;
581 	register ADDRESS *to = firstto;
582 	bool clever = FALSE;		/* running user smtp to this mailer */
583 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
584 	int rcode;			/* response code */
585 	char *firstsig;			/* signature of firstto */
586 	int pid;
587 	char *curhost;
588 	int mpvect[2];
589 	int rpvect[2];
590 	char *pv[MAXPV+1];
591 	char tobuf[TOBUFSIZE];		/* text line of to people */
592 	char buf[MAXNAME];
593 	char rpathbuf[MAXNAME];		/* translated return path */
594 	extern int checkcompat();
595 
596 	errno = 0;
597 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
598 		return (0);
599 
600 #if NAMED_BIND
601 	/* unless interactive, try twice, over a minute */
602 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
603 	{
604 		_res.retrans = 30;
605 		_res.retry = 2;
606 	}
607 #endif
608 
609 	m = to->q_mailer;
610 	host = to->q_host;
611 	CurEnv = e;			/* just in case */
612 	e->e_statmsg = NULL;
613 	SmtpError[0] = '\0';
614 
615 	if (tTd(10, 1))
616 		printf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
617 			e->e_id, m->m_name, host, to->q_user);
618 	if (tTd(10, 100))
619 		printopenfds(FALSE);
620 
621 	/*
622 	**  If this mailer is expensive, and if we don't want to make
623 	**  connections now, just mark these addresses and return.
624 	**	This is useful if we want to batch connections to
625 	**	reduce load.  This will cause the messages to be
626 	**	queued up, and a daemon will come along to send the
627 	**	messages later.
628 	**		This should be on a per-mailer basis.
629 	*/
630 
631 	if (NoConnect && bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
632 	{
633 		for (; to != NULL; to = to->q_next)
634 		{
635 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
636 			    to->q_mailer != m)
637 				continue;
638 			to->q_flags |= QQUEUEUP;
639 			e->e_to = to->q_paddr;
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_CONFIG;
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 			if (e->e_lockfp != NULL)
1159 			{
1160 				fclose(e->e_lockfp);
1161 				e->e_lockfp = NULL;
1162 			}
1163 
1164 			/* child -- set up input & exec mailer */
1165 			(void) setsignal(SIGINT, SIG_IGN);
1166 			(void) setsignal(SIGHUP, SIG_IGN);
1167 			(void) setsignal(SIGTERM, SIG_DFL);
1168 
1169 			/* reset user and group */
1170 			if (!bitnset(M_RESTR, m->m_flags))
1171 			{
1172 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1173 				{
1174 					(void) initgroups(DefUser, DefGid);
1175 					(void) setgid(DefGid);
1176 					(void) setuid(DefUid);
1177 				}
1178 				else
1179 				{
1180 					(void) initgroups(ctladdr->q_ruser?
1181 						ctladdr->q_ruser: ctladdr->q_user,
1182 						ctladdr->q_gid);
1183 					(void) setgid(ctladdr->q_gid);
1184 					(void) setuid(ctladdr->q_uid);
1185 				}
1186 			}
1187 
1188 			if (tTd(11, 2))
1189 				printf("openmailer: running as r/euid=%d/%d\n",
1190 					getuid(), geteuid());
1191 
1192 			/* move into some "safe" directory */
1193 			if (m->m_execdir != NULL)
1194 			{
1195 				char *p, *q;
1196 				char buf[MAXLINE];
1197 
1198 				for (p = m->m_execdir; p != NULL; p = q)
1199 				{
1200 					q = strchr(p, ':');
1201 					if (q != NULL)
1202 						*q = '\0';
1203 					expand(p, buf, &buf[sizeof buf] - 1, e);
1204 					if (q != NULL)
1205 						*q++ = ':';
1206 					if (tTd(11, 20))
1207 						printf("openmailer: trydir %s\n",
1208 							buf);
1209 					if (buf[0] != '\0' && chdir(buf) >= 0)
1210 						break;
1211 				}
1212 			}
1213 
1214 			/* arrange to filter std & diag output of command */
1215 			if (clever)
1216 			{
1217 				(void) close(rpvect[0]);
1218 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1219 				{
1220 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1221 						e->e_to, m->m_name, rpvect[1]);
1222 					_exit(EX_OSERR);
1223 				}
1224 				(void) close(rpvect[1]);
1225 			}
1226 			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON ||
1227 				  HoldErrs || DisConnected)
1228 			{
1229 				/* put mailer output in transcript */
1230 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1231 				{
1232 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1233 						e->e_to, m->m_name,
1234 						fileno(e->e_xfp));
1235 					_exit(EX_OSERR);
1236 				}
1237 			}
1238 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1239 			{
1240 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1241 					e->e_to, m->m_name);
1242 				_exit(EX_OSERR);
1243 			}
1244 
1245 			/* arrange to get standard input */
1246 			(void) close(mpvect[1]);
1247 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1248 			{
1249 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1250 					e->e_to, m->m_name, mpvect[0]);
1251 				_exit(EX_OSERR);
1252 			}
1253 			(void) close(mpvect[0]);
1254 
1255 			/* arrange for all the files to be closed */
1256 			for (i = 3; i < DtableSize; i++)
1257 			{
1258 				register int j;
1259 
1260 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1261 					(void) fcntl(i, F_SETFD, j | 1);
1262 			}
1263 
1264 			/*
1265 			**  Set up the mailer environment
1266 			**	TZ is timezone information.
1267 			**	SYSTYPE is Apollo software sys type (required).
1268 			**	ISP is Apollo hardware system type (required).
1269 			*/
1270 
1271 			i = 0;
1272 			env[i++] = "AGENT=sendmail";
1273 			for (ep = environ; *ep != NULL; ep++)
1274 			{
1275 				if (strncmp(*ep, "TZ=", 3) == 0 ||
1276 				    strncmp(*ep, "ISP=", 4) == 0 ||
1277 				    strncmp(*ep, "SYSTYPE=", 8) == 0)
1278 					env[i++] = *ep;
1279 			}
1280 			env[i++] = NULL;
1281 
1282 			/* run disconnected from terminal */
1283 			(void) setsid();
1284 
1285 			/* try to execute the mailer */
1286 			execve(m->m_mailer, pv, env);
1287 			saveerrno = errno;
1288 			syserr("Cannot exec %s", m->m_mailer);
1289 			if (m == LocalMailer || transienterror(saveerrno))
1290 				_exit(EX_OSERR);
1291 			_exit(EX_UNAVAILABLE);
1292 		}
1293 
1294 		/*
1295 		**  Set up return value.
1296 		*/
1297 
1298 		mci = (MCI *) xalloc(sizeof *mci);
1299 		bzero((char *) mci, sizeof *mci);
1300 		mci->mci_mailer = m;
1301 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1302 		mci->mci_pid = pid;
1303 		(void) close(mpvect[0]);
1304 		mci->mci_out = fdopen(mpvect[1], "w");
1305 		if (mci->mci_out == NULL)
1306 		{
1307 			syserr("deliver: cannot create mailer output channel, fd=%d",
1308 				mpvect[1]);
1309 			(void) close(mpvect[1]);
1310 			if (clever)
1311 			{
1312 				(void) close(rpvect[0]);
1313 				(void) close(rpvect[1]);
1314 			}
1315 			rcode = EX_OSERR;
1316 			goto give_up;
1317 		}
1318 		if (clever)
1319 		{
1320 			(void) close(rpvect[1]);
1321 			mci->mci_in = fdopen(rpvect[0], "r");
1322 			if (mci->mci_in == NULL)
1323 			{
1324 				syserr("deliver: cannot create mailer input channel, fd=%d",
1325 					mpvect[1]);
1326 				(void) close(rpvect[0]);
1327 				fclose(mci->mci_out);
1328 				mci->mci_out = NULL;
1329 				rcode = EX_OSERR;
1330 				goto give_up;
1331 			}
1332 		}
1333 		else
1334 		{
1335 			mci->mci_flags |= MCIF_TEMP;
1336 			mci->mci_in = NULL;
1337 		}
1338 	}
1339 
1340 	/*
1341 	**  If we are in SMTP opening state, send initial protocol.
1342 	*/
1343 
1344 	if (clever && mci->mci_state != MCIS_CLOSED)
1345 	{
1346 		smtpinit(m, mci, e);
1347 	}
1348 	if (tTd(11, 1))
1349 	{
1350 		printf("openmailer: ");
1351 		mci_dump(mci, FALSE);
1352 	}
1353 
1354 	if (mci->mci_state != MCIS_OPEN)
1355 	{
1356 		/* couldn't open the mailer */
1357 		rcode = mci->mci_exitstat;
1358 		errno = mci->mci_errno;
1359 #if NAMED_BIND
1360 		h_errno = mci->mci_herrno;
1361 #endif
1362 		if (rcode == EX_OK)
1363 		{
1364 			/* shouldn't happen */
1365 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1366 				rcode, mci->mci_state, firstsig);
1367 			rcode = EX_SOFTWARE;
1368 		}
1369 		else if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
1370 		{
1371 			/* try next MX site */
1372 			goto tryhost;
1373 		}
1374 	}
1375 	else if (!clever)
1376 	{
1377 		/*
1378 		**  Format and send message.
1379 		*/
1380 
1381 		putfromline(mci, e);
1382 		(*e->e_puthdr)(mci, e);
1383 		putline("\n", mci);
1384 		(*e->e_putbody)(mci, e, NULL);
1385 
1386 		/* get the exit status */
1387 		rcode = endmailer(mci, e, pv);
1388 	}
1389 	else
1390 #ifdef SMTP
1391 	{
1392 		/*
1393 		**  Send the MAIL FROM: protocol
1394 		*/
1395 
1396 		rcode = smtpmailfrom(m, mci, e);
1397 		if (rcode == EX_OK)
1398 		{
1399 			register char *t = tobuf;
1400 			register int i;
1401 
1402 			/* send the recipient list */
1403 			tobuf[0] = '\0';
1404 			for (to = tochain; to != NULL; to = to->q_tchain)
1405 			{
1406 				e->e_to = to->q_paddr;
1407 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1408 				{
1409 					markfailure(e, to, i);
1410 					giveresponse(i, m, mci, ctladdr, e);
1411 				}
1412 				else
1413 				{
1414 					*t++ = ',';
1415 					for (p = to->q_paddr; *p; *t++ = *p++)
1416 						continue;
1417 					*t = '\0';
1418 				}
1419 			}
1420 
1421 			/* now send the data */
1422 			if (tobuf[0] == '\0')
1423 			{
1424 				rcode = EX_OK;
1425 				e->e_to = NULL;
1426 				if (bitset(MCIF_CACHED, mci->mci_flags))
1427 					smtprset(m, mci, e);
1428 			}
1429 			else
1430 			{
1431 				e->e_to = tobuf + 1;
1432 				rcode = smtpdata(m, mci, e);
1433 			}
1434 
1435 			/* now close the connection */
1436 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1437 				smtpquit(m, mci, e);
1438 		}
1439 		if (rcode != EX_OK && curhost != NULL && *curhost != '\0')
1440 		{
1441 			/* try next MX site */
1442 			goto tryhost;
1443 		}
1444 	}
1445 #else /* not SMTP */
1446 	{
1447 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1448 		rcode = EX_CONFIG;
1449 		goto give_up;
1450 	}
1451 #endif /* SMTP */
1452 #if NAMED_BIND
1453 	if (ConfigLevel < 2)
1454 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1455 #endif
1456 
1457 	/* arrange a return receipt if requested */
1458 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1459 	    bitnset(M_LOCALMAILER, m->m_flags))
1460 	{
1461 		e->e_flags |= EF_SENDRECEIPT;
1462 		/* do we want to send back more info? */
1463 	}
1464 
1465 	/*
1466 	**  Do final status disposal.
1467 	**	We check for something in tobuf for the SMTP case.
1468 	**	If we got a temporary failure, arrange to queue the
1469 	**		addressees.
1470 	*/
1471 
1472   give_up:
1473 	if (tobuf[0] != '\0')
1474 		giveresponse(rcode, m, mci, ctladdr, e);
1475 	for (to = tochain; to != NULL; to = to->q_tchain)
1476 	{
1477 		if (rcode != EX_OK)
1478 			markfailure(e, to, rcode);
1479 		else
1480 		{
1481 			to->q_flags |= QSENT;
1482 			e->e_nsent++;
1483 			if (e->e_receiptto != NULL &&
1484 			    bitnset(M_LOCALMAILER, m->m_flags))
1485 			{
1486 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1487 					to->q_paddr);
1488 			}
1489 		}
1490 	}
1491 
1492 	/*
1493 	**  Restore state and return.
1494 	*/
1495 
1496 #ifdef XDEBUG
1497 	{
1498 		char wbuf[MAXLINE];
1499 
1500 		/* make absolutely certain 0, 1, and 2 are in use */
1501 		sprintf(wbuf, "%s... end of deliver(%s)",
1502 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1503 			m->m_name);
1504 		checkfd012(wbuf);
1505 	}
1506 #endif
1507 
1508 	errno = 0;
1509 	define('g', (char *) NULL, e);
1510 	return (rcode);
1511 }
1512 /*
1513 **  MARKFAILURE -- mark a failure on a specific address.
1514 **
1515 **	Parameters:
1516 **		e -- the envelope we are sending.
1517 **		q -- the address to mark.
1518 **		rcode -- the code signifying the particular failure.
1519 **
1520 **	Returns:
1521 **		none.
1522 **
1523 **	Side Effects:
1524 **		marks the address (and possibly the envelope) with the
1525 **			failure so that an error will be returned or
1526 **			the message will be queued, as appropriate.
1527 */
1528 
1529 markfailure(e, q, rcode)
1530 	register ENVELOPE *e;
1531 	register ADDRESS *q;
1532 	int rcode;
1533 {
1534 	char buf[MAXLINE];
1535 
1536 	switch (rcode)
1537 	{
1538 	  case EX_OK:
1539 		break;
1540 
1541 	  case EX_TEMPFAIL:
1542 	  case EX_IOERR:
1543 	  case EX_OSERR:
1544 		q->q_flags |= QQUEUEUP;
1545 		break;
1546 
1547 	  default:
1548 		q->q_flags |= QBADADDR;
1549 		break;
1550 	}
1551 }
1552 /*
1553 **  ENDMAILER -- Wait for mailer to terminate.
1554 **
1555 **	We should never get fatal errors (e.g., segmentation
1556 **	violation), so we report those specially.  For other
1557 **	errors, we choose a status message (into statmsg),
1558 **	and if it represents an error, we print it.
1559 **
1560 **	Parameters:
1561 **		pid -- pid of mailer.
1562 **		e -- the current envelope.
1563 **		pv -- the parameter vector that invoked the mailer
1564 **			(for error messages).
1565 **
1566 **	Returns:
1567 **		exit code of mailer.
1568 **
1569 **	Side Effects:
1570 **		none.
1571 */
1572 
1573 endmailer(mci, e, pv)
1574 	register MCI *mci;
1575 	register ENVELOPE *e;
1576 	char **pv;
1577 {
1578 	int st;
1579 
1580 	/* close any connections */
1581 	if (mci->mci_in != NULL)
1582 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1583 	if (mci->mci_out != NULL)
1584 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1585 	mci->mci_in = mci->mci_out = NULL;
1586 	mci->mci_state = MCIS_CLOSED;
1587 
1588 	/* in the IPC case there is nothing to wait for */
1589 	if (mci->mci_pid == 0)
1590 		return (EX_OK);
1591 
1592 	/* wait for the mailer process to die and collect status */
1593 	st = waitfor(mci->mci_pid);
1594 	if (st == -1)
1595 	{
1596 		syserr("endmailer %s: wait", pv[0]);
1597 		return (EX_SOFTWARE);
1598 	}
1599 
1600 	if (WIFEXITED(st))
1601 	{
1602 		/* normal death -- return status */
1603 		return (WEXITSTATUS(st));
1604 	}
1605 
1606 	/* it died a horrid death */
1607 	syserr("451 mailer %s died with signal %o",
1608 		mci->mci_mailer->m_name, st);
1609 
1610 	/* log the arguments */
1611 	if (pv != NULL && e->e_xfp != NULL)
1612 	{
1613 		register char **av;
1614 
1615 		fprintf(e->e_xfp, "Arguments:");
1616 		for (av = pv; *av != NULL; av++)
1617 			fprintf(e->e_xfp, " %s", *av);
1618 		fprintf(e->e_xfp, "\n");
1619 	}
1620 
1621 	ExitStat = EX_TEMPFAIL;
1622 	return (EX_TEMPFAIL);
1623 }
1624 /*
1625 **  GIVERESPONSE -- Interpret an error response from a mailer
1626 **
1627 **	Parameters:
1628 **		stat -- the status code from the mailer (high byte
1629 **			only; core dumps must have been taken care of
1630 **			already).
1631 **		m -- the mailer info for this mailer.
1632 **		mci -- the mailer connection info -- can be NULL if the
1633 **			response is given before the connection is made.
1634 **		ctladdr -- the controlling address for the recipient
1635 **			address(es).
1636 **		e -- the current envelope.
1637 **
1638 **	Returns:
1639 **		none.
1640 **
1641 **	Side Effects:
1642 **		Errors may be incremented.
1643 **		ExitStat may be set.
1644 */
1645 
1646 giveresponse(stat, m, mci, ctladdr, e)
1647 	int stat;
1648 	register MAILER *m;
1649 	register MCI *mci;
1650 	ADDRESS *ctladdr;
1651 	ENVELOPE *e;
1652 {
1653 	register const char *statmsg;
1654 	extern char *SysExMsg[];
1655 	register int i;
1656 	extern int N_SysEx;
1657 	char buf[MAXLINE];
1658 
1659 	/*
1660 	**  Compute status message from code.
1661 	*/
1662 
1663 	i = stat - EX__BASE;
1664 	if (stat == 0)
1665 	{
1666 		statmsg = "250 Sent";
1667 		if (e->e_statmsg != NULL)
1668 		{
1669 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1670 			statmsg = buf;
1671 		}
1672 	}
1673 	else if (i < 0 || i > N_SysEx)
1674 	{
1675 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1676 		stat = EX_UNAVAILABLE;
1677 		statmsg = buf;
1678 	}
1679 	else if (stat == EX_TEMPFAIL)
1680 	{
1681 		(void) strcpy(buf, SysExMsg[i] + 1);
1682 #if NAMED_BIND
1683 		if (h_errno == TRY_AGAIN)
1684 			statmsg = errstring(h_errno+E_DNSBASE);
1685 		else
1686 #endif
1687 		{
1688 			if (errno != 0)
1689 				statmsg = errstring(errno);
1690 			else
1691 			{
1692 #ifdef SMTP
1693 				statmsg = SmtpError;
1694 #else /* SMTP */
1695 				statmsg = NULL;
1696 #endif /* SMTP */
1697 			}
1698 		}
1699 		if (statmsg != NULL && statmsg[0] != '\0')
1700 		{
1701 			(void) strcat(buf, ": ");
1702 			(void) strcat(buf, statmsg);
1703 		}
1704 		statmsg = buf;
1705 	}
1706 #if NAMED_BIND
1707 	else if (stat == EX_NOHOST && h_errno != 0)
1708 	{
1709 		statmsg = errstring(h_errno + E_DNSBASE);
1710 		(void) sprintf(buf, "%s (%s)", SysExMsg[i] + 1, statmsg);
1711 		statmsg = buf;
1712 	}
1713 #endif
1714 	else
1715 	{
1716 		statmsg = SysExMsg[i];
1717 		if (*statmsg++ == ':')
1718 		{
1719 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1720 			statmsg = buf;
1721 		}
1722 	}
1723 
1724 	/*
1725 	**  Print the message as appropriate
1726 	*/
1727 
1728 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1729 	{
1730 		extern char MsgBuf[];
1731 
1732 		message("%s", &statmsg[4]);
1733 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1734 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1735 	}
1736 	else
1737 	{
1738 		char mbuf[8];
1739 
1740 		Errors++;
1741 		sprintf(mbuf, "%.3s %%s", statmsg);
1742 		usrerr(mbuf, &statmsg[4]);
1743 	}
1744 
1745 	/*
1746 	**  Final cleanup.
1747 	**	Log a record of the transaction.  Compute the new
1748 	**	ExitStat -- if we already had an error, stick with
1749 	**	that.
1750 	*/
1751 
1752 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1753 		logdelivery(m, mci, &statmsg[4], ctladdr, e);
1754 
1755 	if (tTd(11, 2))
1756 		printf("giveresponse: stat=%d, e->e_message=%s\n",
1757 			stat, e->e_message == NULL ? "<NULL>" : e->e_message);
1758 
1759 	if (stat != EX_TEMPFAIL)
1760 		setstat(stat);
1761 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1762 	{
1763 		if (e->e_message != NULL)
1764 			free(e->e_message);
1765 		e->e_message = newstr(&statmsg[4]);
1766 	}
1767 	errno = 0;
1768 #if NAMED_BIND
1769 	h_errno = 0;
1770 #endif
1771 }
1772 /*
1773 **  LOGDELIVERY -- log the delivery in the system log
1774 **
1775 **	Care is taken to avoid logging lines that are too long, because
1776 **	some versions of syslog have an unfortunate proclivity for core
1777 **	dumping.  This is a hack, to be sure, that is at best empirical.
1778 **
1779 **	Parameters:
1780 **		m -- the mailer info.  Can be NULL for initial queue.
1781 **		mci -- the mailer connection info -- can be NULL if the
1782 **			log is occuring when no connection is active.
1783 **		stat -- the message to print for the status.
1784 **		ctladdr -- the controlling address for the to list.
1785 **		e -- the current envelope.
1786 **
1787 **	Returns:
1788 **		none
1789 **
1790 **	Side Effects:
1791 **		none
1792 */
1793 
1794 logdelivery(m, mci, stat, ctladdr, e)
1795 	MAILER *m;
1796 	register MCI *mci;
1797 	char *stat;
1798 	ADDRESS *ctladdr;
1799 	register ENVELOPE *e;
1800 {
1801 # ifdef LOG
1802 	register char *bp;
1803 	register char *p;
1804 	int l;
1805 	char buf[512];
1806 
1807 #  if (SYSLOG_BUFSIZE) >= 256
1808 	bp = buf;
1809 	if (ctladdr != NULL)
1810 	{
1811 		strcpy(bp, ", ctladdr=");
1812 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
1813 		bp += strlen(bp);
1814 		if (bitset(QGOODUID, ctladdr->q_flags))
1815 		{
1816 			(void) sprintf(bp, " (%d/%d)",
1817 					ctladdr->q_uid, ctladdr->q_gid);
1818 			bp += strlen(bp);
1819 		}
1820 	}
1821 
1822 	(void) sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1823 	bp += strlen(bp);
1824 
1825 	if (m != NULL)
1826 	{
1827 		(void) strcpy(bp, ", mailer=");
1828 		(void) strcat(bp, m->m_name);
1829 		bp += strlen(bp);
1830 	}
1831 
1832 	if (mci != NULL && mci->mci_host != NULL)
1833 	{
1834 # ifdef DAEMON
1835 		extern SOCKADDR CurHostAddr;
1836 # endif
1837 
1838 		(void) strcpy(bp, ", relay=");
1839 		(void) strcat(bp, mci->mci_host);
1840 
1841 # ifdef DAEMON
1842 		(void) strcat(bp, " [");
1843 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1844 		(void) strcat(bp, "]");
1845 # endif
1846 	}
1847 	else if (strcmp(stat, "queued") != 0)
1848 	{
1849 		char *p = macvalue('h', e);
1850 
1851 		if (p != NULL && p[0] != '\0')
1852 		{
1853 			(void) strcpy(bp, ", relay=");
1854 			(void) strcat(bp, p);
1855 		}
1856 	}
1857 	bp += strlen(bp);
1858 
1859 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
1860 #if (STATLEN) < 63
1861 # undef STATLEN
1862 # define STATLEN	63
1863 #endif
1864 #if (STATLEN) > 203
1865 # undef STATLEN
1866 # define STATLEN	203
1867 #endif
1868 
1869 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
1870 	{
1871 		/* desperation move -- truncate data */
1872 		bp = buf + sizeof buf - ((STATLEN) + 17);
1873 		strcpy(bp, "...");
1874 		bp += 3;
1875 	}
1876 
1877 	(void) strcpy(bp, ", stat=");
1878 	bp += strlen(bp);
1879 
1880 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
1881 
1882 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
1883 	p = e->e_to;
1884 	while (strlen(p) >= l)
1885 	{
1886 		register char *q = strchr(p + l, ',');
1887 
1888 		if (q == NULL)
1889 			break;
1890 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
1891 			e->e_id, ++q - p, p, buf);
1892 		p = q;
1893 	}
1894 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
1895 
1896 #  else		/* we have a very short log buffer size */
1897 
1898 	l = SYSLOG_BUFSIZE - 85;
1899 	p = e->e_to;
1900 	while (strlen(p) >= l)
1901 	{
1902 		register char *q = strchr(p + l, ',');
1903 
1904 		if (q == NULL)
1905 			break;
1906 		syslog(LOG_INFO, "%s: to=%.*s [more]",
1907 			e->e_id, ++q - p, p);
1908 		p = q;
1909 	}
1910 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
1911 
1912 	if (ctladdr != NULL)
1913 	{
1914 		bp = buf;
1915 		strcpy(buf, "ctladdr=");
1916 		bp += strlen(buf);
1917 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
1918 		bp += strlen(buf);
1919 		if (bitset(QGOODUID, ctladdr->q_flags))
1920 		{
1921 			(void) sprintf(bp, " (%d/%d)",
1922 					ctladdr->q_uid, ctladdr->q_gid);
1923 			bp += strlen(bp);
1924 		}
1925 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1926 	}
1927 	bp = buf;
1928 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1929 	bp += strlen(bp);
1930 
1931 	if (m != NULL)
1932 	{
1933 		sprintf(bp, ", mailer=%s", m->m_name);
1934 		bp += strlen(bp);
1935 	}
1936 	syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1937 
1938 	buf[0] = '\0';
1939 	if (mci != NULL && mci->mci_host != NULL)
1940 	{
1941 # ifdef DAEMON
1942 		extern SOCKADDR CurHostAddr;
1943 # endif
1944 
1945 		sprintf(buf, "relay=%s", mci->mci_host);
1946 
1947 # ifdef DAEMON
1948 		(void) strcat(buf, " [");
1949 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
1950 		(void) strcat(buf, "]");
1951 # endif
1952 	}
1953 	else if (strcmp(stat, "queued") != 0)
1954 	{
1955 		char *p = macvalue('h', e);
1956 
1957 		if (p != NULL && p[0] != '\0')
1958 			sprintf(buf, "relay=%s", p);
1959 	}
1960 	if (buf[0] != '\0')
1961 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1962 
1963 	syslog(LOG_INFO, "%s: stat=%s", e->e_id, shortenstring(stat, 63));
1964 #  endif /* short log buffer */
1965 # endif /* LOG */
1966 }
1967 /*
1968 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1969 **
1970 **	This can be made an arbitrary message separator by changing $l
1971 **
1972 **	One of the ugliest hacks seen by human eyes is contained herein:
1973 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1974 **	does a well-meaning programmer such as myself have to deal with
1975 **	this kind of antique garbage????
1976 **
1977 **	Parameters:
1978 **		mci -- the connection information.
1979 **		e -- the envelope.
1980 **
1981 **	Returns:
1982 **		none
1983 **
1984 **	Side Effects:
1985 **		outputs some text to fp.
1986 */
1987 
1988 putfromline(mci, e)
1989 	register MCI *mci;
1990 	ENVELOPE *e;
1991 {
1992 	char *template = "\201l\n";
1993 	char buf[MAXLINE];
1994 
1995 	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
1996 		return;
1997 
1998 # ifdef UGLYUUCP
1999 	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
2000 	{
2001 		char *bang;
2002 		char xbuf[MAXLINE];
2003 
2004 		expand("\201g", buf, &buf[sizeof buf - 1], e);
2005 		bang = strchr(buf, '!');
2006 		if (bang == NULL)
2007 		{
2008 			errno = 0;
2009 			syserr("554 No ! in UUCP From address! (%s given)", buf);
2010 		}
2011 		else
2012 		{
2013 			*bang++ = '\0';
2014 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
2015 			template = xbuf;
2016 		}
2017 	}
2018 # endif /* UGLYUUCP */
2019 	expand(template, buf, &buf[sizeof buf - 1], e);
2020 	putline(buf, mci);
2021 }
2022 /*
2023 **  PUTBODY -- put the body of a message.
2024 **
2025 **	Parameters:
2026 **		mci -- the connection information.
2027 **		e -- the envelope to put out.
2028 **		separator -- if non-NULL, a message separator that must
2029 **			not be permitted in the resulting message.
2030 **
2031 **	Returns:
2032 **		none.
2033 **
2034 **	Side Effects:
2035 **		The message is written onto fp.
2036 */
2037 
2038 putbody(mci, e, separator)
2039 	register MCI *mci;
2040 	register ENVELOPE *e;
2041 	char *separator;
2042 {
2043 	char buf[MAXLINE];
2044 
2045 	/*
2046 	**  Output the body of the message
2047 	*/
2048 
2049 	if (e->e_dfp == NULL)
2050 	{
2051 		if (e->e_df != NULL)
2052 		{
2053 			e->e_dfp = fopen(e->e_df, "r");
2054 			if (e->e_dfp == NULL)
2055 				syserr("putbody: Cannot open %s for %s from %s",
2056 				e->e_df, e->e_to, e->e_from.q_paddr);
2057 		}
2058 		else
2059 			putline("<<< No Message Collected >>>", mci);
2060 	}
2061 	if (e->e_dfp != NULL)
2062 	{
2063 		rewind(e->e_dfp);
2064 		while (!ferror(mci->mci_out) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
2065 		{
2066 			if (buf[0] == 'F' &&
2067 			    bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
2068 			    strncmp(buf, "From ", 5) == 0)
2069 				(void) putc('>', mci->mci_out);
2070 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
2071 			{
2072 				/* possible separator */
2073 				int sl = strlen(separator);
2074 
2075 				if (strncmp(&buf[2], separator, sl) == 0)
2076 					(void) putc(' ', mci->mci_out);
2077 			}
2078 			putline(buf, mci);
2079 		}
2080 
2081 		if (ferror(e->e_dfp))
2082 		{
2083 			syserr("putbody: %s: read error", e->e_df);
2084 			ExitStat = EX_IOERR;
2085 		}
2086 	}
2087 
2088 	/* some mailers want extra blank line at end of message */
2089 	if (bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
2090 	    buf[0] != '\0' && buf[0] != '\n')
2091 		putline("", mci);
2092 
2093 	(void) fflush(mci->mci_out);
2094 	if (ferror(mci->mci_out) && errno != EPIPE)
2095 	{
2096 		syserr("putbody: write error");
2097 		ExitStat = EX_IOERR;
2098 	}
2099 	errno = 0;
2100 }
2101 /*
2102 **  MAILFILE -- Send a message to a file.
2103 **
2104 **	If the file has the setuid/setgid bits set, but NO execute
2105 **	bits, sendmail will try to become the owner of that file
2106 **	rather than the real user.  Obviously, this only works if
2107 **	sendmail runs as root.
2108 **
2109 **	This could be done as a subordinate mailer, except that it
2110 **	is used implicitly to save messages in ~/dead.letter.  We
2111 **	view this as being sufficiently important as to include it
2112 **	here.  For example, if the system is dying, we shouldn't have
2113 **	to create another process plus some pipes to save the message.
2114 **
2115 **	Parameters:
2116 **		filename -- the name of the file to send to.
2117 **		ctladdr -- the controlling address header -- includes
2118 **			the userid/groupid to be when sending.
2119 **
2120 **	Returns:
2121 **		The exit code associated with the operation.
2122 **
2123 **	Side Effects:
2124 **		none.
2125 */
2126 
2127 mailfile(filename, ctladdr, e)
2128 	char *filename;
2129 	ADDRESS *ctladdr;
2130 	register ENVELOPE *e;
2131 {
2132 	register FILE *f;
2133 	register int pid;
2134 	int mode;
2135 
2136 	if (tTd(11, 1))
2137 	{
2138 		printf("mailfile %s\n  ctladdr=", filename);
2139 		printaddr(ctladdr, FALSE);
2140 	}
2141 
2142 	if (e->e_xfp != NULL)
2143 		fflush(e->e_xfp);
2144 
2145 	/*
2146 	**  Fork so we can change permissions here.
2147 	**	Note that we MUST use fork, not vfork, because of
2148 	**	the complications of calling subroutines, etc.
2149 	*/
2150 
2151 	DOFORK(fork);
2152 
2153 	if (pid < 0)
2154 		return (EX_OSERR);
2155 	else if (pid == 0)
2156 	{
2157 		/* child -- actually write to file */
2158 		struct stat stb;
2159 		struct stat fsb;
2160 		MCI mcibuf;
2161 		int oflags = O_WRONLY|O_APPEND;
2162 
2163 		if (e->e_lockfp != NULL)
2164 		{
2165 			fclose(e->e_lockfp);
2166 			e->e_lockfp = NULL;
2167 		}
2168 
2169 		(void) setsignal(SIGINT, SIG_DFL);
2170 		(void) setsignal(SIGHUP, SIG_DFL);
2171 		(void) setsignal(SIGTERM, SIG_DFL);
2172 		(void) umask(OldUmask);
2173 
2174 		if (stat(filename, &stb) < 0)
2175 		{
2176 			stb.st_mode = FileMode;
2177 			oflags |= O_CREAT|O_EXCL;
2178 		}
2179 		else if (bitset(0111, stb.st_mode))
2180 			exit(EX_CANTCREAT);
2181 		mode = stb.st_mode;
2182 
2183 		/* limit the errors to those actually caused in the child */
2184 		errno = 0;
2185 		ExitStat = EX_OK;
2186 
2187 		if (ctladdr != NULL)
2188 		{
2189 			/* ignore setuid and setgid bits */
2190 			mode &= ~(S_ISGID|S_ISUID);
2191 		}
2192 
2193 		/* we have to open the dfile BEFORE setuid */
2194 		if (e->e_dfp == NULL && e->e_df != NULL)
2195 		{
2196 			e->e_dfp = fopen(e->e_df, "r");
2197 			if (e->e_dfp == NULL)
2198 			{
2199 				syserr("mailfile: Cannot open %s for %s from %s",
2200 					e->e_df, e->e_to, e->e_from.q_paddr);
2201 			}
2202 		}
2203 
2204 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
2205 		{
2206 			if (ctladdr == NULL || ctladdr->q_uid == 0)
2207 			{
2208 				(void) initgroups(DefUser, DefGid);
2209 			}
2210 			else
2211 			{
2212 				(void) initgroups(ctladdr->q_ruser ?
2213 					ctladdr->q_ruser : ctladdr->q_user,
2214 					ctladdr->q_gid);
2215 			}
2216 		}
2217 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
2218 		{
2219 			if (ctladdr == NULL || ctladdr->q_uid == 0)
2220 				(void) setuid(DefUid);
2221 			else
2222 				(void) setuid(ctladdr->q_uid);
2223 		}
2224 		FileName = filename;
2225 		LineNumber = 0;
2226 		f = dfopen(filename, oflags, FileMode);
2227 		if (f == NULL)
2228 		{
2229 			message("554 cannot open: %s", errstring(errno));
2230 			exit(EX_CANTCREAT);
2231 		}
2232 		if (fstat(fileno(f), &fsb) < 0 ||
2233 		    !bitset(O_CREAT, oflags) &&
2234 		     (stb.st_nlink != fsb.st_nlink ||
2235 		      stb.st_dev != fsb.st_dev ||
2236 		      stb.st_ino != fsb.st_ino ||
2237 		      stb.st_uid != fsb.st_uid))
2238 		{
2239 			message("554 cannot write: file changed after open");
2240 			exit(EX_CANTCREAT);
2241 		}
2242 
2243 		bzero(&mcibuf, sizeof mcibuf);
2244 		mcibuf.mci_mailer = FileMailer;
2245 		mcibuf.mci_out = f;
2246 		if (bitnset(M_7BITS, FileMailer->m_flags))
2247 			mcibuf.mci_flags |= MCIF_7BIT;
2248 
2249 		putfromline(&mcibuf, e);
2250 		(*e->e_puthdr)(&mcibuf, e);
2251 		putline("\n", &mcibuf);
2252 		(*e->e_putbody)(&mcibuf, e, NULL);
2253 		putline("\n", &mcibuf);
2254 		if (ferror(f))
2255 		{
2256 			message("451 I/O error: %s", errstring(errno));
2257 			setstat(EX_IOERR);
2258 		}
2259 		(void) xfclose(f, "mailfile", filename);
2260 		(void) fflush(stdout);
2261 
2262 		/* reset ISUID & ISGID bits for paranoid systems */
2263 		(void) chmod(filename, (int) stb.st_mode);
2264 		exit(ExitStat);
2265 		/*NOTREACHED*/
2266 	}
2267 	else
2268 	{
2269 		/* parent -- wait for exit status */
2270 		int st;
2271 
2272 		st = waitfor(pid);
2273 		if (WIFEXITED(st))
2274 			return (WEXITSTATUS(st));
2275 		else
2276 		{
2277 			syserr("child died on signal %d", st);
2278 			return (EX_UNAVAILABLE);
2279 		}
2280 		/*NOTREACHED*/
2281 	}
2282 }
2283 /*
2284 **  HOSTSIGNATURE -- return the "signature" for a host.
2285 **
2286 **	The signature describes how we are going to send this -- it
2287 **	can be just the hostname (for non-Internet hosts) or can be
2288 **	an ordered list of MX hosts.
2289 **
2290 **	Parameters:
2291 **		m -- the mailer describing this host.
2292 **		host -- the host name.
2293 **		e -- the current envelope.
2294 **
2295 **	Returns:
2296 **		The signature for this host.
2297 **
2298 **	Side Effects:
2299 **		Can tweak the symbol table.
2300 */
2301 
2302 char *
2303 hostsignature(m, host, e)
2304 	register MAILER *m;
2305 	char *host;
2306 	ENVELOPE *e;
2307 {
2308 	register char *p;
2309 	register STAB *s;
2310 	int i;
2311 	int len;
2312 #if NAMED_BIND
2313 	int nmx;
2314 	auto int rcode;
2315 	char *hp;
2316 	char *endp;
2317 	int oldoptions;
2318 	char *mxhosts[MAXMXHOSTS + 1];
2319 #endif
2320 
2321 	/*
2322 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2323 	*/
2324 
2325 	p = m->m_mailer;
2326 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2327 	{
2328 		/* just an ordinary mailer */
2329 		return host;
2330 	}
2331 
2332 	/*
2333 	**  Look it up in the symbol table.
2334 	*/
2335 
2336 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2337 	if (s->s_hostsig != NULL)
2338 		return s->s_hostsig;
2339 
2340 	/*
2341 	**  Not already there -- create a signature.
2342 	*/
2343 
2344 #if NAMED_BIND
2345 	if (ConfigLevel < 2)
2346 	{
2347 		oldoptions = _res.options;
2348 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2349 	}
2350 
2351 	for (hp = host; hp != NULL; hp = endp)
2352 	{
2353 		endp = strchr(hp, ':');
2354 		if (endp != NULL)
2355 			*endp = '\0';
2356 
2357 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2358 
2359 		if (nmx <= 0)
2360 		{
2361 			register MCI *mci;
2362 
2363 			/* update the connection info for this host */
2364 			mci = mci_get(hp, m);
2365 			mci->mci_exitstat = rcode;
2366 			mci->mci_errno = errno;
2367 #if NAMED_BIND
2368 			mci->mci_herrno = h_errno;
2369 #endif
2370 
2371 			/* and return the original host name as the signature */
2372 			nmx = 1;
2373 			mxhosts[0] = hp;
2374 		}
2375 
2376 		len = 0;
2377 		for (i = 0; i < nmx; i++)
2378 		{
2379 			len += strlen(mxhosts[i]) + 1;
2380 		}
2381 		if (s->s_hostsig != NULL)
2382 			len += strlen(s->s_hostsig) + 1;
2383 		p = xalloc(len);
2384 		if (s->s_hostsig != NULL)
2385 		{
2386 			(void) strcpy(p, s->s_hostsig);
2387 			free(s->s_hostsig);
2388 			s->s_hostsig = p;
2389 			p += strlen(p);
2390 			*p++ = ':';
2391 		}
2392 		else
2393 			s->s_hostsig = p;
2394 		for (i = 0; i < nmx; i++)
2395 		{
2396 			if (i != 0)
2397 				*p++ = ':';
2398 			strcpy(p, mxhosts[i]);
2399 			p += strlen(p);
2400 		}
2401 		if (endp != NULL)
2402 			*endp++ = ':';
2403 	}
2404 	makelower(s->s_hostsig);
2405 	if (ConfigLevel < 2)
2406 		_res.options = oldoptions;
2407 #else
2408 	/* not using BIND -- the signature is just the host name */
2409 	s->s_hostsig = host;
2410 #endif
2411 	if (tTd(17, 1))
2412 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2413 	return s->s_hostsig;
2414 }
2415