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