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