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