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