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