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