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