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