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