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