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.67 (Berkeley) 02/05/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 
242 			if (mode != SM_VERIFY)
243 				openxscript(ee);
244 #ifdef LOG
245 			if (LogLevel > 4)
246 				syslog(LOG_INFO, "%s: clone %s",
247 					ee->e_id, e->e_id);
248 #endif
249 		}
250 	}
251 
252 	if (owner != NULL)
253 	{
254 		setsender(owner, e, NULL, TRUE);
255 		if (tTd(13, 5))
256 		{
257 			printf("sendall(owner): QDONTSEND ");
258 			printaddr(&e->e_from, FALSE);
259 		}
260 		e->e_from.q_flags |= QDONTSEND;
261 		e->e_errormode = EM_MAIL;
262 	}
263 
264 # ifdef QUEUE
265 	if ((mode == SM_QUEUE || mode == SM_FORK ||
266 	     (mode != SM_VERIFY && SuperSafe)) &&
267 	    !bitset(EF_INQUEUE, e->e_flags))
268 	{
269 		/* be sure everything is instantiated in the queue */
270 		queueup(e, TRUE, announcequeueup);
271 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
272 			queueup(ee, TRUE, announcequeueup);
273 	}
274 #endif /* QUEUE */
275 
276 	if (splitenv != NULL)
277 	{
278 		if (tTd(13, 1))
279 		{
280 			printf("\nsendall: Split queue; remaining queue:\n");
281 			printaddr(e->e_sendqueue, TRUE);
282 		}
283 
284 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
285 		{
286 			CurEnv = ee;
287 			sendenvelope(ee, mode);
288 		}
289 
290 		CurEnv = e;
291 	}
292 	sendenvelope(e, mode);
293 
294 	for (; splitenv != NULL; splitenv = splitenv->e_sibling)
295 		dropenvelope(splitenv);
296 }
297 
298 sendenvelope(e, mode)
299 	register ENVELOPE *e;
300 	char mode;
301 {
302 	bool oldverbose;
303 	int pid;
304 	register ADDRESS *q;
305 	char *qf;
306 	char *id;
307 
308 	/*
309 	**  If we have had global, fatal errors, don't bother sending
310 	**  the message at all if we are in SMTP mode.  Local errors
311 	**  (e.g., a single address failing) will still cause the other
312 	**  addresses to be sent.
313 	*/
314 
315 	if (bitset(EF_FATALERRS, e->e_flags) &&
316 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
317 	{
318 		e->e_flags |= EF_CLRQUEUE;
319 		return;
320 	}
321 
322 	oldverbose = Verbose;
323 	switch (mode)
324 	{
325 	  case SM_VERIFY:
326 		Verbose = TRUE;
327 		break;
328 
329 	  case SM_QUEUE:
330   queueonly:
331 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
332 		return;
333 
334 	  case SM_FORK:
335 		if (e->e_xfp != NULL)
336 			(void) fflush(e->e_xfp);
337 
338 # if !HASFLOCK
339 		/*
340 		**  Since fcntl locking has the interesting semantic that
341 		**  the lock is owned by a process, not by an open file
342 		**  descriptor, we have to flush this to the queue, and
343 		**  then restart from scratch in the child.
344 		*/
345 
346 		/* save id for future use */
347 		id = e->e_id;
348 
349 		/* now drop the envelope in the parent */
350 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
351 		dropenvelope(e);
352 
353 		/* and reacquire in the child */
354 		(void) dowork(id, TRUE, FALSE, e);
355 
356 		return;
357 
358 # else /* HASFLOCK */
359 
360 		pid = fork();
361 		if (pid < 0)
362 		{
363 			goto queueonly;
364 		}
365 		else if (pid > 0)
366 		{
367 			/* be sure we leave the temp files to our child */
368 			/* can't call unlockqueue to avoid unlink of xfp */
369 			if (e->e_lockfp != NULL)
370 				(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
371 			e->e_lockfp = NULL;
372 
373 			/* close any random open files in the envelope */
374 			closexscript(e);
375 			if (e->e_dfp != NULL)
376 				(void) xfclose(e->e_dfp, "sendenvelope", e->e_df);
377 			e->e_dfp = NULL;
378 			e->e_id = e->e_df = NULL;
379 			return;
380 		}
381 
382 		/* double fork to avoid zombies */
383 		if (fork() > 0)
384 			exit(EX_OK);
385 
386 		/* be sure we are immune from the terminal */
387 		disconnect(1, e);
388 
389 		/*
390 		**  Close any cached connections.
391 		**
392 		**	We don't send the QUIT protocol because the parent
393 		**	still knows about the connection.
394 		**
395 		**	This should only happen when delivering an error
396 		**	message.
397 		*/
398 
399 		mci_flush(FALSE, NULL);
400 
401 # endif /* HASFLOCK */
402 
403 		break;
404 	}
405 
406 	/*
407 	**  Run through the list and send everything.
408 	**
409 	**	Set EF_GLOBALERRS so that error messages during delivery
410 	**	result in returned mail.
411 	*/
412 
413 	e->e_nsent = 0;
414 	e->e_flags |= EF_GLOBALERRS;
415 
416 	/* now run through the queue */
417 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
418 	{
419 #ifdef XDEBUG
420 		char wbuf[MAXNAME + 20];
421 
422 		(void) sprintf(wbuf, "sendall(%s)", q->q_paddr);
423 		checkfd012(wbuf);
424 #endif
425 		if (mode == SM_VERIFY)
426 		{
427 			e->e_to = q->q_paddr;
428 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
429 			{
430 				if (q->q_host != NULL && q->q_host[0] != '\0')
431 					message("deliverable: mailer %s, host %s, user %s",
432 						q->q_mailer->m_name,
433 						q->q_host,
434 						q->q_user);
435 				else
436 					message("deliverable: mailer %s, user %s",
437 						q->q_mailer->m_name,
438 						q->q_user);
439 			}
440 		}
441 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
442 		{
443 # ifdef QUEUE
444 			/*
445 			**  Checkpoint the send list every few addresses
446 			*/
447 
448 			if (e->e_nsent >= CheckpointInterval)
449 			{
450 				queueup(e, TRUE, FALSE);
451 				e->e_nsent = 0;
452 			}
453 # endif /* QUEUE */
454 			(void) deliver(e, q);
455 		}
456 	}
457 	Verbose = oldverbose;
458 
459 #ifdef XDEBUG
460 	checkfd012("end of sendenvelope");
461 #endif
462 
463 	if (mode == SM_FORK)
464 		finis();
465 }
466 /*
467 **  DOFORK -- do a fork, retrying a couple of times on failure.
468 **
469 **	This MUST be a macro, since after a vfork we are running
470 **	two processes on the same stack!!!
471 **
472 **	Parameters:
473 **		none.
474 **
475 **	Returns:
476 **		From a macro???  You've got to be kidding!
477 **
478 **	Side Effects:
479 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
480 **			pid of child in parent, zero in child.
481 **			-1 on unrecoverable error.
482 **
483 **	Notes:
484 **		I'm awfully sorry this looks so awful.  That's
485 **		vfork for you.....
486 */
487 
488 # define NFORKTRIES	5
489 
490 # ifndef FORK
491 # define FORK	fork
492 # endif
493 
494 # define DOFORK(fORKfN) \
495 {\
496 	register int i;\
497 \
498 	for (i = NFORKTRIES; --i >= 0; )\
499 	{\
500 		pid = fORKfN();\
501 		if (pid >= 0)\
502 			break;\
503 		if (i > 0)\
504 			sleep((unsigned) NFORKTRIES - i);\
505 	}\
506 }
507 /*
508 **  DOFORK -- simple fork interface to DOFORK.
509 **
510 **	Parameters:
511 **		none.
512 **
513 **	Returns:
514 **		pid of child in parent.
515 **		zero in child.
516 **		-1 on error.
517 **
518 **	Side Effects:
519 **		returns twice, once in parent and once in child.
520 */
521 
522 dofork()
523 {
524 	register int pid;
525 
526 	DOFORK(fork);
527 	return (pid);
528 }
529 /*
530 **  DELIVER -- Deliver a message to a list of addresses.
531 **
532 **	This routine delivers to everyone on the same host as the
533 **	user on the head of the list.  It is clever about mailers
534 **	that don't handle multiple users.  It is NOT guaranteed
535 **	that it will deliver to all these addresses however -- so
536 **	deliver should be called once for each address on the
537 **	list.
538 **
539 **	Parameters:
540 **		e -- the envelope to deliver.
541 **		firstto -- head of the address list to deliver to.
542 **
543 **	Returns:
544 **		zero -- successfully delivered.
545 **		else -- some failure, see ExitStat for more info.
546 **
547 **	Side Effects:
548 **		The standard input is passed off to someone.
549 */
550 
551 deliver(e, firstto)
552 	register ENVELOPE *e;
553 	ADDRESS *firstto;
554 {
555 	char *host;			/* host being sent to */
556 	char *user;			/* user being sent to */
557 	char **pvp;
558 	register char **mvp;
559 	register char *p;
560 	register MAILER *m;		/* mailer for this recipient */
561 	ADDRESS *ctladdr;
562 	register MCI *mci;
563 	register ADDRESS *to = firstto;
564 	bool clever = FALSE;		/* running user smtp to this mailer */
565 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
566 	int rcode;			/* response code */
567 	char *firstsig;			/* signature of firstto */
568 	int pid;
569 	char *curhost;
570 	int mpvect[2];
571 	int rpvect[2];
572 	char *pv[MAXPV+1];
573 	char tobuf[TOBUFSIZE];		/* text line of to people */
574 	char buf[MAXNAME];
575 	char rpathbuf[MAXNAME];		/* translated return path */
576 	extern int checkcompat();
577 
578 	errno = 0;
579 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
580 		return (0);
581 
582 #ifdef NAMED_BIND
583 	/* unless interactive, try twice, over a minute */
584 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
585 	{
586 		_res.retrans = 30;
587 		_res.retry = 2;
588 	}
589 #endif
590 
591 	m = to->q_mailer;
592 	host = to->q_host;
593 	CurEnv = e;			/* just in case */
594 	e->e_statmsg = NULL;
595 	SmtpError[0] = '\0';
596 
597 	if (tTd(10, 1))
598 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
599 			m->m_mno, host, to->q_user);
600 	if (tTd(10, 100))
601 		printopenfds(FALSE);
602 
603 	/*
604 	**  If this mailer is expensive, and if we don't want to make
605 	**  connections now, just mark these addresses and return.
606 	**	This is useful if we want to batch connections to
607 	**	reduce load.  This will cause the messages to be
608 	**	queued up, and a daemon will come along to send the
609 	**	messages later.
610 	**		This should be on a per-mailer basis.
611 	*/
612 
613 	if (NoConnect && bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
614 	{
615 		for (; to != NULL; to = to->q_next)
616 		{
617 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
618 			    to->q_mailer != m)
619 				continue;
620 			to->q_flags |= QQUEUEUP;
621 			e->e_to = to->q_paddr;
622 			message("queued");
623 			if (LogLevel > 8)
624 				logdelivery(m, NULL, "queued", NULL, e);
625 		}
626 		e->e_to = NULL;
627 		return (0);
628 	}
629 
630 	/*
631 	**  Do initial argv setup.
632 	**	Insert the mailer name.  Notice that $x expansion is
633 	**	NOT done on the mailer name.  Then, if the mailer has
634 	**	a picky -f flag, we insert it as appropriate.  This
635 	**	code does not check for 'pv' overflow; this places a
636 	**	manifest lower limit of 4 for MAXPV.
637 	**		The from address rewrite is expected to make
638 	**		the address relative to the other end.
639 	*/
640 
641 	/* rewrite from address, using rewriting rules */
642 	rcode = EX_OK;
643 	(void) strcpy(rpathbuf, remotename(e->e_from.q_paddr, m,
644 					   RF_SENDERADDR|RF_CANONICAL,
645 					   &rcode, e));
646 	define('g', rpathbuf, e);		/* translated return path */
647 	define('h', host, e);			/* to host */
648 	Errors = 0;
649 	pvp = pv;
650 	*pvp++ = m->m_argv[0];
651 
652 	/* insert -f or -r flag as appropriate */
653 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
654 	{
655 		if (bitnset(M_FOPT, m->m_flags))
656 			*pvp++ = "-f";
657 		else
658 			*pvp++ = "-r";
659 		*pvp++ = newstr(rpathbuf);
660 	}
661 
662 	/*
663 	**  Append the other fixed parts of the argv.  These run
664 	**  up to the first entry containing "$u".  There can only
665 	**  be one of these, and there are only a few more slots
666 	**  in the pv after it.
667 	*/
668 
669 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
670 	{
671 		/* can't use strchr here because of sign extension problems */
672 		while (*p != '\0')
673 		{
674 			if ((*p++ & 0377) == MACROEXPAND)
675 			{
676 				if (*p == 'u')
677 					break;
678 			}
679 		}
680 
681 		if (*p != '\0')
682 			break;
683 
684 		/* this entry is safe -- go ahead and process it */
685 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
686 		*pvp++ = newstr(buf);
687 		if (pvp >= &pv[MAXPV - 3])
688 		{
689 			syserr("554 Too many parameters to %s before $u", pv[0]);
690 			return (-1);
691 		}
692 	}
693 
694 	/*
695 	**  If we have no substitution for the user name in the argument
696 	**  list, we know that we must supply the names otherwise -- and
697 	**  SMTP is the answer!!
698 	*/
699 
700 	if (*mvp == NULL)
701 	{
702 		/* running SMTP */
703 # ifdef SMTP
704 		clever = TRUE;
705 		*pvp = NULL;
706 # else /* SMTP */
707 		/* oops!  we don't implement SMTP */
708 		syserr("554 SMTP style mailer not implemented");
709 		return (EX_SOFTWARE);
710 # endif /* SMTP */
711 	}
712 
713 	/*
714 	**  At this point *mvp points to the argument with $u.  We
715 	**  run through our address list and append all the addresses
716 	**  we can.  If we run out of space, do not fret!  We can
717 	**  always send another copy later.
718 	*/
719 
720 	tobuf[0] = '\0';
721 	e->e_to = tobuf;
722 	ctladdr = NULL;
723 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
724 	for (; to != NULL; to = to->q_next)
725 	{
726 		/* avoid sending multiple recipients to dumb mailers */
727 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
728 			break;
729 
730 		/* if already sent or not for this host, don't send */
731 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
732 		    to->q_mailer != firstto->q_mailer ||
733 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
734 			continue;
735 
736 		/* avoid overflowing tobuf */
737 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
738 			break;
739 
740 		if (tTd(10, 1))
741 		{
742 			printf("\nsend to ");
743 			printaddr(to, FALSE);
744 		}
745 
746 		/* compute effective uid/gid when sending */
747 		/* XXX perhaps this should be to->q_mailer != LocalMailer ?? */
748 		/* XXX perhaps it should be a mailer flag? */
749 		if (to->q_mailer == ProgMailer || to->q_mailer == FileMailer)
750 			ctladdr = getctladdr(to);
751 
752 		user = to->q_user;
753 		e->e_to = to->q_paddr;
754 		if (tTd(10, 5))
755 		{
756 			printf("deliver: QDONTSEND ");
757 			printaddr(to, FALSE);
758 		}
759 		to->q_flags |= QDONTSEND;
760 
761 		/*
762 		**  Check to see that these people are allowed to
763 		**  talk to each other.
764 		*/
765 
766 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
767 		{
768 			NoReturn = TRUE;
769 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
770 			giveresponse(EX_UNAVAILABLE, m, NULL, ctladdr, e);
771 			continue;
772 		}
773 		rcode = checkcompat(to, e);
774 		if (rcode != EX_OK)
775 		{
776 			markfailure(e, to, rcode);
777 			giveresponse(rcode, m, NULL, ctladdr, e);
778 			continue;
779 		}
780 
781 		/*
782 		**  Strip quote bits from names if the mailer is dumb
783 		**	about them.
784 		*/
785 
786 		if (bitnset(M_STRIPQ, m->m_flags))
787 		{
788 			stripquotes(user);
789 			stripquotes(host);
790 		}
791 
792 		/* hack attack -- delivermail compatibility */
793 		if (m == ProgMailer && *user == '|')
794 			user++;
795 
796 		/*
797 		**  If an error message has already been given, don't
798 		**	bother to send to this address.
799 		**
800 		**	>>>>>>>>>> This clause assumes that the local mailer
801 		**	>> NOTE >> cannot do any further aliasing; that
802 		**	>>>>>>>>>> function is subsumed by sendmail.
803 		*/
804 
805 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
806 			continue;
807 
808 		/* save statistics.... */
809 		markstats(e, to);
810 
811 		/*
812 		**  See if this user name is "special".
813 		**	If the user name has a slash in it, assume that this
814 		**	is a file -- send it off without further ado.  Note
815 		**	that this type of addresses is not processed along
816 		**	with the others, so we fudge on the To person.
817 		*/
818 
819 		if (m == FileMailer)
820 		{
821 			rcode = mailfile(user, ctladdr, e);
822 			giveresponse(rcode, m, NULL, ctladdr, e);
823 			if (rcode == EX_OK)
824 				to->q_flags |= QSENT;
825 			continue;
826 		}
827 
828 		/*
829 		**  Address is verified -- add this user to mailer
830 		**  argv, and add it to the print list of recipients.
831 		*/
832 
833 		/* link together the chain of recipients */
834 		to->q_tchain = tochain;
835 		tochain = to;
836 
837 		/* create list of users for error messages */
838 		(void) strcat(tobuf, ",");
839 		(void) strcat(tobuf, to->q_paddr);
840 		define('u', user, e);		/* to user */
841 		p = to->q_home;
842 		if (p == NULL && ctladdr != NULL)
843 			p = ctladdr->q_home;
844 		define('z', p, e);	/* user's home */
845 
846 		/*
847 		**  Expand out this user into argument list.
848 		*/
849 
850 		if (!clever)
851 		{
852 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
853 			*pvp++ = newstr(buf);
854 			if (pvp >= &pv[MAXPV - 2])
855 			{
856 				/* allow some space for trailing parms */
857 				break;
858 			}
859 		}
860 	}
861 
862 	/* see if any addresses still exist */
863 	if (tobuf[0] == '\0')
864 	{
865 		define('g', (char *) NULL, e);
866 		return (0);
867 	}
868 
869 	/* print out messages as full list */
870 	e->e_to = tobuf + 1;
871 
872 	/*
873 	**  Fill out any parameters after the $u parameter.
874 	*/
875 
876 	while (!clever && *++mvp != NULL)
877 	{
878 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
879 		*pvp++ = newstr(buf);
880 		if (pvp >= &pv[MAXPV])
881 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
882 	}
883 	*pvp++ = NULL;
884 
885 	/*
886 	**  Call the mailer.
887 	**	The argument vector gets built, pipes
888 	**	are created as necessary, and we fork & exec as
889 	**	appropriate.
890 	**	If we are running SMTP, we just need to clean up.
891 	*/
892 
893 	/*XXX this seems a bit wierd */
894 	if (ctladdr == NULL && m != ProgMailer &&
895 	    bitset(QGOODUID, e->e_from.q_flags))
896 		ctladdr = &e->e_from;
897 
898 #ifdef NAMED_BIND
899 	if (ConfigLevel < 2)
900 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
901 #endif
902 
903 	if (tTd(11, 1))
904 	{
905 		printf("openmailer:");
906 		printav(pv);
907 	}
908 	errno = 0;
909 
910 	CurHostName = m->m_mailer;
911 
912 	/*
913 	**  Deal with the special case of mail handled through an IPC
914 	**  connection.
915 	**	In this case we don't actually fork.  We must be
916 	**	running SMTP for this to work.  We will return a
917 	**	zero pid to indicate that we are running IPC.
918 	**  We also handle a debug version that just talks to stdin/out.
919 	*/
920 
921 	curhost = NULL;
922 	SmtpPhase = NULL;
923 	mci = NULL;
924 
925 #ifdef XDEBUG
926 	{
927 		char wbuf[MAXLINE];
928 
929 		/* make absolutely certain 0, 1, and 2 are in use */
930 		sprintf(wbuf, "%s... openmailer(%s)", e->e_to, m->m_name);
931 		checkfd012(wbuf);
932 	}
933 #endif
934 
935 	/* check for Local Person Communication -- not for mortals!!! */
936 	if (strcmp(m->m_mailer, "[LPC]") == 0)
937 	{
938 		mci = (MCI *) xalloc(sizeof *mci);
939 		bzero((char *) mci, sizeof *mci);
940 		mci->mci_in = stdin;
941 		mci->mci_out = stdout;
942 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
943 		mci->mci_mailer = m;
944 	}
945 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
946 		 strcmp(m->m_mailer, "[TCP]") == 0)
947 	{
948 #ifdef DAEMON
949 		register int i;
950 		register u_short port;
951 
952 		if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
953 		{
954 			syserr("null host name for %s mailer", m->m_mailer);
955 			rcode = EX_CONFIG;
956 			goto give_up;
957 		}
958 
959 		CurHostName = pv[1];
960 		curhost = hostsignature(m, pv[1], e);
961 
962 		if (curhost == NULL || curhost[0] == '\0')
963 		{
964 			syserr("null host signature for %s", pv[1]);
965 			rcode = EX_OSERR;
966 			goto give_up;
967 		}
968 
969 		if (!clever)
970 		{
971 			syserr("554 non-clever IPC");
972 			rcode = EX_CONFIG;
973 			goto give_up;
974 		}
975 		if (pv[2] != NULL)
976 			port = atoi(pv[2]);
977 		else
978 			port = 0;
979 tryhost:
980 		while (*curhost != '\0')
981 		{
982 			register char *p;
983 			static char hostbuf[MAXNAME];
984 
985 			/* pull the next host from the signature */
986 			p = strchr(curhost, ':');
987 			if (p == NULL)
988 				p = &curhost[strlen(curhost)];
989 			if (p == curhost)
990 			{
991 				syserr("deliver: null host name in signature");
992 				curhost++;
993 				continue;
994 			}
995 			strncpy(hostbuf, curhost, p - curhost);
996 			hostbuf[p - curhost] = '\0';
997 			if (*p != '\0')
998 				p++;
999 			curhost = p;
1000 
1001 			/* see if we already know that this host is fried */
1002 			CurHostName = hostbuf;
1003 			mci = mci_get(hostbuf, m);
1004 			if (mci->mci_state != MCIS_CLOSED)
1005 			{
1006 				if (tTd(11, 1))
1007 				{
1008 					printf("openmailer: ");
1009 					mci_dump(mci, FALSE);
1010 				}
1011 				CurHostName = mci->mci_host;
1012 				break;
1013 			}
1014 			mci->mci_mailer = m;
1015 			if (mci->mci_exitstat != EX_OK)
1016 				continue;
1017 
1018 			/* try the connection */
1019 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
1020 			message("Connecting to %s (%s)...",
1021 				hostbuf, m->m_name);
1022 			i = makeconnection(hostbuf, port, mci,
1023 				bitnset(M_SECURE_PORT, m->m_flags));
1024 			mci->mci_exitstat = i;
1025 			mci->mci_errno = errno;
1026 #ifdef NAMED_BIND
1027 			mci->mci_herrno = h_errno;
1028 #endif
1029 			if (i == EX_OK)
1030 			{
1031 				mci->mci_state = MCIS_OPENING;
1032 				mci_cache(mci);
1033 				if (TrafficLogFile != NULL)
1034 					fprintf(TrafficLogFile, "%05d == CONNECT %s\n",
1035 						getpid(), hostbuf);
1036 				break;
1037 			}
1038 			else if (tTd(11, 1))
1039 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1040 					i, errno);
1041 
1042 			/* enter status of this host */
1043 			setstat(i);
1044 
1045 			/* should print some message here for -v mode */
1046 		}
1047 		if (mci == NULL)
1048 		{
1049 			syserr("deliver: no host name");
1050 			rcode = EX_OSERR;
1051 			goto give_up;
1052 		}
1053 		mci->mci_pid = 0;
1054 #else /* no DAEMON */
1055 		syserr("554 openmailer: no IPC");
1056 		if (tTd(11, 1))
1057 			printf("openmailer: NULL\n");
1058 		rcode = EX_UNAVAILABLE;
1059 		goto give_up;
1060 #endif /* DAEMON */
1061 	}
1062 	else
1063 	{
1064 		if (TrafficLogFile != NULL)
1065 		{
1066 			char **av;
1067 
1068 			fprintf(TrafficLogFile, "%05d === EXEC", getpid());
1069 			for (av = pv; *av != NULL; av++)
1070 				fprintf(TrafficLogFile, " %s", *av);
1071 			fprintf(TrafficLogFile, "\n");
1072 		}
1073 
1074 		/* create a pipe to shove the mail through */
1075 		if (pipe(mpvect) < 0)
1076 		{
1077 			syserr("%s... openmailer(%s): pipe (to mailer)",
1078 				e->e_to, m->m_name);
1079 			if (tTd(11, 1))
1080 				printf("openmailer: NULL\n");
1081 			rcode = EX_OSERR;
1082 			goto give_up;
1083 		}
1084 
1085 		/* if this mailer speaks smtp, create a return pipe */
1086 		if (clever && pipe(rpvect) < 0)
1087 		{
1088 			syserr("%s... openmailer(%s): pipe (from mailer)",
1089 				e->e_to, m->m_name);
1090 			(void) close(mpvect[0]);
1091 			(void) close(mpvect[1]);
1092 			if (tTd(11, 1))
1093 				printf("openmailer: NULL\n");
1094 			rcode = EX_OSERR;
1095 			goto give_up;
1096 		}
1097 
1098 		/*
1099 		**  Actually fork the mailer process.
1100 		**	DOFORK is clever about retrying.
1101 		**
1102 		**	Dispose of SIGCHLD signal catchers that may be laying
1103 		**	around so that endmail will get it.
1104 		*/
1105 
1106 		if (e->e_xfp != NULL)
1107 			(void) fflush(e->e_xfp);		/* for debugging */
1108 		(void) fflush(stdout);
1109 # ifdef SIGCHLD
1110 		(void) setsignal(SIGCHLD, SIG_DFL);
1111 # endif /* SIGCHLD */
1112 		DOFORK(FORK);
1113 		/* pid is set by DOFORK */
1114 		if (pid < 0)
1115 		{
1116 			/* failure */
1117 			syserr("%s... openmailer(%s): cannot fork",
1118 				e->e_to, m->m_name);
1119 			(void) close(mpvect[0]);
1120 			(void) close(mpvect[1]);
1121 			if (clever)
1122 			{
1123 				(void) close(rpvect[0]);
1124 				(void) close(rpvect[1]);
1125 			}
1126 			if (tTd(11, 1))
1127 				printf("openmailer: NULL\n");
1128 			rcode = EX_OSERR;
1129 			goto give_up;
1130 		}
1131 		else if (pid == 0)
1132 		{
1133 			int i;
1134 			int saveerrno;
1135 			char **ep;
1136 			char *env[MAXUSERENVIRON];
1137 			extern char **environ;
1138 			extern int DtableSize;
1139 
1140 			/* child -- set up input & exec mailer */
1141 			(void) setsignal(SIGINT, SIG_IGN);
1142 			(void) setsignal(SIGHUP, SIG_IGN);
1143 			(void) setsignal(SIGTERM, SIG_DFL);
1144 
1145 			/* reset user and group */
1146 			if (!bitnset(M_RESTR, m->m_flags))
1147 			{
1148 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1149 				{
1150 					(void) initgroups(DefUser, DefGid);
1151 					(void) setgid(DefGid);
1152 					(void) setuid(DefUid);
1153 				}
1154 				else
1155 				{
1156 					(void) initgroups(ctladdr->q_ruser?
1157 						ctladdr->q_ruser: ctladdr->q_user,
1158 						ctladdr->q_gid);
1159 					(void) setgid(ctladdr->q_gid);
1160 					(void) setuid(ctladdr->q_uid);
1161 				}
1162 			}
1163 
1164 			if (tTd(11, 2))
1165 				printf("openmailer: running as r/euid=%d/%d\n",
1166 					getuid(), geteuid());
1167 
1168 			/* move into some "safe" directory */
1169 			if (m->m_execdir != NULL)
1170 			{
1171 				char *p, *q;
1172 				char buf[MAXLINE];
1173 
1174 				for (p = m->m_execdir; p != NULL; p = q)
1175 				{
1176 					q = strchr(p, ':');
1177 					if (q != NULL)
1178 						*q = '\0';
1179 					expand(p, buf, &buf[sizeof buf] - 1, e);
1180 					if (q != NULL)
1181 						*q++ = ':';
1182 					if (tTd(11, 20))
1183 						printf("openmailer: trydir %s\n",
1184 							buf);
1185 					if (buf[0] != '\0' && chdir(buf) >= 0)
1186 						break;
1187 				}
1188 			}
1189 
1190 			/* arrange to filter std & diag output of command */
1191 			if (clever)
1192 			{
1193 				(void) close(rpvect[0]);
1194 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1195 				{
1196 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1197 						e->e_to, m->m_name, rpvect[1]);
1198 					_exit(EX_OSERR);
1199 				}
1200 				(void) close(rpvect[1]);
1201 			}
1202 			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON || HoldErrs)
1203 			{
1204 				/* put mailer output in transcript */
1205 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1206 				{
1207 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1208 						e->e_to, m->m_name,
1209 						fileno(e->e_xfp));
1210 					_exit(EX_OSERR);
1211 				}
1212 			}
1213 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1214 			{
1215 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1216 					e->e_to, m->m_name);
1217 				_exit(EX_OSERR);
1218 			}
1219 
1220 			/* arrange to get standard input */
1221 			(void) close(mpvect[1]);
1222 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1223 			{
1224 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1225 					e->e_to, m->m_name, mpvect[0]);
1226 				_exit(EX_OSERR);
1227 			}
1228 			(void) close(mpvect[0]);
1229 
1230 			/* arrange for all the files to be closed */
1231 			for (i = 3; i < DtableSize; i++)
1232 			{
1233 				register int j;
1234 
1235 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1236 					(void) fcntl(i, F_SETFD, j | 1);
1237 			}
1238 
1239 			/* set up the mailer environment */
1240 			i = 0;
1241 			env[i++] = "AGENT=sendmail";
1242 			for (ep = environ; *ep != NULL; ep++)
1243 			{
1244 				if (strncmp(*ep, "TZ=", 3) == 0)
1245 					env[i++] = *ep;
1246 			}
1247 			env[i++] = NULL;
1248 
1249 			/* try to execute the mailer */
1250 			execve(m->m_mailer, pv, env);
1251 			saveerrno = errno;
1252 			syserr("Cannot exec %s", m->m_mailer);
1253 			if (m == LocalMailer || transienterror(saveerrno))
1254 				_exit(EX_OSERR);
1255 			_exit(EX_UNAVAILABLE);
1256 		}
1257 
1258 		/*
1259 		**  Set up return value.
1260 		*/
1261 
1262 		mci = (MCI *) xalloc(sizeof *mci);
1263 		bzero((char *) mci, sizeof *mci);
1264 		mci->mci_mailer = m;
1265 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1266 		mci->mci_pid = pid;
1267 		(void) close(mpvect[0]);
1268 		mci->mci_out = fdopen(mpvect[1], "w");
1269 		if (mci->mci_out == NULL)
1270 		{
1271 			syserr("deliver: cannot create mailer output channel, fd=%d",
1272 				mpvect[1]);
1273 			(void) close(mpvect[1]);
1274 			if (clever)
1275 			{
1276 				(void) close(rpvect[0]);
1277 				(void) close(rpvect[1]);
1278 			}
1279 			rcode = EX_OSERR;
1280 			goto give_up;
1281 		}
1282 		if (clever)
1283 		{
1284 			(void) close(rpvect[1]);
1285 			mci->mci_in = fdopen(rpvect[0], "r");
1286 			if (mci->mci_in == NULL)
1287 			{
1288 				syserr("deliver: cannot create mailer input channel, fd=%d",
1289 					mpvect[1]);
1290 				(void) close(rpvect[0]);
1291 				fclose(mci->mci_out);
1292 				mci->mci_out = NULL;
1293 				rcode = EX_OSERR;
1294 				goto give_up;
1295 			}
1296 		}
1297 		else
1298 		{
1299 			mci->mci_flags |= MCIF_TEMP;
1300 			mci->mci_in = NULL;
1301 		}
1302 	}
1303 
1304 	/*
1305 	**  If we are in SMTP opening state, send initial protocol.
1306 	*/
1307 
1308 	if (clever && mci->mci_state != MCIS_CLOSED)
1309 	{
1310 		smtpinit(m, mci, e);
1311 	}
1312 	if (tTd(11, 1))
1313 	{
1314 		printf("openmailer: ");
1315 		mci_dump(mci, FALSE);
1316 	}
1317 
1318 	if (mci->mci_state != MCIS_OPEN)
1319 	{
1320 		/* couldn't open the mailer */
1321 		rcode = mci->mci_exitstat;
1322 		errno = mci->mci_errno;
1323 #ifdef NAMED_BIND
1324 		h_errno = mci->mci_herrno;
1325 #endif
1326 		if (rcode == EX_OK)
1327 		{
1328 			/* shouldn't happen */
1329 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1330 				rcode, mci->mci_state, firstsig);
1331 			rcode = EX_SOFTWARE;
1332 		}
1333 		else if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
1334 		{
1335 			/* try next MX site */
1336 			goto tryhost;
1337 		}
1338 	}
1339 	else if (!clever)
1340 	{
1341 		/*
1342 		**  Format and send message.
1343 		*/
1344 
1345 		putfromline(mci, e);
1346 		(*e->e_puthdr)(mci, e);
1347 		putline("\n", mci);
1348 		(*e->e_putbody)(mci, e, NULL);
1349 
1350 		/* get the exit status */
1351 		rcode = endmailer(mci, e, pv);
1352 	}
1353 	else
1354 #ifdef SMTP
1355 	{
1356 		/*
1357 		**  Send the MAIL FROM: protocol
1358 		*/
1359 
1360 		rcode = smtpmailfrom(m, mci, e);
1361 		if (rcode == EX_OK)
1362 		{
1363 			register char *t = tobuf;
1364 			register int i;
1365 
1366 			/* send the recipient list */
1367 			tobuf[0] = '\0';
1368 			for (to = tochain; to != NULL; to = to->q_tchain)
1369 			{
1370 				e->e_to = to->q_paddr;
1371 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1372 				{
1373 					markfailure(e, to, i);
1374 					giveresponse(i, m, mci, ctladdr, e);
1375 				}
1376 				else
1377 				{
1378 					*t++ = ',';
1379 					for (p = to->q_paddr; *p; *t++ = *p++)
1380 						continue;
1381 					*t = '\0';
1382 				}
1383 			}
1384 
1385 			/* now send the data */
1386 			if (tobuf[0] == '\0')
1387 			{
1388 				rcode = EX_OK;
1389 				e->e_to = NULL;
1390 				if (bitset(MCIF_CACHED, mci->mci_flags))
1391 					smtprset(m, mci, e);
1392 			}
1393 			else
1394 			{
1395 				e->e_to = tobuf + 1;
1396 				rcode = smtpdata(m, mci, e);
1397 			}
1398 
1399 			/* now close the connection */
1400 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1401 				smtpquit(m, mci, e);
1402 		}
1403 		if (rcode != EX_OK && curhost != NULL && *curhost != '\0')
1404 		{
1405 			/* try next MX site */
1406 			goto tryhost;
1407 		}
1408 	}
1409 #else /* not SMTP */
1410 	{
1411 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1412 		rcode = EX_CONFIG;
1413 		goto give_up;
1414 	}
1415 #endif /* SMTP */
1416 #ifdef NAMED_BIND
1417 	if (ConfigLevel < 2)
1418 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1419 #endif
1420 
1421 	/* arrange a return receipt if requested */
1422 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1423 	    bitnset(M_LOCALMAILER, m->m_flags))
1424 	{
1425 		e->e_flags |= EF_SENDRECEIPT;
1426 		/* do we want to send back more info? */
1427 	}
1428 
1429 	/*
1430 	**  Do final status disposal.
1431 	**	We check for something in tobuf for the SMTP case.
1432 	**	If we got a temporary failure, arrange to queue the
1433 	**		addressees.
1434 	*/
1435 
1436   give_up:
1437 	if (tobuf[0] != '\0')
1438 		giveresponse(rcode, m, mci, ctladdr, e);
1439 	for (to = tochain; to != NULL; to = to->q_tchain)
1440 	{
1441 		if (rcode != EX_OK)
1442 			markfailure(e, to, rcode);
1443 		else
1444 		{
1445 			to->q_flags |= QSENT;
1446 			e->e_nsent++;
1447 			if (e->e_receiptto != NULL &&
1448 			    bitnset(M_LOCALMAILER, m->m_flags))
1449 			{
1450 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1451 					to->q_paddr);
1452 			}
1453 		}
1454 	}
1455 
1456 	/*
1457 	**  Restore state and return.
1458 	*/
1459 
1460 #ifdef XDEBUG
1461 	{
1462 		char wbuf[MAXLINE];
1463 
1464 		/* make absolutely certain 0, 1, and 2 are in use */
1465 		sprintf(wbuf, "%s... end of deliver(%s)",
1466 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1467 			m->m_name);
1468 		checkfd012(wbuf);
1469 	}
1470 #endif
1471 
1472 	errno = 0;
1473 	define('g', (char *) NULL, e);
1474 	return (rcode);
1475 }
1476 /*
1477 **  MARKFAILURE -- mark a failure on a specific address.
1478 **
1479 **	Parameters:
1480 **		e -- the envelope we are sending.
1481 **		q -- the address to mark.
1482 **		rcode -- the code signifying the particular failure.
1483 **
1484 **	Returns:
1485 **		none.
1486 **
1487 **	Side Effects:
1488 **		marks the address (and possibly the envelope) with the
1489 **			failure so that an error will be returned or
1490 **			the message will be queued, as appropriate.
1491 */
1492 
1493 markfailure(e, q, rcode)
1494 	register ENVELOPE *e;
1495 	register ADDRESS *q;
1496 	int rcode;
1497 {
1498 	char buf[MAXLINE];
1499 
1500 	switch (rcode)
1501 	{
1502 	  case EX_OK:
1503 		break;
1504 
1505 	  case EX_TEMPFAIL:
1506 	  case EX_IOERR:
1507 	  case EX_OSERR:
1508 		q->q_flags |= QQUEUEUP;
1509 		break;
1510 
1511 	  default:
1512 		q->q_flags |= QBADADDR;
1513 		break;
1514 	}
1515 }
1516 /*
1517 **  ENDMAILER -- Wait for mailer to terminate.
1518 **
1519 **	We should never get fatal errors (e.g., segmentation
1520 **	violation), so we report those specially.  For other
1521 **	errors, we choose a status message (into statmsg),
1522 **	and if it represents an error, we print it.
1523 **
1524 **	Parameters:
1525 **		pid -- pid of mailer.
1526 **		e -- the current envelope.
1527 **		pv -- the parameter vector that invoked the mailer
1528 **			(for error messages).
1529 **
1530 **	Returns:
1531 **		exit code of mailer.
1532 **
1533 **	Side Effects:
1534 **		none.
1535 */
1536 
1537 endmailer(mci, e, pv)
1538 	register MCI *mci;
1539 	register ENVELOPE *e;
1540 	char **pv;
1541 {
1542 	int st;
1543 
1544 	/* close any connections */
1545 	if (mci->mci_in != NULL)
1546 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1547 	if (mci->mci_out != NULL)
1548 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1549 	mci->mci_in = mci->mci_out = NULL;
1550 	mci->mci_state = MCIS_CLOSED;
1551 
1552 	/* in the IPC case there is nothing to wait for */
1553 	if (mci->mci_pid == 0)
1554 		return (EX_OK);
1555 
1556 	/* wait for the mailer process to die and collect status */
1557 	st = waitfor(mci->mci_pid);
1558 	if (st == -1)
1559 	{
1560 		syserr("endmailer %s: wait", pv[0]);
1561 		return (EX_SOFTWARE);
1562 	}
1563 
1564 	if (WIFEXITED(st))
1565 	{
1566 		/* normal death -- return status */
1567 		return (WEXITSTATUS(st));
1568 	}
1569 
1570 	/* it died a horrid death */
1571 	syserr("451 mailer %s died with signal %o",
1572 		mci->mci_mailer->m_name, st);
1573 
1574 	/* log the arguments */
1575 	if (pv != NULL && e->e_xfp != NULL)
1576 	{
1577 		register char **av;
1578 
1579 		fprintf(e->e_xfp, "Arguments:");
1580 		for (av = pv; *av != NULL; av++)
1581 			fprintf(e->e_xfp, " %s", *av);
1582 		fprintf(e->e_xfp, "\n");
1583 	}
1584 
1585 	ExitStat = EX_TEMPFAIL;
1586 	return (EX_TEMPFAIL);
1587 }
1588 /*
1589 **  GIVERESPONSE -- Interpret an error response from a mailer
1590 **
1591 **	Parameters:
1592 **		stat -- the status code from the mailer (high byte
1593 **			only; core dumps must have been taken care of
1594 **			already).
1595 **		m -- the mailer info for this mailer.
1596 **		mci -- the mailer connection info -- can be NULL if the
1597 **			response is given before the connection is made.
1598 **		ctladdr -- the controlling address for the recipient
1599 **			address(es).
1600 **		e -- the current envelope.
1601 **
1602 **	Returns:
1603 **		none.
1604 **
1605 **	Side Effects:
1606 **		Errors may be incremented.
1607 **		ExitStat may be set.
1608 */
1609 
1610 giveresponse(stat, m, mci, ctladdr, e)
1611 	int stat;
1612 	register MAILER *m;
1613 	register MCI *mci;
1614 	ADDRESS *ctladdr;
1615 	ENVELOPE *e;
1616 {
1617 	register const char *statmsg;
1618 	extern char *SysExMsg[];
1619 	register int i;
1620 	extern int N_SysEx;
1621 	char buf[MAXLINE];
1622 
1623 	/*
1624 	**  Compute status message from code.
1625 	*/
1626 
1627 	i = stat - EX__BASE;
1628 	if (stat == 0)
1629 	{
1630 		statmsg = "250 Sent";
1631 		if (e->e_statmsg != NULL)
1632 		{
1633 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1634 			statmsg = buf;
1635 		}
1636 	}
1637 	else if (i < 0 || i > N_SysEx)
1638 	{
1639 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1640 		stat = EX_UNAVAILABLE;
1641 		statmsg = buf;
1642 	}
1643 	else if (stat == EX_TEMPFAIL)
1644 	{
1645 		(void) strcpy(buf, SysExMsg[i] + 1);
1646 #ifdef NAMED_BIND
1647 		if (h_errno == TRY_AGAIN)
1648 			statmsg = errstring(h_errno+E_DNSBASE);
1649 		else
1650 #endif
1651 		{
1652 			if (errno != 0)
1653 				statmsg = errstring(errno);
1654 			else
1655 			{
1656 #ifdef SMTP
1657 				statmsg = SmtpError;
1658 #else /* SMTP */
1659 				statmsg = NULL;
1660 #endif /* SMTP */
1661 			}
1662 		}
1663 		if (statmsg != NULL && statmsg[0] != '\0')
1664 		{
1665 			(void) strcat(buf, ": ");
1666 			(void) strcat(buf, statmsg);
1667 		}
1668 		statmsg = buf;
1669 	}
1670 #ifdef NAMED_BIND
1671 	else if (stat == EX_NOHOST && h_errno != 0)
1672 	{
1673 		statmsg = errstring(h_errno + E_DNSBASE);
1674 		(void) sprintf(buf, "%s (%s)", SysExMsg[i], statmsg);
1675 		statmsg = buf;
1676 	}
1677 #endif
1678 	else
1679 	{
1680 		statmsg = SysExMsg[i];
1681 		if (*statmsg++ == ':')
1682 		{
1683 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1684 			statmsg = buf;
1685 		}
1686 	}
1687 
1688 	/*
1689 	**  Print the message as appropriate
1690 	*/
1691 
1692 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1693 	{
1694 		extern char MsgBuf[];
1695 
1696 		message(&statmsg[4], errstring(errno));
1697 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1698 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1699 	}
1700 	else
1701 	{
1702 		Errors++;
1703 		usrerr(statmsg, errstring(errno));
1704 	}
1705 
1706 	/*
1707 	**  Final cleanup.
1708 	**	Log a record of the transaction.  Compute the new
1709 	**	ExitStat -- if we already had an error, stick with
1710 	**	that.
1711 	*/
1712 
1713 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1714 		logdelivery(m, mci, &statmsg[4], ctladdr, e);
1715 
1716 	if (stat != EX_TEMPFAIL)
1717 		setstat(stat);
1718 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1719 	{
1720 		if (e->e_message != NULL)
1721 			free(e->e_message);
1722 		e->e_message = newstr(&statmsg[4]);
1723 	}
1724 	errno = 0;
1725 #ifdef NAMED_BIND
1726 	h_errno = 0;
1727 #endif
1728 }
1729 /*
1730 **  LOGDELIVERY -- log the delivery in the system log
1731 **
1732 **	Care is taken to avoid logging lines that are too long, because
1733 **	some versions of syslog have an unfortunate proclivity for core
1734 **	dumping.  This is a hack, to be sure, that is at best empirical.
1735 **
1736 **	Parameters:
1737 **		m -- the mailer info.  Can be NULL for initial queue.
1738 **		mci -- the mailer connection info -- can be NULL if the
1739 **			log is occuring when no connection is active.
1740 **		stat -- the message to print for the status.
1741 **		ctladdr -- the controlling address for the to list.
1742 **		e -- the current envelope.
1743 **
1744 **	Returns:
1745 **		none
1746 **
1747 **	Side Effects:
1748 **		none
1749 */
1750 
1751 logdelivery(m, mci, stat, ctladdr, e)
1752 	MAILER *m;
1753 	register MCI *mci;
1754 	char *stat;
1755 	ADDRESS *ctladdr;
1756 	register ENVELOPE *e;
1757 {
1758 # ifdef LOG
1759 	register char *bp;
1760 	register char *p;
1761 	int l;
1762 	char buf[512];
1763 
1764 #  if (SYSLOG_BUFSIZE) >= 256
1765 	bp = buf;
1766 	if (ctladdr != NULL)
1767 	{
1768 		strcpy(bp, ", ctladdr=");
1769 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
1770 		bp += strlen(bp);
1771 		if (bitset(QGOODUID, ctladdr->q_flags))
1772 		{
1773 			(void) sprintf(bp, " (%d/%d)",
1774 					ctladdr->q_uid, ctladdr->q_gid);
1775 			bp += strlen(bp);
1776 		}
1777 	}
1778 
1779 	(void) sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1780 	bp += strlen(bp);
1781 
1782 	if (m != NULL)
1783 	{
1784 		(void) strcpy(bp, ", mailer=");
1785 		(void) strcat(bp, m->m_name);
1786 		bp += strlen(bp);
1787 	}
1788 
1789 	if (mci != NULL && mci->mci_host != NULL)
1790 	{
1791 # ifdef DAEMON
1792 		extern SOCKADDR CurHostAddr;
1793 # endif
1794 
1795 		(void) strcpy(bp, ", relay=");
1796 		(void) strcat(bp, mci->mci_host);
1797 
1798 # ifdef DAEMON
1799 		(void) strcat(bp, " [");
1800 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1801 		(void) strcat(bp, "]");
1802 # endif
1803 	}
1804 	else
1805 	{
1806 		char *p = macvalue('h', e);
1807 
1808 		if (p != NULL && p[0] != '\0')
1809 		{
1810 			(void) strcpy(bp, ", relay=");
1811 			(void) strcat(bp, p);
1812 		}
1813 	}
1814 	bp += strlen(bp);
1815 
1816 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
1817 #if (STATLEN) < 63
1818 # undef STATLEN
1819 # define STATLEN	63
1820 #endif
1821 #if (STATLEN) > 203
1822 # undef STATLEN
1823 # define STATLEN	203
1824 #endif
1825 
1826 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
1827 	{
1828 		/* desperation move -- truncate data */
1829 		bp = buf + sizeof buf - ((STATLEN) + 17);
1830 		strcpy(bp, "...");
1831 		bp += 3;
1832 	}
1833 
1834 	(void) strcpy(bp, ", stat=");
1835 	bp += strlen(bp);
1836 
1837 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
1838 
1839 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
1840 	p = e->e_to;
1841 	while (strlen(p) >= l)
1842 	{
1843 		register char *q = strchr(p + l, ',');
1844 
1845 		if (q == NULL)
1846 			break;
1847 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
1848 			e->e_id, ++q - p, p, buf);
1849 		p = q;
1850 	}
1851 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
1852 
1853 #  else		/* we have a very short log buffer size */
1854 
1855 	l = SYSLOG_BUFSIZE - 80;
1856 	p = e->e_to;
1857 	while (strlen(p) >= l)
1858 	{
1859 		register char *q = strchr(p + l, ',');
1860 
1861 		if (q == NULL)
1862 			break;
1863 		syslog(LOG_INFO, "%s: to=%.*s [more]",
1864 			e->e_id, ++q - p, p);
1865 		p = q;
1866 	}
1867 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
1868 
1869 	if (ctladdr != NULL)
1870 	{
1871 		bp = buf;
1872 		strcpy(buf, "ctladdr=");
1873 		bp += strlen(buf);
1874 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
1875 		bp += strlen(buf);
1876 		if (bitset(QGOODUID, ctladdr->q_flags))
1877 		{
1878 			(void) sprintf(bp, " (%d/%d)",
1879 					ctladdr->q_uid, ctladdr->q_gid);
1880 			bp += strlen(bp);
1881 		}
1882 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1883 	}
1884 	bp = buf;
1885 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1886 	bp += strlen(bp);
1887 
1888 	if (m != NULL)
1889 	{
1890 		sprintf(bp, ", mailer=%s", m->m_name);
1891 		bp += strlen(bp);
1892 	}
1893 
1894 	if (mci != NULL && mci->mci_host != NULL)
1895 	{
1896 # ifdef DAEMON
1897 		extern SOCKADDR CurHostAddr;
1898 # endif
1899 
1900 		sprintf(bp, ", relay=%s", mci->mci_host);
1901 
1902 # ifdef DAEMON
1903 		(void) strcat(bp, " [");
1904 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1905 		(void) strcat(bp, "]");
1906 # endif
1907 	}
1908 	else
1909 	{
1910 		char *p = macvalue('h', e);
1911 
1912 		if (p != NULL && p[0] != '\0')
1913 			sprintf(bp, ", relay=%s", p);
1914 	}
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