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.130 (Berkeley) 03/14/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 + 1];
606 	char rpathbuf[MAXNAME + 1];	/* 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, sizeof buf, 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, sizeof buf, 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, sizeof buf, 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 + 1];
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 			if (e->e_lockfp != NULL)
1217 			{
1218 				fclose(e->e_lockfp);
1219 				e->e_lockfp = NULL;
1220 			}
1221 
1222 			/* child -- set up input & exec mailer */
1223 			(void) setsignal(SIGINT, SIG_IGN);
1224 			(void) setsignal(SIGHUP, SIG_IGN);
1225 			(void) setsignal(SIGTERM, SIG_DFL);
1226 
1227 			/* reset user and group */
1228 			if (bitnset(M_SPECIFIC_UID, m->m_flags))
1229 			{
1230 				(void) setgid(m->m_gid);
1231 				(void) setuid(m->m_uid);
1232 			}
1233 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
1234 			{
1235 				(void) initgroups(ctladdr->q_ruser?
1236 					ctladdr->q_ruser: ctladdr->q_user,
1237 					ctladdr->q_gid);
1238 				(void) setgid(ctladdr->q_gid);
1239 				(void) setuid(ctladdr->q_uid);
1240 			}
1241 			else
1242 			{
1243 				(void) initgroups(DefUser, DefGid);
1244 				if (m->m_gid == 0)
1245 					(void) setgid(DefGid);
1246 				else
1247 					(void) setgid(m->m_gid);
1248 				if (m->m_uid == 0)
1249 					(void) setuid(DefUid);
1250 				else
1251 					(void) setuid(m->m_uid);
1252 			}
1253 
1254 			if (tTd(11, 2))
1255 				printf("openmailer: running as r/euid=%d/%d\n",
1256 					getuid(), geteuid());
1257 
1258 			/* move into some "safe" directory */
1259 			if (m->m_execdir != NULL)
1260 			{
1261 				char *p, *q;
1262 				char buf[MAXLINE + 1];
1263 
1264 				for (p = m->m_execdir; p != NULL; p = q)
1265 				{
1266 					q = strchr(p, ':');
1267 					if (q != NULL)
1268 						*q = '\0';
1269 					expand(p, buf, sizeof buf, e);
1270 					if (q != NULL)
1271 						*q++ = ':';
1272 					if (tTd(11, 20))
1273 						printf("openmailer: trydir %s\n",
1274 							buf);
1275 					if (buf[0] != '\0' && chdir(buf) >= 0)
1276 						break;
1277 				}
1278 			}
1279 
1280 			/* arrange to filter std & diag output of command */
1281 			if (clever)
1282 			{
1283 				(void) close(rpvect[0]);
1284 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1285 				{
1286 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1287 						e->e_to, m->m_name, rpvect[1]);
1288 					_exit(EX_OSERR);
1289 				}
1290 				(void) close(rpvect[1]);
1291 			}
1292 			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON ||
1293 				  HoldErrs || DisConnected)
1294 			{
1295 				/* put mailer output in transcript */
1296 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1297 				{
1298 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1299 						e->e_to, m->m_name,
1300 						fileno(e->e_xfp));
1301 					_exit(EX_OSERR);
1302 				}
1303 			}
1304 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1305 			{
1306 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1307 					e->e_to, m->m_name);
1308 				_exit(EX_OSERR);
1309 			}
1310 
1311 			/* arrange to get standard input */
1312 			(void) close(mpvect[1]);
1313 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1314 			{
1315 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1316 					e->e_to, m->m_name, mpvect[0]);
1317 				_exit(EX_OSERR);
1318 			}
1319 			(void) close(mpvect[0]);
1320 
1321 			/* arrange for all the files to be closed */
1322 			for (i = 3; i < DtableSize; i++)
1323 			{
1324 				register int j;
1325 
1326 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1327 					(void) fcntl(i, F_SETFD, j | 1);
1328 			}
1329 
1330 			/*
1331 			**  Set up the mailer environment
1332 			**	_FORCE_MAIL_LOCAL_ is DG-UX equiv of -d flag.
1333 			**	TZ is timezone information.
1334 			**	SYSTYPE is Apollo software sys type (required).
1335 			**	ISP is Apollo hardware system type (required).
1336 			*/
1337 
1338 			i = 0;
1339 			env[i++] = "AGENT=sendmail";
1340 			env[i++] = "_FORCE_MAIL_LOCAL_=yes";
1341 			for (ep = environ; *ep != NULL; ep++)
1342 			{
1343 				if (strncmp(*ep, "TZ=", 3) == 0 ||
1344 				    strncmp(*ep, "ISP=", 4) == 0 ||
1345 				    strncmp(*ep, "SYSTYPE=", 8) == 0)
1346 					env[i++] = *ep;
1347 			}
1348 			env[i] = NULL;
1349 
1350 			/* run disconnected from terminal */
1351 			(void) setsid();
1352 
1353 			/* try to execute the mailer */
1354 			execve(m->m_mailer, pv, env);
1355 			saveerrno = errno;
1356 			syserr("Cannot exec %s", m->m_mailer);
1357 			if (bitnset(M_LOCALMAILER, m->m_flags) ||
1358 			    transienterror(saveerrno))
1359 				_exit(EX_OSERR);
1360 			_exit(EX_UNAVAILABLE);
1361 		}
1362 
1363 		/*
1364 		**  Set up return value.
1365 		*/
1366 
1367 		mci = (MCI *) xalloc(sizeof *mci);
1368 		bzero((char *) mci, sizeof *mci);
1369 		mci->mci_mailer = m;
1370 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1371 		mci->mci_pid = pid;
1372 		(void) close(mpvect[0]);
1373 		mci->mci_out = fdopen(mpvect[1], "w");
1374 		if (mci->mci_out == NULL)
1375 		{
1376 			syserr("deliver: cannot create mailer output channel, fd=%d",
1377 				mpvect[1]);
1378 			(void) close(mpvect[1]);
1379 			if (clever)
1380 			{
1381 				(void) close(rpvect[0]);
1382 				(void) close(rpvect[1]);
1383 			}
1384 			rcode = EX_OSERR;
1385 			goto give_up;
1386 		}
1387 		if (clever)
1388 		{
1389 			(void) close(rpvect[1]);
1390 			mci->mci_in = fdopen(rpvect[0], "r");
1391 			if (mci->mci_in == NULL)
1392 			{
1393 				syserr("deliver: cannot create mailer input channel, fd=%d",
1394 					mpvect[1]);
1395 				(void) close(rpvect[0]);
1396 				fclose(mci->mci_out);
1397 				mci->mci_out = NULL;
1398 				rcode = EX_OSERR;
1399 				goto give_up;
1400 			}
1401 		}
1402 		else
1403 		{
1404 			mci->mci_flags |= MCIF_TEMP;
1405 			mci->mci_in = NULL;
1406 		}
1407 	}
1408 
1409 	/*
1410 	**  If we are in SMTP opening state, send initial protocol.
1411 	*/
1412 
1413 	if (clever && mci->mci_state != MCIS_CLOSED)
1414 	{
1415 		smtpinit(m, mci, e);
1416 	}
1417 
1418 	if (bitset(EF_HAS8BIT, e->e_flags) && bitnset(M_7BITS, m->m_flags))
1419 		mci->mci_flags |= MCIF_CVT8TO7;
1420 	else
1421 		mci->mci_flags &= ~MCIF_CVT8TO7;
1422 
1423 	if (tTd(11, 1))
1424 	{
1425 		printf("openmailer: ");
1426 		mci_dump(mci, FALSE);
1427 	}
1428 
1429 	if (mci->mci_state != MCIS_OPEN)
1430 	{
1431 		/* couldn't open the mailer */
1432 		rcode = mci->mci_exitstat;
1433 		errno = mci->mci_errno;
1434 #if NAMED_BIND
1435 		h_errno = mci->mci_herrno;
1436 #endif
1437 		if (rcode == EX_OK)
1438 		{
1439 			/* shouldn't happen */
1440 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1441 				rcode, mci->mci_state, firstsig);
1442 			rcode = EX_SOFTWARE;
1443 		}
1444 		else if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
1445 		{
1446 			/* try next MX site */
1447 			goto tryhost;
1448 		}
1449 	}
1450 	else if (!clever)
1451 	{
1452 		/*
1453 		**  Format and send message.
1454 		*/
1455 
1456 		putfromline(mci, e);
1457 		(*e->e_puthdr)(mci, e->e_header, e);
1458 		(*e->e_putbody)(mci, e, NULL);
1459 
1460 		/* get the exit status */
1461 		rcode = endmailer(mci, e, pv);
1462 	}
1463 	else
1464 #ifdef SMTP
1465 	{
1466 		/*
1467 		**  Send the MAIL FROM: protocol
1468 		*/
1469 
1470 		rcode = smtpmailfrom(m, mci, e);
1471 		if (rcode == EX_OK)
1472 		{
1473 			register char *t = tobuf;
1474 			register int i;
1475 
1476 			/* send the recipient list */
1477 			tobuf[0] = '\0';
1478 			for (to = tochain; to != NULL; to = to->q_tchain)
1479 			{
1480 				e->e_to = to->q_paddr;
1481 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1482 				{
1483 					markfailure(e, to, mci, i);
1484 					giveresponse(i, m, mci, ctladdr, xstart, e);
1485 				}
1486 				else
1487 				{
1488 					*t++ = ',';
1489 					for (p = to->q_paddr; *p; *t++ = *p++)
1490 						continue;
1491 					*t = '\0';
1492 				}
1493 			}
1494 
1495 			/* now send the data */
1496 			if (tobuf[0] == '\0')
1497 			{
1498 				rcode = EX_OK;
1499 				e->e_to = NULL;
1500 				if (bitset(MCIF_CACHED, mci->mci_flags))
1501 					smtprset(m, mci, e);
1502 			}
1503 			else
1504 			{
1505 				e->e_to = tobuf + 1;
1506 				rcode = smtpdata(m, mci, e);
1507 			}
1508 
1509 			/* now close the connection */
1510 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1511 				smtpquit(m, mci, e);
1512 		}
1513 		if (rcode != EX_OK && curhost != NULL && *curhost != '\0')
1514 		{
1515 			/* try next MX site */
1516 			goto tryhost;
1517 		}
1518 	}
1519 #else /* not SMTP */
1520 	{
1521 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1522 		rcode = EX_CONFIG;
1523 		goto give_up;
1524 	}
1525 #endif /* SMTP */
1526 #if NAMED_BIND
1527 	if (ConfigLevel < 2)
1528 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1529 #endif
1530 
1531 	/* arrange a return receipt if requested */
1532 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1533 	    bitnset(M_LOCALMAILER, m->m_flags))
1534 	{
1535 		e->e_flags |= EF_SENDRECEIPT;
1536 		/* do we want to send back more info? */
1537 	}
1538 
1539 	/*
1540 	**  Do final status disposal.
1541 	**	We check for something in tobuf for the SMTP case.
1542 	**	If we got a temporary failure, arrange to queue the
1543 	**		addressees.
1544 	*/
1545 
1546   give_up:
1547 	if (tobuf[0] != '\0')
1548 		giveresponse(rcode, m, mci, ctladdr, xstart, e);
1549 	for (to = tochain; to != NULL; to = to->q_tchain)
1550 	{
1551 		if (rcode != EX_OK)
1552 			markfailure(e, to, mci, rcode);
1553 		else if (!bitset(QBADADDR|QQUEUEUP, to->q_flags))
1554 		{
1555 			to->q_flags |= QSENT;
1556 			to->q_statdate = curtime();
1557 			e->e_nsent++;
1558 			if (bitnset(M_LOCALMAILER, m->m_flags) &&
1559 			    (e->e_receiptto != NULL ||
1560 			     bitset(QPINGONSUCCESS, to->q_flags)))
1561 			{
1562 				to->q_flags |= QREPORT;
1563 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1564 					to->q_paddr);
1565 			}
1566 			else if (bitset(QPINGONSUCCESS, to->q_flags) &&
1567 				 !bitset(MCIF_DSN, mci->mci_flags))
1568 			{
1569 				to->q_flags |= QRELAYED;
1570 				fprintf(e->e_xfp, "%s... relayed; expect no further notifications\n",
1571 					to->q_paddr);
1572 			}
1573 		}
1574 	}
1575 
1576 	/*
1577 	**  Restore state and return.
1578 	*/
1579 
1580 #ifdef XDEBUG
1581 	{
1582 		char wbuf[MAXLINE];
1583 
1584 		/* make absolutely certain 0, 1, and 2 are in use */
1585 		sprintf(wbuf, "%s... end of deliver(%s)",
1586 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1587 			m->m_name);
1588 		checkfd012(wbuf);
1589 	}
1590 #endif
1591 
1592 	errno = 0;
1593 	define('g', (char *) NULL, e);
1594 	return (rcode);
1595 }
1596 /*
1597 **  MARKFAILURE -- mark a failure on a specific address.
1598 **
1599 **	Parameters:
1600 **		e -- the envelope we are sending.
1601 **		q -- the address to mark.
1602 **		mci -- mailer connection information.
1603 **		rcode -- the code signifying the particular failure.
1604 **
1605 **	Returns:
1606 **		none.
1607 **
1608 **	Side Effects:
1609 **		marks the address (and possibly the envelope) with the
1610 **			failure so that an error will be returned or
1611 **			the message will be queued, as appropriate.
1612 */
1613 
1614 markfailure(e, q, mci, rcode)
1615 	register ENVELOPE *e;
1616 	register ADDRESS *q;
1617 	register MCI *mci;
1618 	int rcode;
1619 {
1620 	char *stat = NULL;
1621 
1622 	switch (rcode)
1623 	{
1624 	  case EX_OK:
1625 		break;
1626 
1627 	  case EX_TEMPFAIL:
1628 	  case EX_IOERR:
1629 	  case EX_OSERR:
1630 		q->q_flags |= QQUEUEUP;
1631 		break;
1632 
1633 	  default:
1634 		q->q_flags |= QBADADDR;
1635 		break;
1636 	}
1637 
1638 	if (q->q_status == NULL && mci != NULL)
1639 		q->q_status = mci->mci_status;
1640 	switch (rcode)
1641 	{
1642 	  case EX_USAGE:
1643 		stat = "5.5.4";
1644 		break;
1645 
1646 	  case EX_DATAERR:
1647 		stat = "5.5.2";
1648 		break;
1649 
1650 	  case EX_NOUSER:
1651 	  case EX_NOHOST:
1652 		stat = "5.1.1";
1653 		break;
1654 
1655 	  case EX_NOINPUT:
1656 	  case EX_CANTCREAT:
1657 	  case EX_NOPERM:
1658 		stat = "5.3.0";
1659 		break;
1660 
1661 	  case EX_UNAVAILABLE:
1662 	  case EX_SOFTWARE:
1663 	  case EX_OSFILE:
1664 	  case EX_PROTOCOL:
1665 	  case EX_CONFIG:
1666 		stat = "5.5.0";
1667 		break;
1668 
1669 	  case EX_OSERR:
1670 	  case EX_IOERR:
1671 		stat = "4.5.0";
1672 		break;
1673 
1674 	  case EX_TEMPFAIL:
1675 		stat = "4.2.0";
1676 		break;
1677 	}
1678 	if (stat != NULL && q->q_status == NULL)
1679 		q->q_status = stat;
1680 
1681 	q->q_statdate = curtime();
1682 	if (CurHostName != NULL && CurHostName[0] != '\0')
1683 		q->q_statmta = newstr(CurHostName);
1684 	if (rcode != EX_OK && q->q_rstatus == NULL)
1685 	{
1686 		char buf[30];
1687 
1688 		(void) sprintf(buf, "%d", rcode);
1689 		q->q_rstatus = newstr(buf);
1690 	}
1691 }
1692 /*
1693 **  ENDMAILER -- Wait for mailer to terminate.
1694 **
1695 **	We should never get fatal errors (e.g., segmentation
1696 **	violation), so we report those specially.  For other
1697 **	errors, we choose a status message (into statmsg),
1698 **	and if it represents an error, we print it.
1699 **
1700 **	Parameters:
1701 **		pid -- pid of mailer.
1702 **		e -- the current envelope.
1703 **		pv -- the parameter vector that invoked the mailer
1704 **			(for error messages).
1705 **
1706 **	Returns:
1707 **		exit code of mailer.
1708 **
1709 **	Side Effects:
1710 **		none.
1711 */
1712 
1713 endmailer(mci, e, pv)
1714 	register MCI *mci;
1715 	register ENVELOPE *e;
1716 	char **pv;
1717 {
1718 	int st;
1719 
1720 	/* close any connections */
1721 	if (mci->mci_in != NULL)
1722 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1723 	if (mci->mci_out != NULL)
1724 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1725 	mci->mci_in = mci->mci_out = NULL;
1726 	mci->mci_state = MCIS_CLOSED;
1727 
1728 	/* in the IPC case there is nothing to wait for */
1729 	if (mci->mci_pid == 0)
1730 		return (EX_OK);
1731 
1732 	/* wait for the mailer process to die and collect status */
1733 	st = waitfor(mci->mci_pid);
1734 	if (st == -1)
1735 	{
1736 		syserr("endmailer %s: wait", pv[0]);
1737 		return (EX_SOFTWARE);
1738 	}
1739 
1740 	if (WIFEXITED(st))
1741 	{
1742 		/* normal death -- return status */
1743 		return (WEXITSTATUS(st));
1744 	}
1745 
1746 	/* it died a horrid death */
1747 	syserr("451 mailer %s died with signal %o",
1748 		mci->mci_mailer->m_name, st);
1749 
1750 	/* log the arguments */
1751 	if (pv != NULL && e->e_xfp != NULL)
1752 	{
1753 		register char **av;
1754 
1755 		fprintf(e->e_xfp, "Arguments:");
1756 		for (av = pv; *av != NULL; av++)
1757 			fprintf(e->e_xfp, " %s", *av);
1758 		fprintf(e->e_xfp, "\n");
1759 	}
1760 
1761 	ExitStat = EX_TEMPFAIL;
1762 	return (EX_TEMPFAIL);
1763 }
1764 /*
1765 **  GIVERESPONSE -- Interpret an error response from a mailer
1766 **
1767 **	Parameters:
1768 **		stat -- the status code from the mailer (high byte
1769 **			only; core dumps must have been taken care of
1770 **			already).
1771 **		m -- the mailer info for this mailer.
1772 **		mci -- the mailer connection info -- can be NULL if the
1773 **			response is given before the connection is made.
1774 **		ctladdr -- the controlling address for the recipient
1775 **			address(es).
1776 **		xstart -- the transaction start time, for computing
1777 **			transaction delays.
1778 **		e -- the current envelope.
1779 **
1780 **	Returns:
1781 **		none.
1782 **
1783 **	Side Effects:
1784 **		Errors may be incremented.
1785 **		ExitStat may be set.
1786 */
1787 
1788 giveresponse(stat, m, mci, ctladdr, xstart, e)
1789 	int stat;
1790 	register MAILER *m;
1791 	register MCI *mci;
1792 	ADDRESS *ctladdr;
1793 	time_t xstart;
1794 	ENVELOPE *e;
1795 {
1796 	register const char *statmsg;
1797 	extern char *SysExMsg[];
1798 	register int i;
1799 	extern int N_SysEx;
1800 	char buf[MAXLINE];
1801 
1802 	/*
1803 	**  Compute status message from code.
1804 	*/
1805 
1806 	i = stat - EX__BASE;
1807 	if (stat == 0)
1808 	{
1809 		statmsg = "250 Sent";
1810 		if (e->e_statmsg != NULL)
1811 		{
1812 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1813 			statmsg = buf;
1814 		}
1815 	}
1816 	else if (i < 0 || i > N_SysEx)
1817 	{
1818 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1819 		stat = EX_UNAVAILABLE;
1820 		statmsg = buf;
1821 	}
1822 	else if (stat == EX_TEMPFAIL)
1823 	{
1824 		(void) strcpy(buf, SysExMsg[i] + 1);
1825 #if NAMED_BIND
1826 		if (h_errno == TRY_AGAIN)
1827 			statmsg = errstring(h_errno+E_DNSBASE);
1828 		else
1829 #endif
1830 		{
1831 			if (errno != 0)
1832 				statmsg = errstring(errno);
1833 			else
1834 			{
1835 #ifdef SMTP
1836 				statmsg = SmtpError;
1837 #else /* SMTP */
1838 				statmsg = NULL;
1839 #endif /* SMTP */
1840 			}
1841 		}
1842 		if (statmsg != NULL && statmsg[0] != '\0')
1843 		{
1844 			(void) strcat(buf, ": ");
1845 			(void) strcat(buf, statmsg);
1846 		}
1847 		statmsg = buf;
1848 	}
1849 #if NAMED_BIND
1850 	else if (stat == EX_NOHOST && h_errno != 0)
1851 	{
1852 		statmsg = errstring(h_errno + E_DNSBASE);
1853 		(void) sprintf(buf, "%s (%s)", SysExMsg[i] + 1, statmsg);
1854 		statmsg = buf;
1855 	}
1856 #endif
1857 	else
1858 	{
1859 		statmsg = SysExMsg[i];
1860 		if (*statmsg++ == ':')
1861 		{
1862 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1863 			statmsg = buf;
1864 		}
1865 	}
1866 
1867 	/*
1868 	**  Print the message as appropriate
1869 	*/
1870 
1871 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1872 	{
1873 		extern char MsgBuf[];
1874 
1875 		message("%s", &statmsg[4]);
1876 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1877 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1878 	}
1879 	else
1880 	{
1881 		char mbuf[8];
1882 
1883 		Errors++;
1884 		sprintf(mbuf, "%.3s %%s", statmsg);
1885 		usrerr(mbuf, &statmsg[4]);
1886 	}
1887 
1888 	/*
1889 	**  Final cleanup.
1890 	**	Log a record of the transaction.  Compute the new
1891 	**	ExitStat -- if we already had an error, stick with
1892 	**	that.
1893 	*/
1894 
1895 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1896 		logdelivery(m, mci, &statmsg[4], ctladdr, xstart, e);
1897 
1898 	if (tTd(11, 2))
1899 		printf("giveresponse: stat=%d, e->e_message=%s\n",
1900 			stat, e->e_message == NULL ? "<NULL>" : e->e_message);
1901 
1902 	if (stat != EX_TEMPFAIL)
1903 		setstat(stat);
1904 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1905 	{
1906 		if (e->e_message != NULL)
1907 			free(e->e_message);
1908 		e->e_message = newstr(&statmsg[4]);
1909 	}
1910 	errno = 0;
1911 #if NAMED_BIND
1912 	h_errno = 0;
1913 #endif
1914 }
1915 /*
1916 **  LOGDELIVERY -- log the delivery in the system log
1917 **
1918 **	Care is taken to avoid logging lines that are too long, because
1919 **	some versions of syslog have an unfortunate proclivity for core
1920 **	dumping.  This is a hack, to be sure, that is at best empirical.
1921 **
1922 **	Parameters:
1923 **		m -- the mailer info.  Can be NULL for initial queue.
1924 **		mci -- the mailer connection info -- can be NULL if the
1925 **			log is occuring when no connection is active.
1926 **		stat -- the message to print for the status.
1927 **		ctladdr -- the controlling address for the to list.
1928 **		xstart -- the transaction start time, used for
1929 **			computing transaction delay.
1930 **		e -- the current envelope.
1931 **
1932 **	Returns:
1933 **		none
1934 **
1935 **	Side Effects:
1936 **		none
1937 */
1938 
1939 logdelivery(m, mci, stat, ctladdr, xstart, e)
1940 	MAILER *m;
1941 	register MCI *mci;
1942 	char *stat;
1943 	ADDRESS *ctladdr;
1944 	time_t xstart;
1945 	register ENVELOPE *e;
1946 {
1947 # ifdef LOG
1948 	register char *bp;
1949 	register char *p;
1950 	int l;
1951 	char buf[512];
1952 
1953 #  if (SYSLOG_BUFSIZE) >= 256
1954 	bp = buf;
1955 	if (ctladdr != NULL)
1956 	{
1957 		strcpy(bp, ", ctladdr=");
1958 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
1959 		bp += strlen(bp);
1960 		if (bitset(QGOODUID, ctladdr->q_flags))
1961 		{
1962 			(void) sprintf(bp, " (%d/%d)",
1963 					ctladdr->q_uid, ctladdr->q_gid);
1964 			bp += strlen(bp);
1965 		}
1966 	}
1967 
1968 	sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1969 	bp += strlen(bp);
1970 
1971 	if (xstart != (time_t) 0)
1972 	{
1973 		sprintf(bp, ", xdelay=%s", pintvl(curtime() - xstart, TRUE));
1974 		bp += strlen(bp);
1975 	}
1976 
1977 	if (m != NULL)
1978 	{
1979 		(void) strcpy(bp, ", mailer=");
1980 		(void) strcat(bp, m->m_name);
1981 		bp += strlen(bp);
1982 	}
1983 
1984 	if (mci != NULL && mci->mci_host != NULL)
1985 	{
1986 # ifdef DAEMON
1987 		extern SOCKADDR CurHostAddr;
1988 # endif
1989 
1990 		(void) strcpy(bp, ", relay=");
1991 		(void) strcat(bp, mci->mci_host);
1992 
1993 # ifdef DAEMON
1994 		(void) strcat(bp, " [");
1995 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1996 		(void) strcat(bp, "]");
1997 # endif
1998 	}
1999 	else if (strcmp(stat, "queued") != 0)
2000 	{
2001 		char *p = macvalue('h', e);
2002 
2003 		if (p != NULL && p[0] != '\0')
2004 		{
2005 			(void) strcpy(bp, ", relay=");
2006 			(void) strcat(bp, p);
2007 		}
2008 	}
2009 	bp += strlen(bp);
2010 
2011 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
2012 #if (STATLEN) < 63
2013 # undef STATLEN
2014 # define STATLEN	63
2015 #endif
2016 #if (STATLEN) > 203
2017 # undef STATLEN
2018 # define STATLEN	203
2019 #endif
2020 
2021 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
2022 	{
2023 		/* desperation move -- truncate data */
2024 		bp = buf + sizeof buf - ((STATLEN) + 17);
2025 		strcpy(bp, "...");
2026 		bp += 3;
2027 	}
2028 
2029 	(void) strcpy(bp, ", stat=");
2030 	bp += strlen(bp);
2031 
2032 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
2033 
2034 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
2035 	p = e->e_to;
2036 	while (strlen(p) >= l)
2037 	{
2038 		register char *q = strchr(p + l, ',');
2039 
2040 		if (q == NULL)
2041 			break;
2042 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
2043 			e->e_id, ++q - p, p, buf);
2044 		p = q;
2045 	}
2046 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
2047 
2048 #  else		/* we have a very short log buffer size */
2049 
2050 	l = SYSLOG_BUFSIZE - 85;
2051 	p = e->e_to;
2052 	while (strlen(p) >= l)
2053 	{
2054 		register char *q = strchr(p + l, ',');
2055 
2056 		if (q == NULL)
2057 			break;
2058 		syslog(LOG_INFO, "%s: to=%.*s [more]",
2059 			e->e_id, ++q - p, p);
2060 		p = q;
2061 	}
2062 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
2063 
2064 	if (ctladdr != NULL)
2065 	{
2066 		bp = buf;
2067 		strcpy(buf, "ctladdr=");
2068 		bp += strlen(buf);
2069 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
2070 		bp += strlen(buf);
2071 		if (bitset(QGOODUID, ctladdr->q_flags))
2072 		{
2073 			(void) sprintf(bp, " (%d/%d)",
2074 					ctladdr->q_uid, ctladdr->q_gid);
2075 			bp += strlen(bp);
2076 		}
2077 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2078 	}
2079 	bp = buf;
2080 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
2081 	bp += strlen(bp);
2082 	if (xstart != (time_t) 0)
2083 	{
2084 		sprintf(bp, ", xdelay=%s", pintvl(curtime() - xstart, TRUE));
2085 		bp += strlen(bp);
2086 	}
2087 
2088 	if (m != NULL)
2089 	{
2090 		sprintf(bp, ", mailer=%s", m->m_name);
2091 		bp += strlen(bp);
2092 	}
2093 	syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2094 
2095 	buf[0] = '\0';
2096 	if (mci != NULL && mci->mci_host != NULL)
2097 	{
2098 # ifdef DAEMON
2099 		extern SOCKADDR CurHostAddr;
2100 # endif
2101 
2102 		sprintf(buf, "relay=%s", mci->mci_host);
2103 
2104 # ifdef DAEMON
2105 		(void) strcat(buf, " [");
2106 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
2107 		(void) strcat(buf, "]");
2108 # endif
2109 	}
2110 	else if (strcmp(stat, "queued") != 0)
2111 	{
2112 		char *p = macvalue('h', e);
2113 
2114 		if (p != NULL && p[0] != '\0')
2115 			sprintf(buf, "relay=%s", p);
2116 	}
2117 	if (buf[0] != '\0')
2118 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2119 
2120 	syslog(LOG_INFO, "%s: stat=%s", e->e_id, shortenstring(stat, 63));
2121 #  endif /* short log buffer */
2122 # endif /* LOG */
2123 }
2124 /*
2125 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
2126 **
2127 **	This can be made an arbitrary message separator by changing $l
2128 **
2129 **	One of the ugliest hacks seen by human eyes is contained herein:
2130 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
2131 **	does a well-meaning programmer such as myself have to deal with
2132 **	this kind of antique garbage????
2133 **
2134 **	Parameters:
2135 **		mci -- the connection information.
2136 **		e -- the envelope.
2137 **
2138 **	Returns:
2139 **		none
2140 **
2141 **	Side Effects:
2142 **		outputs some text to fp.
2143 */
2144 
2145 putfromline(mci, e)
2146 	register MCI *mci;
2147 	ENVELOPE *e;
2148 {
2149 	char *template = "\201l\n";
2150 	char buf[MAXLINE];
2151 
2152 	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
2153 		return;
2154 
2155 # ifdef UGLYUUCP
2156 	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
2157 	{
2158 		char *bang;
2159 		char xbuf[MAXLINE];
2160 
2161 		expand("\201g", buf, sizeof buf, e);
2162 		bang = strchr(buf, '!');
2163 		if (bang == NULL)
2164 		{
2165 			errno = 0;
2166 			syserr("554 No ! in UUCP From address! (%s given)", buf);
2167 		}
2168 		else
2169 		{
2170 			*bang++ = '\0';
2171 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
2172 			template = xbuf;
2173 		}
2174 	}
2175 # endif /* UGLYUUCP */
2176 	expand(template, buf, sizeof buf, e);
2177 	putxline(buf, mci, FALSE);
2178 }
2179 /*
2180 **  PUTBODY -- put the body of a message.
2181 **
2182 **	Parameters:
2183 **		mci -- the connection information.
2184 **		e -- the envelope to put out.
2185 **		separator -- if non-NULL, a message separator that must
2186 **			not be permitted in the resulting message.
2187 **
2188 **	Returns:
2189 **		none.
2190 **
2191 **	Side Effects:
2192 **		The message is written onto fp.
2193 */
2194 
2195 /* values for output state variable */
2196 #define OS_HEAD		0	/* at beginning of line */
2197 #define OS_CR		1	/* read a carriage return */
2198 #define OS_INLINE	2	/* putting rest of line */
2199 
2200 putbody(mci, e, separator)
2201 	register MCI *mci;
2202 	register ENVELOPE *e;
2203 	char *separator;
2204 {
2205 	char buf[MAXLINE];
2206 
2207 	/*
2208 	**  Output the body of the message
2209 	*/
2210 
2211 	if (e->e_dfp == NULL && e->e_df != NULL)
2212 	{
2213 		e->e_dfp = fopen(e->e_df, "r");
2214 		if (e->e_dfp == NULL)
2215 			syserr("putbody: Cannot open %s for %s from %s",
2216 			e->e_df, e->e_to, e->e_from.q_paddr);
2217 	}
2218 	if (e->e_dfp == NULL)
2219 	{
2220 		if (bitset(MCIF_INHEADER, mci->mci_flags))
2221 		{
2222 			putline("", mci);
2223 			mci->mci_flags &= ~MCIF_INHEADER;
2224 		}
2225 		putline("<<< No Message Collected >>>", mci);
2226 		goto endofmessage;
2227 	}
2228 	if (e->e_dfino == (ino_t) 0)
2229 	{
2230 		struct stat stbuf;
2231 
2232 		if (fstat(fileno(e->e_dfp), &stbuf) < 0)
2233 			e->e_dfino = -1;
2234 		else
2235 		{
2236 			e->e_dfdev = stbuf.st_dev;
2237 			e->e_dfino = stbuf.st_ino;
2238 		}
2239 	}
2240 	rewind(e->e_dfp);
2241 
2242 	if (bitset(MCIF_CVT8TO7, mci->mci_flags))
2243 	{
2244 		char *boundaries[MAXMIMENESTING + 1];
2245 
2246 		/*
2247 		**  Do 8 to 7 bit MIME conversion.
2248 		*/
2249 
2250 		/* make sure it looks like a MIME message */
2251 		if (hvalue("MIME-Version", e->e_header) == NULL)
2252 			putline("MIME-Version: 1.0", mci);
2253 
2254 		if (hvalue("Content-Type", e->e_header) == NULL)
2255 		{
2256 			sprintf(buf, "Content-Type: text/plain; charset=%s",
2257 				defcharset(e));
2258 			putline(buf, mci);
2259 		}
2260 
2261 		/* now do the hard work */
2262 		boundaries[0] = NULL;
2263 		mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER);
2264 	}
2265 	else
2266 	{
2267 		int ostate;
2268 		register char *bp;
2269 		register char *pbp;
2270 		register int c;
2271 		int padc;
2272 		char *buflim;
2273 		int pos = 0;
2274 		char peekbuf[10];
2275 
2276 		/* we can pass it through unmodified */
2277 		if (bitset(MCIF_INHEADER, mci->mci_flags))
2278 		{
2279 			putline("", mci);
2280 			mci->mci_flags &= ~MCIF_INHEADER;
2281 		}
2282 
2283 		/* determine end of buffer; allow for short mailer lines */
2284 		buflim = &buf[sizeof buf - 1];
2285 		if (mci->mci_mailer->m_linelimit > 0 &&
2286 		    mci->mci_mailer->m_linelimit < sizeof buf - 1)
2287 			buflim = &buf[mci->mci_mailer->m_linelimit - 1];
2288 
2289 		/* copy temp file to output with mapping */
2290 		ostate = OS_HEAD;
2291 		bp = buf;
2292 		pbp = peekbuf;
2293 		while (!ferror(mci->mci_out))
2294 		{
2295 			register char *xp;
2296 
2297 			if (pbp > peekbuf)
2298 				c = *--pbp;
2299 			else if ((c = fgetc(e->e_dfp)) == EOF)
2300 				break;
2301 			if (bitset(MCIF_7BIT, mci->mci_flags))
2302 				c &= 0x7f;
2303 			switch (ostate)
2304 			{
2305 			  case OS_HEAD:
2306 				if (c != '\r' && c != '\n' && bp < buflim)
2307 				{
2308 					*bp++ = c;
2309 					break;
2310 				}
2311 
2312 				/* check beginning of line for special cases */
2313 				*bp = '\0';
2314 				pos = 0;
2315 				padc = EOF;
2316 				if (buf[0] == 'F' &&
2317 				    bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
2318 				    strncmp(buf, "From ", 5) == 0)
2319 				{
2320 					padc = '>';
2321 				}
2322 				if (buf[0] == '-' && buf[1] == '-' &&
2323 				    separator != NULL)
2324 				{
2325 					/* possible separator */
2326 					int sl = strlen(separator);
2327 
2328 					if (strncmp(&buf[2], separator, sl) == 0)
2329 						padc = ' ';
2330 				}
2331 				if (buf[0] == '.' &&
2332 				    bitnset(M_XDOT, mci->mci_mailer->m_flags))
2333 				{
2334 					padc = '.';
2335 				}
2336 
2337 				/* now copy out saved line */
2338 				if (TrafficLogFile != NULL)
2339 				{
2340 					fprintf(TrafficLogFile, "%05d >>> ", getpid());
2341 					if (padc != EOF)
2342 						fputc(padc, TrafficLogFile);
2343 					for (xp = buf; xp < bp; xp++)
2344 						fputc(*xp, TrafficLogFile);
2345 					if (c == '\n')
2346 						fputs(mci->mci_mailer->m_eol,
2347 						      TrafficLogFile);
2348 				}
2349 				if (padc != EOF)
2350 				{
2351 					fputc(padc, mci->mci_out);
2352 					pos++;
2353 				}
2354 				for (xp = buf; xp < bp; xp++)
2355 					fputc(*xp, mci->mci_out);
2356 				if (c == '\n')
2357 				{
2358 					fputs(mci->mci_mailer->m_eol,
2359 					      mci->mci_out);
2360 					pos = 0;
2361 				}
2362 				else
2363 				{
2364 					pos += bp - buf;
2365 					if (c != '\r')
2366 						*pbp++ = c;
2367 				}
2368 				bp = buf;
2369 
2370 				/* determine next state */
2371 				if (c == '\n')
2372 					ostate = OS_HEAD;
2373 				else if (c == '\r')
2374 					ostate = OS_CR;
2375 				else
2376 					ostate = OS_INLINE;
2377 				continue;
2378 
2379 			  case OS_CR:
2380 				if (c == '\n')
2381 				{
2382 					/* got CRLF */
2383 					fputs(mci->mci_mailer->m_eol, mci->mci_out);
2384 					if (TrafficLogFile != NULL)
2385 					{
2386 						fputs(mci->mci_mailer->m_eol,
2387 						      TrafficLogFile);
2388 					}
2389 					ostate = OS_HEAD;
2390 					continue;
2391 				}
2392 
2393 				/* had a naked carriage return */
2394 				*pbp++ = c;
2395 				c = '\r';
2396 				goto putch;
2397 
2398 			  case OS_INLINE:
2399 				if (c == '\r')
2400 				{
2401 					ostate = OS_CR;
2402 					continue;
2403 				}
2404 putch:
2405 				if (mci->mci_mailer->m_linelimit > 0 &&
2406 				    pos > mci->mci_mailer->m_linelimit &&
2407 				    c != '\n')
2408 				{
2409 					putc('!', mci->mci_out);
2410 					fputs(mci->mci_mailer->m_eol, mci->mci_out);
2411 					if (TrafficLogFile != NULL)
2412 					{
2413 						fprintf(TrafficLogFile, "!%s",
2414 							mci->mci_mailer->m_eol);
2415 					}
2416 					ostate = OS_HEAD;
2417 					*pbp++ = c;
2418 					continue;
2419 				}
2420 				if (TrafficLogFile != NULL)
2421 					fputc(c, TrafficLogFile);
2422 				putc(c, mci->mci_out);
2423 				pos++;
2424 				ostate = c == '\n' ? OS_HEAD : OS_INLINE;
2425 				break;
2426 			}
2427 		}
2428 	}
2429 
2430 	if (ferror(e->e_dfp))
2431 	{
2432 		syserr("putbody: %s: read error", e->e_df);
2433 		ExitStat = EX_IOERR;
2434 	}
2435 
2436 endofmessage:
2437 	/* some mailers want extra blank line at end of message */
2438 	if (bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
2439 	    buf[0] != '\0' && buf[0] != '\n')
2440 		putline("", mci);
2441 
2442 	(void) fflush(mci->mci_out);
2443 	if (ferror(mci->mci_out) && errno != EPIPE)
2444 	{
2445 		syserr("putbody: write error");
2446 		ExitStat = EX_IOERR;
2447 	}
2448 	errno = 0;
2449 }
2450 /*
2451 **  MAILFILE -- Send a message to a file.
2452 **
2453 **	If the file has the setuid/setgid bits set, but NO execute
2454 **	bits, sendmail will try to become the owner of that file
2455 **	rather than the real user.  Obviously, this only works if
2456 **	sendmail runs as root.
2457 **
2458 **	This could be done as a subordinate mailer, except that it
2459 **	is used implicitly to save messages in ~/dead.letter.  We
2460 **	view this as being sufficiently important as to include it
2461 **	here.  For example, if the system is dying, we shouldn't have
2462 **	to create another process plus some pipes to save the message.
2463 **
2464 **	Parameters:
2465 **		filename -- the name of the file to send to.
2466 **		ctladdr -- the controlling address header -- includes
2467 **			the userid/groupid to be when sending.
2468 **
2469 **	Returns:
2470 **		The exit code associated with the operation.
2471 **
2472 **	Side Effects:
2473 **		none.
2474 */
2475 
2476 mailfile(filename, ctladdr, e)
2477 	char *filename;
2478 	ADDRESS *ctladdr;
2479 	register ENVELOPE *e;
2480 {
2481 	register FILE *f;
2482 	register int pid = -1;
2483 	int mode;
2484 
2485 	if (tTd(11, 1))
2486 	{
2487 		printf("mailfile %s\n  ctladdr=", filename);
2488 		printaddr(ctladdr, FALSE);
2489 	}
2490 
2491 	if (e->e_xfp != NULL)
2492 		fflush(e->e_xfp);
2493 
2494 	/*
2495 	**  Fork so we can change permissions here.
2496 	**	Note that we MUST use fork, not vfork, because of
2497 	**	the complications of calling subroutines, etc.
2498 	*/
2499 
2500 	DOFORK(fork);
2501 
2502 	if (pid < 0)
2503 		return (EX_OSERR);
2504 	else if (pid == 0)
2505 	{
2506 		/* child -- actually write to file */
2507 		struct stat stb;
2508 		struct stat fsb;
2509 		MCI mcibuf;
2510 		int oflags = O_WRONLY|O_APPEND;
2511 
2512 		if (e->e_lockfp != NULL)
2513 		{
2514 			fclose(e->e_lockfp);
2515 			e->e_lockfp = NULL;
2516 		}
2517 
2518 		(void) setsignal(SIGINT, SIG_DFL);
2519 		(void) setsignal(SIGHUP, SIG_DFL);
2520 		(void) setsignal(SIGTERM, SIG_DFL);
2521 		(void) umask(OldUmask);
2522 
2523 #ifdef HASLSTAT
2524 		if ((SafeFileEnv != NULL ? lstat(filename, &stb)
2525 					 : stat(filename, &stb)) < 0)
2526 #else
2527 		if (stat(filename, &stb) < 0)
2528 #endif
2529 		{
2530 			stb.st_mode = FileMode;
2531 			oflags |= O_CREAT|O_EXCL;
2532 		}
2533 		else if (bitset(0111, stb.st_mode) || stb.st_nlink != 1 ||
2534 			 (SafeFileEnv != NULL && !S_ISREG(stb.st_mode)))
2535 			exit(EX_CANTCREAT);
2536 		mode = stb.st_mode;
2537 
2538 		/* limit the errors to those actually caused in the child */
2539 		errno = 0;
2540 		ExitStat = EX_OK;
2541 
2542 		if (ctladdr != NULL)
2543 		{
2544 			/* ignore setuid and setgid bits */
2545 			mode &= ~(S_ISGID|S_ISUID);
2546 		}
2547 
2548 		/* we have to open the dfile BEFORE setuid */
2549 		if (e->e_dfp == NULL && e->e_df != NULL)
2550 		{
2551 			e->e_dfp = fopen(e->e_df, "r");
2552 			if (e->e_dfp == NULL)
2553 			{
2554 				syserr("mailfile: Cannot open %s for %s from %s",
2555 					e->e_df, e->e_to, e->e_from.q_paddr);
2556 			}
2557 		}
2558 
2559 		if (SafeFileEnv != NULL && SafeFileEnv[0] != NULL)
2560 		{
2561 			int i;
2562 
2563 			if (chroot(SafeFileEnv) < 0)
2564 			{
2565 				syserr("mailfile: Cannot chroot(%s)",
2566 					SafeFileEnv);
2567 				exit(EX_CANTCREAT);
2568 			}
2569 			i = strlen(SafeFileEnv);
2570 			if (strncmp(SafeFileEnv, filename, i) == 0)
2571 				filename += i;
2572 		}
2573 		if (chdir("/") < 0)
2574 			syserr("mailfile: cannot chdir(/)");
2575 
2576 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
2577 		{
2578 			if (ctladdr != NULL && ctladdr->q_uid != 0)
2579 				(void) initgroups(ctladdr->q_ruser ?
2580 					ctladdr->q_ruser : ctladdr->q_user,
2581 					ctladdr->q_gid);
2582 			else if (FileMailer != NULL && FileMailer->m_gid != 0)
2583 				(void) initgroups(DefUser, FileMailer->m_gid);
2584 			else
2585 				(void) initgroups(DefUser, DefGid);
2586 		}
2587 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
2588 		{
2589 			if (ctladdr != NULL && ctladdr->q_uid != 0)
2590 				(void) setuid(ctladdr->q_uid);
2591 			else if (FileMailer != NULL && FileMailer->m_uid != 0)
2592 				(void) setuid(FileMailer->m_uid);
2593 			else
2594 				(void) setuid(DefUid);
2595 		}
2596 		FileName = filename;
2597 		LineNumber = 0;
2598 		f = dfopen(filename, oflags, FileMode);
2599 		if (f == NULL)
2600 		{
2601 			message("554 cannot open: %s", errstring(errno));
2602 			exit(EX_CANTCREAT);
2603 		}
2604 		if (fstat(fileno(f), &fsb) < 0 ||
2605 		    (!bitset(O_CREAT, oflags) &&
2606 		     (stb.st_nlink != fsb.st_nlink ||
2607 		      stb.st_dev != fsb.st_dev ||
2608 		      stb.st_ino != fsb.st_ino ||
2609 		      stb.st_uid != fsb.st_uid)))
2610 		{
2611 			message("554 cannot write: file changed after open");
2612 			exit(EX_CANTCREAT);
2613 		}
2614 
2615 		bzero(&mcibuf, sizeof mcibuf);
2616 		mcibuf.mci_mailer = FileMailer;
2617 		mcibuf.mci_out = f;
2618 		if (bitnset(M_7BITS, FileMailer->m_flags))
2619 			mcibuf.mci_flags |= MCIF_7BIT;
2620 
2621 		putfromline(&mcibuf, e);
2622 		(*e->e_puthdr)(&mcibuf, e->e_header, e);
2623 		(*e->e_putbody)(&mcibuf, e, NULL);
2624 		putline("\n", &mcibuf);
2625 		if (ferror(f))
2626 		{
2627 			message("451 I/O error: %s", errstring(errno));
2628 			setstat(EX_IOERR);
2629 		}
2630 		(void) xfclose(f, "mailfile", filename);
2631 		(void) fflush(stdout);
2632 
2633 		/* reset ISUID & ISGID bits for paranoid systems */
2634 		(void) chmod(filename, (int) stb.st_mode);
2635 		exit(ExitStat);
2636 		/*NOTREACHED*/
2637 	}
2638 	else
2639 	{
2640 		/* parent -- wait for exit status */
2641 		int st;
2642 
2643 		st = waitfor(pid);
2644 		if (WIFEXITED(st))
2645 			return (WEXITSTATUS(st));
2646 		else
2647 		{
2648 			syserr("child died on signal %d", st);
2649 			return (EX_UNAVAILABLE);
2650 		}
2651 		/*NOTREACHED*/
2652 	}
2653 }
2654 /*
2655 **  HOSTSIGNATURE -- return the "signature" for a host.
2656 **
2657 **	The signature describes how we are going to send this -- it
2658 **	can be just the hostname (for non-Internet hosts) or can be
2659 **	an ordered list of MX hosts.
2660 **
2661 **	Parameters:
2662 **		m -- the mailer describing this host.
2663 **		host -- the host name.
2664 **		e -- the current envelope.
2665 **
2666 **	Returns:
2667 **		The signature for this host.
2668 **
2669 **	Side Effects:
2670 **		Can tweak the symbol table.
2671 */
2672 
2673 char *
2674 hostsignature(m, host, e)
2675 	register MAILER *m;
2676 	char *host;
2677 	ENVELOPE *e;
2678 {
2679 	register char *p;
2680 	register STAB *s;
2681 	int i;
2682 	int len;
2683 #if NAMED_BIND
2684 	int nmx;
2685 	auto int rcode;
2686 	char *hp;
2687 	char *endp;
2688 	int oldoptions = _res.options;
2689 	char *mxhosts[MAXMXHOSTS + 1];
2690 #endif
2691 
2692 	/*
2693 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2694 	*/
2695 
2696 	p = m->m_mailer;
2697 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2698 	{
2699 		/* just an ordinary mailer */
2700 		return host;
2701 	}
2702 
2703 	/*
2704 	**  Look it up in the symbol table.
2705 	*/
2706 
2707 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2708 	if (s->s_hostsig != NULL)
2709 		return s->s_hostsig;
2710 
2711 	/*
2712 	**  Not already there -- create a signature.
2713 	*/
2714 
2715 #if NAMED_BIND
2716 	if (ConfigLevel < 2)
2717 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2718 
2719 	for (hp = host; hp != NULL; hp = endp)
2720 	{
2721 		endp = strchr(hp, ':');
2722 		if (endp != NULL)
2723 			*endp = '\0';
2724 
2725 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2726 
2727 		if (nmx <= 0)
2728 		{
2729 			register MCI *mci;
2730 
2731 			/* update the connection info for this host */
2732 			mci = mci_get(hp, m);
2733 			mci->mci_exitstat = rcode;
2734 			mci->mci_errno = errno;
2735 			mci->mci_herrno = h_errno;
2736 
2737 			/* and return the original host name as the signature */
2738 			nmx = 1;
2739 			mxhosts[0] = hp;
2740 		}
2741 
2742 		len = 0;
2743 		for (i = 0; i < nmx; i++)
2744 		{
2745 			len += strlen(mxhosts[i]) + 1;
2746 		}
2747 		if (s->s_hostsig != NULL)
2748 			len += strlen(s->s_hostsig) + 1;
2749 		p = xalloc(len);
2750 		if (s->s_hostsig != NULL)
2751 		{
2752 			(void) strcpy(p, s->s_hostsig);
2753 			free(s->s_hostsig);
2754 			s->s_hostsig = p;
2755 			p += strlen(p);
2756 			*p++ = ':';
2757 		}
2758 		else
2759 			s->s_hostsig = p;
2760 		for (i = 0; i < nmx; i++)
2761 		{
2762 			if (i != 0)
2763 				*p++ = ':';
2764 			strcpy(p, mxhosts[i]);
2765 			p += strlen(p);
2766 		}
2767 		if (endp != NULL)
2768 			*endp++ = ':';
2769 	}
2770 	makelower(s->s_hostsig);
2771 	if (ConfigLevel < 2)
2772 		_res.options = oldoptions;
2773 #else
2774 	/* not using BIND -- the signature is just the host name */
2775 	s->s_hostsig = host;
2776 #endif
2777 	if (tTd(17, 1))
2778 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2779 	return s->s_hostsig;
2780 }
2781 /*
2782 **  SETSTATUS -- set the address status for return messages
2783 **
2784 **	Parameters:
2785 **		a -- the address to set.
2786 **		msg -- the text of the message, which must be in standard
2787 **			SMTP form (3 digits, a space, and a message).
2788 **
2789 **	Returns:
2790 **		none.
2791 */
2792 
2793 setstatus(a, msg)
2794 	register ADDRESS *a;
2795 	char *msg;
2796 {
2797 	char buf[MAXLINE];
2798 
2799 	if (a->q_rstatus != NULL)
2800 		free(a->q_rstatus);
2801 	if (strlen(msg) > 4)
2802 	{
2803 		register char *p, *q;
2804 		int parenlev = 0;
2805 
2806 		strncpy(buf, msg, 4);
2807 		p = &buf[4];
2808 		*p++ = '(';
2809 		for (q = &msg[4]; *q != '\0'; q++)
2810 		{
2811 			switch (*q)
2812 			{
2813 			  case '(':
2814 				parenlev++;
2815 				break;
2816 
2817 			  case ')':
2818 				if (parenlev > 0)
2819 					parenlev--;
2820 				else
2821 					*p++ = '\\';
2822 				break;
2823 			}
2824 			*p++ = *q;
2825 		}
2826 		while (parenlev-- >= 0)
2827 			*p++ = ')';
2828 		*p++ = '\0';
2829 		msg = buf;
2830 	}
2831 	a->q_rstatus = newstr(msg);
2832 }
2833