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