1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)deliver.c	6.64 (Berkeley) 04/19/93";
11 #endif /* not lint */
12 
13 #include "sendmail.h"
14 #include <signal.h>
15 #include <sys/stat.h>
16 #include <netdb.h>
17 #include <errno.h>
18 #ifdef NAMED_BIND
19 #include <arpa/nameser.h>
20 #include <resolv.h>
21 #endif
22 
23 /*
24 **  SENDALL -- actually send all the messages.
25 **
26 **	Parameters:
27 **		e -- the envelope to send.
28 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
29 **			the current e->e_sendmode.
30 **
31 **	Returns:
32 **		none.
33 **
34 **	Side Effects:
35 **		Scans the send lists and sends everything it finds.
36 **		Delivers any appropriate error messages.
37 **		If we are running in a non-interactive mode, takes the
38 **			appropriate action.
39 */
40 
41 sendall(e, mode)
42 	ENVELOPE *e;
43 	char mode;
44 {
45 	register ADDRESS *q;
46 	char *owner;
47 	int otherowners;
48 	register ENVELOPE *ee;
49 	ENVELOPE *splitenv = NULL;
50 	bool announcequeueup;
51 
52 	/* determine actual delivery mode */
53 	if (mode == SM_DEFAULT)
54 	{
55 		extern bool shouldqueue();
56 
57 		mode = e->e_sendmode;
58 		if (mode != SM_VERIFY &&
59 		    shouldqueue(e->e_msgpriority, e->e_ctime))
60 			mode = SM_QUEUE;
61 		announcequeueup = mode == SM_QUEUE;
62 	}
63 	else
64 		announcequeueup = FALSE;
65 
66 	if (tTd(13, 1))
67 	{
68 		printf("\nSENDALL: mode %c, e_from ", mode);
69 		printaddr(&e->e_from, FALSE);
70 		printf("sendqueue:\n");
71 		printaddr(e->e_sendqueue, TRUE);
72 	}
73 
74 	/*
75 	**  Do any preprocessing necessary for the mode we are running.
76 	**	Check to make sure the hop count is reasonable.
77 	**	Delete sends to the sender in mailing lists.
78 	*/
79 
80 	CurEnv = e;
81 
82 	if (e->e_hopcount > MaxHopCount)
83 	{
84 		errno = 0;
85 		syserr("554 too many hops %d (%d max): from %s, to %s",
86 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
87 			e->e_sendqueue->q_paddr);
88 		return;
89 	}
90 
91 	if (!MeToo)
92 	{
93 		extern ADDRESS *recipient();
94 
95 		if (tTd(13, 5))
96 		{
97 			printf("sendall: QDONTSEND ");
98 			printaddr(&e->e_from, FALSE);
99 		}
100 		e->e_from.q_flags |= QDONTSEND;
101 		(void) recipient(&e->e_from, &e->e_sendqueue, e);
102 	}
103 
104 	/*
105 	**  Handle alias owners.
106 	**
107 	**	We scan up the q_alias chain looking for owners.
108 	**	We discard owners that are the same as the return path.
109 	*/
110 
111 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
112 	{
113 		register struct address *a;
114 
115 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
116 			continue;
117 		if (a != NULL)
118 			q->q_owner = a->q_owner;
119 
120 		if (q->q_owner != NULL &&
121 		    !bitset(QDONTSEND, q->q_flags) &&
122 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
123 			q->q_owner = NULL;
124 	}
125 
126 	owner = "";
127 	otherowners = 1;
128 	while (owner != NULL && otherowners > 0)
129 	{
130 		owner = NULL;
131 		otherowners = 0;
132 
133 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
134 		{
135 			if (bitset(QDONTSEND, q->q_flags))
136 				continue;
137 
138 			if (q->q_owner != NULL)
139 			{
140 				if (owner == NULL)
141 					owner = q->q_owner;
142 				else if (owner != q->q_owner)
143 				{
144 					if (strcmp(owner, q->q_owner) == 0)
145 					{
146 						/* make future comparisons cheap */
147 						q->q_owner = owner;
148 					}
149 					else
150 					{
151 						otherowners++;
152 					}
153 					owner = q->q_owner;
154 				}
155 			}
156 			else
157 			{
158 				otherowners++;
159 			}
160 		}
161 
162 		if (owner != NULL && otherowners > 0)
163 		{
164 			extern HDR *copyheader();
165 			extern ADDRESS *copyqueue();
166 
167 			/*
168 			**  Split this envelope into two.
169 			*/
170 
171 			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
172 			*ee = *e;
173 			ee->e_id = NULL;
174 			(void) queuename(ee, '\0');
175 
176 			if (tTd(13, 1))
177 				printf("sendall: split %s into %s\n",
178 					e->e_id, ee->e_id);
179 
180 			ee->e_header = copyheader(e->e_header);
181 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
182 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
183 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS);
184 			setsender(owner, ee, NULL, TRUE);
185 			if (tTd(13, 5))
186 			{
187 				printf("sendall(split): QDONTSEND ");
188 				printaddr(&ee->e_from, FALSE);
189 			}
190 			ee->e_from.q_flags |= QDONTSEND;
191 			ee->e_dfp = NULL;
192 			ee->e_xfp = NULL;
193 			ee->e_lockfp = NULL;
194 			ee->e_df = NULL;
195 			ee->e_errormode = EM_MAIL;
196 			ee->e_sibling = splitenv;
197 			splitenv = ee;
198 
199 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
200 				if (q->q_owner == owner)
201 					q->q_flags |= QDONTSEND;
202 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
203 				if (q->q_owner != owner)
204 					q->q_flags |= QDONTSEND;
205 
206 			if (e->e_df != NULL && mode != SM_VERIFY)
207 			{
208 				ee->e_dfp = NULL;
209 				ee->e_df = newstr(queuename(ee, 'd'));
210 				if (link(e->e_df, ee->e_df) < 0)
211 				{
212 					syserr("sendall: link(%s, %s)",
213 						e->e_df, ee->e_df);
214 				}
215 			}
216 
217 			if (mode != SM_VERIFY)
218 				openxscript(ee);
219 #ifdef LOG
220 			if (LogLevel > 4)
221 				syslog(LOG_INFO, "%s: clone %s",
222 					ee->e_id, e->e_id);
223 #endif
224 		}
225 	}
226 
227 	if (owner != NULL)
228 	{
229 		setsender(owner, e, NULL, TRUE);
230 		if (tTd(13, 5))
231 		{
232 			printf("sendall(owner): QDONTSEND ");
233 			printaddr(&e->e_from, FALSE);
234 		}
235 		e->e_from.q_flags |= QDONTSEND;
236 		e->e_errormode = EM_MAIL;
237 	}
238 
239 # ifdef QUEUE
240 	if ((mode == SM_QUEUE || mode == SM_FORK ||
241 	     (mode != SM_VERIFY && SuperSafe)) &&
242 	    !bitset(EF_INQUEUE, e->e_flags))
243 	{
244 		/* be sure everything is instantiated in the queue */
245 		queueup(e, TRUE, announcequeueup);
246 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
247 			queueup(ee, TRUE, announcequeueup);
248 	}
249 #endif /* QUEUE */
250 
251 	if (splitenv != NULL)
252 	{
253 		if (tTd(13, 1))
254 		{
255 			printf("\nsendall: Split queue; remaining queue:\n");
256 			printaddr(e->e_sendqueue, TRUE);
257 		}
258 
259 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
260 		{
261 			CurEnv = ee;
262 			sendenvelope(ee, mode);
263 		}
264 
265 		CurEnv = e;
266 	}
267 	sendenvelope(e, mode);
268 
269 	for (; splitenv != NULL; splitenv = splitenv->e_sibling)
270 		dropenvelope(splitenv);
271 }
272 
273 sendenvelope(e, mode)
274 	register ENVELOPE *e;
275 	char mode;
276 {
277 	bool oldverbose;
278 	int pid;
279 	register ADDRESS *q;
280 #ifdef LOCKF
281 	struct flock lfd;
282 #endif
283 
284 	oldverbose = Verbose;
285 	switch (mode)
286 	{
287 	  case SM_VERIFY:
288 		Verbose = TRUE;
289 		break;
290 
291 	  case SM_QUEUE:
292   queueonly:
293 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
294 		return;
295 
296 	  case SM_FORK:
297 		if (e->e_xfp != NULL)
298 			(void) fflush(e->e_xfp);
299 
300 # ifdef LOCKF
301 		/*
302 		**  Since lockf has the interesting semantic that the
303 		**  lock is lost when we fork, we have to risk losing
304 		**  the lock here by closing before the fork, and then
305 		**  trying to get it back in the child.
306 		*/
307 
308 		if (e->e_lockfp != NULL)
309 		{
310 			(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
311 			e->e_lockfp = NULL;
312 		}
313 # endif /* LOCKF */
314 
315 		pid = fork();
316 		if (pid < 0)
317 		{
318 			goto queueonly;
319 		}
320 		else if (pid > 0)
321 		{
322 			/* be sure we leave the temp files to our child */
323 			e->e_id = e->e_df = NULL;
324 # ifndef LOCKF
325 			if (e->e_lockfp != NULL)
326 			{
327 				(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
328 				e->e_lockfp = NULL;
329 			}
330 # endif
331 
332 			/* close any random open files in the envelope */
333 			if (e->e_dfp != NULL)
334 			{
335 				(void) xfclose(e->e_dfp, "sendenvelope", "dfp");
336 				e->e_dfp = NULL;
337 			}
338 			if (e->e_xfp != NULL)
339 			{
340 				(void) xfclose(e->e_xfp, "sendenvelope", "xfp");
341 				e->e_xfp = NULL;
342 			}
343 			return;
344 		}
345 
346 		/* double fork to avoid zombies */
347 		if (fork() > 0)
348 			exit(EX_OK);
349 
350 		/* be sure we are immune from the terminal */
351 		disconnect(FALSE, e);
352 
353 # ifdef LOCKF
354 		/*
355 		**  Now try to get our lock back.
356 		*/
357 
358 		lfd.l_type = F_WRLCK;
359 		lfd.l_whence = lfd.l_start = lfd.l_len = 0;
360 		e->e_lockfp = fopen(queuename(e, 'q'), "r+");
361 		if (e->e_lockfp == NULL ||
362 		    fcntl(fileno(e->e_lockfp), F_SETLK, &lfd) < 0)
363 		{
364 			/* oops....  lost it */
365 			if (tTd(13, 1))
366 				printf("sendenvelope: %s lost lock: lockfp=%x, %s\n",
367 					e->e_id, e->e_lockfp, errstring(errno));
368 
369 # ifdef LOG
370 			if (LogLevel > 29)
371 				syslog(LOG_NOTICE, "%s: lost lock: %m",
372 					e->e_id);
373 # endif /* LOG */
374 			exit(EX_OK);
375 		}
376 # endif /* LOCKF */
377 
378 		/*
379 		**  Close any cached connections.
380 		**
381 		**	We don't send the QUIT protocol because the parent
382 		**	still knows about the connection.
383 		**
384 		**	This should only happen when delivering an error
385 		**	message.
386 		*/
387 
388 		mci_flush(FALSE, NULL);
389 
390 		break;
391 	}
392 
393 	/*
394 	**  Run through the list and send everything.
395 	*/
396 
397 	e->e_nsent = 0;
398 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
399 	{
400 		if (mode == SM_VERIFY)
401 		{
402 			e->e_to = q->q_paddr;
403 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
404 				message("deliverable");
405 		}
406 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
407 		{
408 # ifdef QUEUE
409 			/*
410 			**  Checkpoint the send list every few addresses
411 			*/
412 
413 			if (e->e_nsent >= CheckpointInterval)
414 			{
415 				queueup(e, TRUE, FALSE);
416 				e->e_nsent = 0;
417 			}
418 # endif /* QUEUE */
419 			(void) deliver(e, q);
420 		}
421 	}
422 	Verbose = oldverbose;
423 
424 	/*
425 	**  Now run through and check for errors.
426 	*/
427 
428 	if (mode == SM_VERIFY)
429 	{
430 		return;
431 	}
432 
433 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
434 	{
435 		if (tTd(13, 3))
436 		{
437 			printf("Checking ");
438 			printaddr(q, FALSE);
439 		}
440 
441 		/* only send errors if the message failed */
442 		if (!bitset(QBADADDR, q->q_flags) ||
443 		    bitset(QDONTSEND, q->q_flags))
444 			continue;
445 
446 		e->e_flags |= EF_FATALERRS;
447 
448 		if (q->q_owner == NULL && strcmp(e->e_from.q_paddr, "<>") != 0)
449 			(void) sendtolist(e->e_from.q_paddr, NULL,
450 					  &e->e_errorqueue, e);
451 	}
452 
453 	if (mode == SM_FORK)
454 		finis();
455 }
456 /*
457 **  DOFORK -- do a fork, retrying a couple of times on failure.
458 **
459 **	This MUST be a macro, since after a vfork we are running
460 **	two processes on the same stack!!!
461 **
462 **	Parameters:
463 **		none.
464 **
465 **	Returns:
466 **		From a macro???  You've got to be kidding!
467 **
468 **	Side Effects:
469 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
470 **			pid of child in parent, zero in child.
471 **			-1 on unrecoverable error.
472 **
473 **	Notes:
474 **		I'm awfully sorry this looks so awful.  That's
475 **		vfork for you.....
476 */
477 
478 # define NFORKTRIES	5
479 
480 # ifndef FORK
481 # define FORK	fork
482 # endif
483 
484 # define DOFORK(fORKfN) \
485 {\
486 	register int i;\
487 \
488 	for (i = NFORKTRIES; --i >= 0; )\
489 	{\
490 		pid = fORKfN();\
491 		if (pid >= 0)\
492 			break;\
493 		if (i > 0)\
494 			sleep((unsigned) NFORKTRIES - i);\
495 	}\
496 }
497 /*
498 **  DOFORK -- simple fork interface to DOFORK.
499 **
500 **	Parameters:
501 **		none.
502 **
503 **	Returns:
504 **		pid of child in parent.
505 **		zero in child.
506 **		-1 on error.
507 **
508 **	Side Effects:
509 **		returns twice, once in parent and once in child.
510 */
511 
512 dofork()
513 {
514 	register int pid;
515 
516 	DOFORK(fork);
517 	return (pid);
518 }
519 /*
520 **  DELIVER -- Deliver a message to a list of addresses.
521 **
522 **	This routine delivers to everyone on the same host as the
523 **	user on the head of the list.  It is clever about mailers
524 **	that don't handle multiple users.  It is NOT guaranteed
525 **	that it will deliver to all these addresses however -- so
526 **	deliver should be called once for each address on the
527 **	list.
528 **
529 **	Parameters:
530 **		e -- the envelope to deliver.
531 **		firstto -- head of the address list to deliver to.
532 **
533 **	Returns:
534 **		zero -- successfully delivered.
535 **		else -- some failure, see ExitStat for more info.
536 **
537 **	Side Effects:
538 **		The standard input is passed off to someone.
539 */
540 
541 deliver(e, firstto)
542 	register ENVELOPE *e;
543 	ADDRESS *firstto;
544 {
545 	char *host;			/* host being sent to */
546 	char *user;			/* user being sent to */
547 	char **pvp;
548 	register char **mvp;
549 	register char *p;
550 	register MAILER *m;		/* mailer for this recipient */
551 	ADDRESS *ctladdr;
552 	register MCI *mci;
553 	register ADDRESS *to = firstto;
554 	bool clever = FALSE;		/* running user smtp to this mailer */
555 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
556 	int rcode;			/* response code */
557 	char *firstsig;			/* signature of firstto */
558 	int pid;
559 	char *curhost;
560 	int mpvect[2];
561 	int rpvect[2];
562 	char *pv[MAXPV+1];
563 	char tobuf[TOBUFSIZE];		/* text line of to people */
564 	char buf[MAXNAME];
565 	char rpathbuf[MAXNAME];		/* translated return path */
566 	extern int checkcompat();
567 	extern ADDRESS *getctladdr();
568 	extern char *remotename();
569 	extern char *hostsignature();
570 	extern FILE *fdopen();
571 
572 	errno = 0;
573 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
574 		return (0);
575 
576 #ifdef NAMED_BIND
577 	/* unless interactive, try twice, over a minute */
578 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP) {
579 		_res.retrans = 30;
580 		_res.retry = 2;
581 	}
582 #endif
583 
584 	m = to->q_mailer;
585 	host = to->q_host;
586 	CurEnv = e;			/* just in case */
587 	e->e_statmsg = NULL;
588 
589 	if (tTd(10, 1))
590 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
591 			m->m_mno, host, to->q_user);
592 
593 	/*
594 	**  If this mailer is expensive, and if we don't want to make
595 	**  connections now, just mark these addresses and return.
596 	**	This is useful if we want to batch connections to
597 	**	reduce load.  This will cause the messages to be
598 	**	queued up, and a daemon will come along to send the
599 	**	messages later.
600 	**		This should be on a per-mailer basis.
601 	*/
602 
603 	if (NoConnect && !bitset(EF_QUEUERUN, e->e_flags) &&
604 	    bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
605 	{
606 		for (; to != NULL; to = to->q_next)
607 		{
608 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
609 			    to->q_mailer != m)
610 				continue;
611 			to->q_flags |= QQUEUEUP|QDONTSEND;
612 			e->e_to = to->q_paddr;
613 			message("queued");
614 			if (LogLevel > 8)
615 				logdelivery(m, NULL, "queued", e);
616 		}
617 		e->e_to = NULL;
618 		return (0);
619 	}
620 
621 	/*
622 	**  Do initial argv setup.
623 	**	Insert the mailer name.  Notice that $x expansion is
624 	**	NOT done on the mailer name.  Then, if the mailer has
625 	**	a picky -f flag, we insert it as appropriate.  This
626 	**	code does not check for 'pv' overflow; this places a
627 	**	manifest lower limit of 4 for MAXPV.
628 	**		The from address rewrite is expected to make
629 	**		the address relative to the other end.
630 	*/
631 
632 	/* rewrite from address, using rewriting rules */
633 	rcode = EX_OK;
634 	(void) strcpy(rpathbuf, remotename(e->e_from.q_paddr, m,
635 					   RF_SENDERADDR|RF_CANONICAL,
636 					   &rcode, e));
637 	define('g', rpathbuf, e);		/* translated return path */
638 	define('h', host, e);			/* to host */
639 	Errors = 0;
640 	pvp = pv;
641 	*pvp++ = m->m_argv[0];
642 
643 	/* insert -f or -r flag as appropriate */
644 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
645 	{
646 		if (bitnset(M_FOPT, m->m_flags))
647 			*pvp++ = "-f";
648 		else
649 			*pvp++ = "-r";
650 		*pvp++ = newstr(rpathbuf);
651 	}
652 
653 	/*
654 	**  Append the other fixed parts of the argv.  These run
655 	**  up to the first entry containing "$u".  There can only
656 	**  be one of these, and there are only a few more slots
657 	**  in the pv after it.
658 	*/
659 
660 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
661 	{
662 		/* can't use strchr here because of sign extension problems */
663 		while (*p != '\0')
664 		{
665 			if ((*p++ & 0377) == MACROEXPAND)
666 			{
667 				if (*p == 'u')
668 					break;
669 			}
670 		}
671 
672 		if (*p != '\0')
673 			break;
674 
675 		/* this entry is safe -- go ahead and process it */
676 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
677 		*pvp++ = newstr(buf);
678 		if (pvp >= &pv[MAXPV - 3])
679 		{
680 			syserr("554 Too many parameters to %s before $u", pv[0]);
681 			return (-1);
682 		}
683 	}
684 
685 	/*
686 	**  If we have no substitution for the user name in the argument
687 	**  list, we know that we must supply the names otherwise -- and
688 	**  SMTP is the answer!!
689 	*/
690 
691 	if (*mvp == NULL)
692 	{
693 		/* running SMTP */
694 # ifdef SMTP
695 		clever = TRUE;
696 		*pvp = NULL;
697 # else /* SMTP */
698 		/* oops!  we don't implement SMTP */
699 		syserr("554 SMTP style mailer");
700 		return (EX_SOFTWARE);
701 # endif /* SMTP */
702 	}
703 
704 	/*
705 	**  At this point *mvp points to the argument with $u.  We
706 	**  run through our address list and append all the addresses
707 	**  we can.  If we run out of space, do not fret!  We can
708 	**  always send another copy later.
709 	*/
710 
711 	tobuf[0] = '\0';
712 	e->e_to = tobuf;
713 	ctladdr = NULL;
714 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
715 	for (; to != NULL; to = to->q_next)
716 	{
717 		/* avoid sending multiple recipients to dumb mailers */
718 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
719 			break;
720 
721 		/* if already sent or not for this host, don't send */
722 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
723 		    to->q_mailer != firstto->q_mailer ||
724 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
725 			continue;
726 
727 		/* avoid overflowing tobuf */
728 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
729 			break;
730 
731 		if (tTd(10, 1))
732 		{
733 			printf("\nsend to ");
734 			printaddr(to, FALSE);
735 		}
736 
737 		/* compute effective uid/gid when sending */
738 		if (to->q_mailer == ProgMailer)
739 			ctladdr = getctladdr(to);
740 
741 		user = to->q_user;
742 		e->e_to = to->q_paddr;
743 		if (tTd(10, 5))
744 		{
745 			printf("deliver: QDONTSEND ");
746 			printaddr(to, FALSE);
747 		}
748 		to->q_flags |= QDONTSEND;
749 
750 		/*
751 		**  Check to see that these people are allowed to
752 		**  talk to each other.
753 		*/
754 
755 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
756 		{
757 			NoReturn = TRUE;
758 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
759 			giveresponse(EX_UNAVAILABLE, m, NULL, e);
760 			continue;
761 		}
762 		rcode = checkcompat(to, e);
763 		if (rcode != EX_OK)
764 		{
765 			giveresponse(rcode, m, NULL, e);
766 			continue;
767 		}
768 
769 		/*
770 		**  Strip quote bits from names if the mailer is dumb
771 		**	about them.
772 		*/
773 
774 		if (bitnset(M_STRIPQ, m->m_flags))
775 		{
776 			stripquotes(user);
777 			stripquotes(host);
778 		}
779 
780 		/* hack attack -- delivermail compatibility */
781 		if (m == ProgMailer && *user == '|')
782 			user++;
783 
784 		/*
785 		**  If an error message has already been given, don't
786 		**	bother to send to this address.
787 		**
788 		**	>>>>>>>>>> This clause assumes that the local mailer
789 		**	>> NOTE >> cannot do any further aliasing; that
790 		**	>>>>>>>>>> function is subsumed by sendmail.
791 		*/
792 
793 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
794 			continue;
795 
796 		/* save statistics.... */
797 		markstats(e, to);
798 
799 		/*
800 		**  See if this user name is "special".
801 		**	If the user name has a slash in it, assume that this
802 		**	is a file -- send it off without further ado.  Note
803 		**	that this type of addresses is not processed along
804 		**	with the others, so we fudge on the To person.
805 		*/
806 
807 		if (m == FileMailer)
808 		{
809 			rcode = mailfile(user, getctladdr(to), e);
810 			giveresponse(rcode, m, NULL, e);
811 			if (rcode == EX_OK)
812 				to->q_flags |= QSENT;
813 			continue;
814 		}
815 
816 		/*
817 		**  Address is verified -- add this user to mailer
818 		**  argv, and add it to the print list of recipients.
819 		*/
820 
821 		/* link together the chain of recipients */
822 		to->q_tchain = tochain;
823 		tochain = to;
824 
825 		/* create list of users for error messages */
826 		(void) strcat(tobuf, ",");
827 		(void) strcat(tobuf, to->q_paddr);
828 		define('u', user, e);		/* to user */
829 		define('z', to->q_home, e);	/* user's home */
830 
831 		/*
832 		**  Expand out this user into argument list.
833 		*/
834 
835 		if (!clever)
836 		{
837 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
838 			*pvp++ = newstr(buf);
839 			if (pvp >= &pv[MAXPV - 2])
840 			{
841 				/* allow some space for trailing parms */
842 				break;
843 			}
844 		}
845 	}
846 
847 	/* see if any addresses still exist */
848 	if (tobuf[0] == '\0')
849 	{
850 		define('g', (char *) NULL, e);
851 		return (0);
852 	}
853 
854 	/* print out messages as full list */
855 	e->e_to = tobuf + 1;
856 
857 	/*
858 	**  Fill out any parameters after the $u parameter.
859 	*/
860 
861 	while (!clever && *++mvp != NULL)
862 	{
863 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
864 		*pvp++ = newstr(buf);
865 		if (pvp >= &pv[MAXPV])
866 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
867 	}
868 	*pvp++ = NULL;
869 
870 	/*
871 	**  Call the mailer.
872 	**	The argument vector gets built, pipes
873 	**	are created as necessary, and we fork & exec as
874 	**	appropriate.
875 	**	If we are running SMTP, we just need to clean up.
876 	*/
877 
878 	if (ctladdr == NULL && m != ProgMailer)
879 		ctladdr = &e->e_from;
880 #ifdef NAMED_BIND
881 	if (ConfigLevel < 2)
882 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
883 #endif
884 
885 	if (tTd(11, 1))
886 	{
887 		printf("openmailer:");
888 		printav(pv);
889 	}
890 	errno = 0;
891 
892 	CurHostName = m->m_mailer;
893 
894 	/*
895 	**  Deal with the special case of mail handled through an IPC
896 	**  connection.
897 	**	In this case we don't actually fork.  We must be
898 	**	running SMTP for this to work.  We will return a
899 	**	zero pid to indicate that we are running IPC.
900 	**  We also handle a debug version that just talks to stdin/out.
901 	*/
902 
903 	curhost = NULL;
904 
905 	/* check for Local Person Communication -- not for mortals!!! */
906 	if (strcmp(m->m_mailer, "[LPC]") == 0)
907 	{
908 		mci = (MCI *) xalloc(sizeof *mci);
909 		bzero((char *) mci, sizeof *mci);
910 		mci->mci_in = stdin;
911 		mci->mci_out = stdout;
912 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
913 		mci->mci_mailer = m;
914 	}
915 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
916 		 strcmp(m->m_mailer, "[TCP]") == 0)
917 	{
918 #ifdef DAEMON
919 		register int i;
920 		register u_short port;
921 		extern MCI *mci_get();
922 		extern char *hostsignature();
923 
924 		CurHostName = pv[1];
925 		curhost = hostsignature(m, pv[1], e);
926 
927 		if (curhost == NULL || curhost[0] == '\0')
928 		{
929 			syserr("null signature");
930 			rcode = EX_OSERR;
931 			goto give_up;
932 		}
933 
934 		if (!clever)
935 		{
936 			syserr("554 non-clever IPC");
937 			rcode = EX_OSERR;
938 			goto give_up;
939 		}
940 		if (pv[2] != NULL)
941 			port = atoi(pv[2]);
942 		else
943 			port = 0;
944 tryhost:
945 		mci = NULL;
946 		while (*curhost != '\0')
947 		{
948 			register char *p;
949 			static char hostbuf[MAXNAME];
950 
951 			mci = NULL;
952 
953 			/* pull the next host from the signature */
954 			p = strchr(curhost, ':');
955 			if (p == NULL)
956 				p = &curhost[strlen(curhost)];
957 			strncpy(hostbuf, curhost, p - curhost);
958 			hostbuf[p - curhost] = '\0';
959 			if (*p != '\0')
960 				p++;
961 			curhost = p;
962 
963 			/* see if we already know that this host is fried */
964 			CurHostName = hostbuf;
965 			mci = mci_get(hostbuf, m);
966 			if (mci->mci_state != MCIS_CLOSED)
967 			{
968 				if (tTd(11, 1))
969 				{
970 					printf("openmailer: ");
971 					mci_dump(mci);
972 				}
973 				CurHostName = mci->mci_host;
974 				break;
975 			}
976 			mci->mci_mailer = m;
977 			if (mci->mci_exitstat != EX_OK)
978 				continue;
979 
980 			/* try the connection */
981 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
982 			message("Connecting to %s (%s)...",
983 				hostbuf, m->m_name);
984 			i = makeconnection(hostbuf, port, mci,
985 				bitnset(M_SECURE_PORT, m->m_flags));
986 			mci->mci_exitstat = i;
987 			mci->mci_errno = errno;
988 			if (i == EX_OK)
989 			{
990 				mci->mci_state = MCIS_OPENING;
991 				mci_cache(mci);
992 				break;
993 			}
994 			else if (tTd(11, 1))
995 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
996 					i, errno);
997 
998 
999 			/* enter status of this host */
1000 			setstat(i);
1001 		}
1002 		mci->mci_pid = 0;
1003 #else /* no DAEMON */
1004 		syserr("554 openmailer: no IPC");
1005 		if (tTd(11, 1))
1006 			printf("openmailer: NULL\n");
1007 		return NULL;
1008 #endif /* DAEMON */
1009 	}
1010 	else
1011 	{
1012 		int i;
1013 		struct stat stbuf;
1014 
1015 		/* make absolutely certain 0, 1, and 2 are in use */
1016 		for (i = 0; i < 3; i++)
1017 		{
1018 			if (fstat(i, &stbuf) < 0)
1019 			{
1020 				/* oops.... */
1021 				int fd;
1022 
1023 				syserr("%s... openmailer(%s): fd %d not open",
1024 					e->e_to, m->m_name, i);
1025 				fd = open("/dev/null", O_RDONLY, 0666);
1026 				if (fd != i)
1027 				{
1028 					(void) dup2(fd, i);
1029 					(void) close(fd);
1030 				}
1031 			}
1032 		}
1033 
1034 		/* create a pipe to shove the mail through */
1035 		if (pipe(mpvect) < 0)
1036 		{
1037 			syserr("%s... openmailer(%s): pipe (to mailer)",
1038 				e->e_to, m->m_name);
1039 			if (tTd(11, 1))
1040 				printf("openmailer: NULL\n");
1041 			rcode = EX_OSERR;
1042 			goto give_up;
1043 		}
1044 
1045 		/* if this mailer speaks smtp, create a return pipe */
1046 		if (clever && pipe(rpvect) < 0)
1047 		{
1048 			syserr("%s... openmailer(%s): pipe (from mailer)",
1049 				e->e_to, m->m_name);
1050 			(void) close(mpvect[0]);
1051 			(void) close(mpvect[1]);
1052 			if (tTd(11, 1))
1053 				printf("openmailer: NULL\n");
1054 			rcode = EX_OSERR;
1055 			goto give_up;
1056 		}
1057 
1058 		/*
1059 		**  Actually fork the mailer process.
1060 		**	DOFORK is clever about retrying.
1061 		**
1062 		**	Dispose of SIGCHLD signal catchers that may be laying
1063 		**	around so that endmail will get it.
1064 		*/
1065 
1066 		if (e->e_xfp != NULL)
1067 			(void) fflush(e->e_xfp);		/* for debugging */
1068 		(void) fflush(stdout);
1069 # ifdef SIGCHLD
1070 		(void) signal(SIGCHLD, SIG_DFL);
1071 # endif /* SIGCHLD */
1072 		DOFORK(FORK);
1073 		/* pid is set by DOFORK */
1074 		if (pid < 0)
1075 		{
1076 			/* failure */
1077 			syserr("%s... openmailer(%s): cannot fork",
1078 				e->e_to, m->m_name);
1079 			(void) close(mpvect[0]);
1080 			(void) close(mpvect[1]);
1081 			if (clever)
1082 			{
1083 				(void) close(rpvect[0]);
1084 				(void) close(rpvect[1]);
1085 			}
1086 			if (tTd(11, 1))
1087 				printf("openmailer: NULL\n");
1088 			rcode = EX_OSERR;
1089 			goto give_up;
1090 		}
1091 		else if (pid == 0)
1092 		{
1093 			int i;
1094 			int saveerrno;
1095 			char **ep;
1096 			char *env[MAXUSERENVIRON];
1097 			extern char **environ;
1098 			extern int DtableSize;
1099 
1100 			/* child -- set up input & exec mailer */
1101 			/* make diagnostic output be standard output */
1102 			(void) signal(SIGINT, SIG_IGN);
1103 			(void) signal(SIGHUP, SIG_IGN);
1104 			(void) signal(SIGTERM, SIG_DFL);
1105 
1106 			/* close any other cached connections */
1107 			mci_flush(FALSE, mci);
1108 
1109 			/* move into some "safe" directory */
1110 			if (m->m_execdir != NULL)
1111 			{
1112 				char *p, *q;
1113 				char buf[MAXLINE];
1114 
1115 				for (p = m->m_execdir; p != NULL; p = q)
1116 				{
1117 					q = strchr(p, ':');
1118 					if (q != NULL)
1119 						*q = '\0';
1120 					expand(p, buf, &buf[sizeof buf] - 1, e);
1121 					if (q != NULL)
1122 						*q++ = ':';
1123 					if (tTd(11, 20))
1124 						printf("openmailer: trydir %s\n",
1125 							buf);
1126 					if (buf[0] != '\0' && chdir(buf) >= 0)
1127 						break;
1128 				}
1129 			}
1130 
1131 			/* arrange to filter std & diag output of command */
1132 			if (clever)
1133 			{
1134 				(void) close(rpvect[0]);
1135 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1136 				{
1137 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1138 						e->e_to, m->m_name, rpvect[1]);
1139 					_exit(EX_OSERR);
1140 				}
1141 				(void) close(rpvect[1]);
1142 			}
1143 			else if (OpMode == MD_SMTP || HoldErrs)
1144 			{
1145 				/* put mailer output in transcript */
1146 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1147 				{
1148 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1149 						e->e_to, m->m_name,
1150 						fileno(e->e_xfp));
1151 					_exit(EX_OSERR);
1152 				}
1153 			}
1154 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1155 			{
1156 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1157 					e->e_to, m->m_name);
1158 				_exit(EX_OSERR);
1159 			}
1160 
1161 			/* arrange to get standard input */
1162 			(void) close(mpvect[1]);
1163 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1164 			{
1165 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1166 					e->e_to, m->m_name, mpvect[0]);
1167 				_exit(EX_OSERR);
1168 			}
1169 			(void) close(mpvect[0]);
1170 			if (!bitnset(M_RESTR, m->m_flags))
1171 			{
1172 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1173 				{
1174 					(void) setgid(DefGid);
1175 					(void) initgroups(DefUser, DefGid);
1176 					(void) setuid(DefUid);
1177 				}
1178 				else
1179 				{
1180 					(void) setgid(ctladdr->q_gid);
1181 					(void) initgroups(ctladdr->q_ruser?
1182 						ctladdr->q_ruser: ctladdr->q_user,
1183 						ctladdr->q_gid);
1184 					(void) setuid(ctladdr->q_uid);
1185 				}
1186 			}
1187 
1188 			/* arrange for all the files to be closed */
1189 			for (i = 3; i < DtableSize; i++)
1190 			{
1191 				register int j;
1192 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1193 					(void)fcntl(i, F_SETFD, j|1);
1194 			}
1195 
1196 			/* set up the mailer environment */
1197 			i = 0;
1198 			env[i++] = "AGENT=sendmail";
1199 			for (ep = environ; *ep != NULL; ep++)
1200 			{
1201 				if (strncmp(*ep, "TZ=", 3) == 0)
1202 					env[i++] = *ep;
1203 			}
1204 			env[i++] = NULL;
1205 
1206 			/* try to execute the mailer */
1207 			execve(m->m_mailer, pv, env);
1208 			saveerrno = errno;
1209 			syserr("Cannot exec %s", m->m_mailer);
1210 			if (m == LocalMailer)
1211 				_exit(EX_TEMPFAIL);
1212 			if (transienterror(saveerrno))
1213 				_exit(EX_TEMPFAIL);
1214 			_exit(EX_UNAVAILABLE);
1215 		}
1216 
1217 		/*
1218 		**  Set up return value.
1219 		*/
1220 
1221 		mci = (MCI *) xalloc(sizeof *mci);
1222 		bzero((char *) mci, sizeof *mci);
1223 		mci->mci_mailer = m;
1224 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1225 		mci->mci_pid = pid;
1226 		(void) close(mpvect[0]);
1227 		mci->mci_out = fdopen(mpvect[1], "w");
1228 		if (clever)
1229 		{
1230 			(void) close(rpvect[1]);
1231 			mci->mci_in = fdopen(rpvect[0], "r");
1232 		}
1233 		else
1234 		{
1235 			mci->mci_flags |= MCIF_TEMP;
1236 			mci->mci_in = NULL;
1237 		}
1238 	}
1239 
1240 	/*
1241 	**  If we are in SMTP opening state, send initial protocol.
1242 	*/
1243 
1244 	if (clever && mci->mci_state != MCIS_CLOSED)
1245 	{
1246 		smtpinit(m, mci, e);
1247 	}
1248 	if (tTd(11, 1))
1249 	{
1250 		printf("openmailer: ");
1251 		mci_dump(mci);
1252 	}
1253 
1254 	if (mci->mci_state != MCIS_OPEN)
1255 	{
1256 		/* couldn't open the mailer */
1257 		rcode = mci->mci_exitstat;
1258 		errno = mci->mci_errno;
1259 		if (rcode == EX_OK)
1260 		{
1261 			/* shouldn't happen */
1262 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1263 				rcode, mci->mci_state, firstsig);
1264 			rcode = EX_SOFTWARE;
1265 		}
1266 	}
1267 	else if (!clever)
1268 	{
1269 		/*
1270 		**  Format and send message.
1271 		*/
1272 
1273 		putfromline(mci->mci_out, m, e);
1274 		(*e->e_puthdr)(mci->mci_out, m, e);
1275 		putline("\n", mci->mci_out, m);
1276 		(*e->e_putbody)(mci->mci_out, m, e);
1277 
1278 		/* get the exit status */
1279 		rcode = endmailer(mci, e, pv);
1280 	}
1281 	else
1282 #ifdef SMTP
1283 	{
1284 		/*
1285 		**  Send the MAIL FROM: protocol
1286 		*/
1287 
1288 		rcode = smtpmailfrom(m, mci, e);
1289 		if (rcode == EX_OK)
1290 		{
1291 			register char *t = tobuf;
1292 			register int i;
1293 
1294 			/* send the recipient list */
1295 			tobuf[0] = '\0';
1296 			for (to = tochain; to != NULL; to = to->q_tchain)
1297 			{
1298 				e->e_to = to->q_paddr;
1299 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1300 				{
1301 					markfailure(e, to, i);
1302 					giveresponse(i, m, mci, e);
1303 				}
1304 				else
1305 				{
1306 					*t++ = ',';
1307 					for (p = to->q_paddr; *p; *t++ = *p++)
1308 						continue;
1309 				}
1310 			}
1311 
1312 			/* now send the data */
1313 			if (tobuf[0] == '\0')
1314 			{
1315 				rcode = EX_OK;
1316 				e->e_to = NULL;
1317 				if (bitset(MCIF_CACHED, mci->mci_flags))
1318 					smtprset(m, mci, e);
1319 			}
1320 			else
1321 			{
1322 				e->e_to = tobuf + 1;
1323 				rcode = smtpdata(m, mci, e);
1324 			}
1325 
1326 			/* now close the connection */
1327 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1328 				smtpquit(m, mci, e);
1329 		}
1330 		if (rcode != EX_OK && *curhost != '\0')
1331 		{
1332 			/* try next MX site */
1333 			goto tryhost;
1334 		}
1335 	}
1336 #else /* not SMTP */
1337 	{
1338 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1339 		rcode = EX_CONFIG;
1340 		goto give_up;
1341 	}
1342 #endif /* SMTP */
1343 #ifdef NAMED_BIND
1344 	if (ConfigLevel < 2)
1345 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1346 #endif
1347 
1348 	/* arrange a return receipt if requested */
1349 	if (e->e_receiptto != NULL && bitnset(M_LOCALMAILER, m->m_flags))
1350 	{
1351 		e->e_flags |= EF_SENDRECEIPT;
1352 		/* do we want to send back more info? */
1353 	}
1354 
1355 	/*
1356 	**  Do final status disposal.
1357 	**	We check for something in tobuf for the SMTP case.
1358 	**	If we got a temporary failure, arrange to queue the
1359 	**		addressees.
1360 	*/
1361 
1362   give_up:
1363 	if (tobuf[0] != '\0')
1364 		giveresponse(rcode, m, mci, e);
1365 	for (to = tochain; to != NULL; to = to->q_tchain)
1366 	{
1367 		if (rcode != EX_OK)
1368 			markfailure(e, to, rcode);
1369 		else
1370 		{
1371 			to->q_flags |= QSENT;
1372 			e->e_nsent++;
1373 		}
1374 	}
1375 
1376 	/*
1377 	**  Restore state and return.
1378 	*/
1379 
1380 	errno = 0;
1381 	define('g', (char *) NULL, e);
1382 	return (rcode);
1383 }
1384 /*
1385 **  MARKFAILURE -- mark a failure on a specific address.
1386 **
1387 **	Parameters:
1388 **		e -- the envelope we are sending.
1389 **		q -- the address to mark.
1390 **		rcode -- the code signifying the particular failure.
1391 **
1392 **	Returns:
1393 **		none.
1394 **
1395 **	Side Effects:
1396 **		marks the address (and possibly the envelope) with the
1397 **			failure so that an error will be returned or
1398 **			the message will be queued, as appropriate.
1399 */
1400 
1401 markfailure(e, q, rcode)
1402 	register ENVELOPE *e;
1403 	register ADDRESS *q;
1404 	int rcode;
1405 {
1406 	char buf[MAXLINE];
1407 	extern char *pintvl();
1408 
1409 	if (rcode == EX_OK)
1410 		return;
1411 	else if (rcode != EX_TEMPFAIL && rcode != EX_IOERR && rcode != EX_OSERR)
1412 		q->q_flags |= QBADADDR;
1413 	else if (curtime() > e->e_ctime + TimeOuts.to_q_return)
1414 	{
1415 		if (!bitset(EF_TIMEOUT, e->e_flags))
1416 		{
1417 			(void) sprintf(buf, "Cannot send message for %s",
1418 				pintvl(TimeOuts.to_q_return, FALSE));
1419 			if (e->e_message != NULL)
1420 				free(e->e_message);
1421 			e->e_message = newstr(buf);
1422 			message(buf);
1423 		}
1424 		q->q_flags |= QBADADDR;
1425 		e->e_flags |= EF_TIMEOUT;
1426 		fprintf(e->e_xfp, "421 %s... Message timed out\n", q->q_paddr);
1427 	}
1428 	else
1429 	{
1430 		q->q_flags |= QQUEUEUP;
1431 		if (TimeOuts.to_q_warning > 0 &&
1432 		    curtime() > e->e_ctime + TimeOuts.to_q_warning)
1433 		{
1434 			if (!bitset(EF_WARNING, e->e_flags) &&
1435 			    e->e_class >= 0)
1436 			{
1437 				(void) sprintf(buf,
1438 					"warning: cannot send message for %s",
1439 					pintvl(TimeOuts.to_q_warning, FALSE));
1440 				if (e->e_message != NULL)
1441 					free(e->e_message);
1442 				e->e_message = newstr(buf);
1443 				message(buf);
1444 				e->e_flags |= EF_WARNING|EF_TIMEOUT;
1445 			}
1446 			fprintf(e->e_xfp,
1447 				"%s... Warning: message still undelivered after %s\n",
1448 				q->q_paddr, pintvl(TimeOuts.to_q_warning, FALSE));
1449 			fprintf(e->e_xfp, "Will keep trying until message is %s old\n",
1450 				pintvl(TimeOuts.to_q_return, FALSE));
1451 		}
1452 	}
1453 }
1454 /*
1455 **  ENDMAILER -- Wait for mailer to terminate.
1456 **
1457 **	We should never get fatal errors (e.g., segmentation
1458 **	violation), so we report those specially.  For other
1459 **	errors, we choose a status message (into statmsg),
1460 **	and if it represents an error, we print it.
1461 **
1462 **	Parameters:
1463 **		pid -- pid of mailer.
1464 **		e -- the current envelope.
1465 **		pv -- the parameter vector that invoked the mailer
1466 **			(for error messages).
1467 **
1468 **	Returns:
1469 **		exit code of mailer.
1470 **
1471 **	Side Effects:
1472 **		none.
1473 */
1474 
1475 endmailer(mci, e, pv)
1476 	register MCI *mci;
1477 	register ENVELOPE *e;
1478 	char **pv;
1479 {
1480 	int st;
1481 
1482 	/* close any connections */
1483 	if (mci->mci_in != NULL)
1484 		(void) xfclose(mci->mci_in, pv[0], "mci_in");
1485 	if (mci->mci_out != NULL)
1486 		(void) xfclose(mci->mci_out, pv[0], "mci_out");
1487 	mci->mci_in = mci->mci_out = NULL;
1488 	mci->mci_state = MCIS_CLOSED;
1489 
1490 	/* in the IPC case there is nothing to wait for */
1491 	if (mci->mci_pid == 0)
1492 		return (EX_OK);
1493 
1494 	/* wait for the mailer process to die and collect status */
1495 	st = waitfor(mci->mci_pid);
1496 	if (st == -1)
1497 	{
1498 		syserr("endmailer %s: wait", pv[0]);
1499 		return (EX_SOFTWARE);
1500 	}
1501 
1502 	/* see if it died a horrid death */
1503 	if ((st & 0377) != 0)
1504 	{
1505 		syserr("mailer %s died with signal %o", pv[0], st);
1506 
1507 		/* log the arguments */
1508 		if (e->e_xfp != NULL)
1509 		{
1510 			register char **av;
1511 
1512 			fprintf(e->e_xfp, "Arguments:");
1513 			for (av = pv; *av != NULL; av++)
1514 				fprintf(e->e_xfp, " %s", *av);
1515 			fprintf(e->e_xfp, "\n");
1516 		}
1517 
1518 		ExitStat = EX_TEMPFAIL;
1519 		return (EX_TEMPFAIL);
1520 	}
1521 
1522 	/* normal death -- return status */
1523 	st = (st >> 8) & 0377;
1524 	return (st);
1525 }
1526 /*
1527 **  GIVERESPONSE -- Interpret an error response from a mailer
1528 **
1529 **	Parameters:
1530 **		stat -- the status code from the mailer (high byte
1531 **			only; core dumps must have been taken care of
1532 **			already).
1533 **		m -- the mailer info for this mailer.
1534 **		mci -- the mailer connection info -- can be NULL if the
1535 **			response is given before the connection is made.
1536 **		e -- the current envelope.
1537 **
1538 **	Returns:
1539 **		none.
1540 **
1541 **	Side Effects:
1542 **		Errors may be incremented.
1543 **		ExitStat may be set.
1544 */
1545 
1546 giveresponse(stat, m, mci, e)
1547 	int stat;
1548 	register MAILER *m;
1549 	register MCI *mci;
1550 	ENVELOPE *e;
1551 {
1552 	register char *statmsg;
1553 	extern char *SysExMsg[];
1554 	register int i;
1555 	extern int N_SysEx;
1556 #ifdef NAMED_BIND
1557 	extern int h_errno;
1558 #endif
1559 	char buf[MAXLINE];
1560 	extern char *errstring();
1561 
1562 	/*
1563 	**  Compute status message from code.
1564 	*/
1565 
1566 	i = stat - EX__BASE;
1567 	if (stat == 0)
1568 	{
1569 		statmsg = "250 Sent";
1570 		if (e->e_statmsg != NULL)
1571 		{
1572 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1573 			statmsg = buf;
1574 		}
1575 	}
1576 	else if (i < 0 || i > N_SysEx)
1577 	{
1578 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1579 		stat = EX_UNAVAILABLE;
1580 		statmsg = buf;
1581 	}
1582 	else if (stat == EX_TEMPFAIL)
1583 	{
1584 		(void) strcpy(buf, SysExMsg[i] + 1);
1585 #ifdef NAMED_BIND
1586 		if (h_errno == TRY_AGAIN)
1587 			statmsg = errstring(h_errno+MAX_ERRNO);
1588 		else
1589 #endif
1590 		{
1591 			if (errno != 0)
1592 				statmsg = errstring(errno);
1593 			else
1594 			{
1595 #ifdef SMTP
1596 				extern char SmtpError[];
1597 
1598 				statmsg = SmtpError;
1599 #else /* SMTP */
1600 				statmsg = NULL;
1601 #endif /* SMTP */
1602 			}
1603 		}
1604 		if (statmsg != NULL && statmsg[0] != '\0')
1605 		{
1606 			(void) strcat(buf, ": ");
1607 			(void) strcat(buf, statmsg);
1608 		}
1609 		statmsg = buf;
1610 	}
1611 	else
1612 	{
1613 		statmsg = SysExMsg[i];
1614 		if (*statmsg++ == ':')
1615 		{
1616 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1617 			statmsg = buf;
1618 		}
1619 	}
1620 
1621 	/*
1622 	**  Print the message as appropriate
1623 	*/
1624 
1625 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1626 		message(&statmsg[4], errstring(errno));
1627 	else
1628 	{
1629 		Errors++;
1630 		usrerr(statmsg, errstring(errno));
1631 	}
1632 
1633 	/*
1634 	**  Final cleanup.
1635 	**	Log a record of the transaction.  Compute the new
1636 	**	ExitStat -- if we already had an error, stick with
1637 	**	that.
1638 	*/
1639 
1640 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1641 		logdelivery(m, mci, &statmsg[4], e);
1642 
1643 	if (stat != EX_TEMPFAIL)
1644 		setstat(stat);
1645 	if (stat != EX_OK)
1646 	{
1647 		if (e->e_message != NULL)
1648 			free(e->e_message);
1649 		e->e_message = newstr(&statmsg[4]);
1650 	}
1651 	errno = 0;
1652 #ifdef NAMED_BIND
1653 	h_errno = 0;
1654 #endif
1655 }
1656 /*
1657 **  LOGDELIVERY -- log the delivery in the system log
1658 **
1659 **	Parameters:
1660 **		m -- the mailer info.  Can be NULL for initial queue.
1661 **		mci -- the mailer connection info -- can be NULL if the
1662 **			log is occuring when no connection is active.
1663 **		stat -- the message to print for the status.
1664 **		e -- the current envelope.
1665 **
1666 **	Returns:
1667 **		none
1668 **
1669 **	Side Effects:
1670 **		none
1671 */
1672 
1673 logdelivery(m, mci, stat, e)
1674 	MAILER *m;
1675 	register MCI *mci;
1676 	char *stat;
1677 	register ENVELOPE *e;
1678 {
1679 # ifdef LOG
1680 	char *curhost;
1681 	char buf[512];
1682 	extern char *pintvl();
1683 	extern char *macvalue();
1684 
1685 	(void) sprintf(buf, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1686 
1687 	if (m != NULL)
1688 	{
1689 		(void) strcat(buf, ", mailer=");
1690 		(void) strcat(buf, m->m_name);
1691 	}
1692 
1693 	if (mci != NULL && mci->mci_host != NULL)
1694 	{
1695 # ifdef DAEMON
1696 		extern SOCKADDR CurHostAddr;
1697 		extern char *anynet_ntoa();
1698 # endif
1699 
1700 		(void) strcat(buf, ", relay=");
1701 		(void) strcat(buf, mci->mci_host);
1702 
1703 # ifdef DAEMON
1704 		(void) strcat(buf, " (");
1705 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
1706 		(void) strcat(buf, ")");
1707 # endif
1708 	}
1709 	else
1710 	{
1711 		char *p = macvalue('h', e);
1712 
1713 		if (p != NULL && p[0] != '\0')
1714 		{
1715 			(void) strcat(buf, ", relay=");
1716 			(void) strcat(buf, p);
1717 		}
1718 	}
1719 
1720 	syslog(LOG_INFO, "%s: to=%s, %s, stat=%s",
1721 	       e->e_id, e->e_to, buf, stat);
1722 # endif /* LOG */
1723 }
1724 /*
1725 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1726 **
1727 **	This can be made an arbitrary message separator by changing $l
1728 **
1729 **	One of the ugliest hacks seen by human eyes is contained herein:
1730 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1731 **	does a well-meaning programmer such as myself have to deal with
1732 **	this kind of antique garbage????
1733 **
1734 **	Parameters:
1735 **		fp -- the file to output to.
1736 **		m -- the mailer describing this entry.
1737 **
1738 **	Returns:
1739 **		none
1740 **
1741 **	Side Effects:
1742 **		outputs some text to fp.
1743 */
1744 
1745 putfromline(fp, m, e)
1746 	register FILE *fp;
1747 	register MAILER *m;
1748 	ENVELOPE *e;
1749 {
1750 	char *template = "\201l\n";
1751 	char buf[MAXLINE];
1752 
1753 	if (bitnset(M_NHDR, m->m_flags))
1754 		return;
1755 
1756 # ifdef UGLYUUCP
1757 	if (bitnset(M_UGLYUUCP, m->m_flags))
1758 	{
1759 		char *bang;
1760 		char xbuf[MAXLINE];
1761 
1762 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1763 		bang = strchr(buf, '!');
1764 		if (bang == NULL)
1765 			syserr("554 No ! in UUCP! (%s)", buf);
1766 		else
1767 		{
1768 			*bang++ = '\0';
1769 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1770 			template = xbuf;
1771 		}
1772 	}
1773 # endif /* UGLYUUCP */
1774 	expand(template, buf, &buf[sizeof buf - 1], e);
1775 	putline(buf, fp, m);
1776 }
1777 /*
1778 **  PUTBODY -- put the body of a message.
1779 **
1780 **	Parameters:
1781 **		fp -- file to output onto.
1782 **		m -- a mailer descriptor to control output format.
1783 **		e -- the envelope to put out.
1784 **
1785 **	Returns:
1786 **		none.
1787 **
1788 **	Side Effects:
1789 **		The message is written onto fp.
1790 */
1791 
1792 putbody(fp, m, e)
1793 	FILE *fp;
1794 	MAILER *m;
1795 	register ENVELOPE *e;
1796 {
1797 	char buf[MAXLINE];
1798 
1799 	/*
1800 	**  Output the body of the message
1801 	*/
1802 
1803 	if (e->e_dfp == NULL)
1804 	{
1805 		if (e->e_df != NULL)
1806 		{
1807 			e->e_dfp = fopen(e->e_df, "r");
1808 			if (e->e_dfp == NULL)
1809 				syserr("putbody: Cannot open %s for %s from %s",
1810 				e->e_df, e->e_to, e->e_from);
1811 		}
1812 		else
1813 			putline("<<< No Message Collected >>>", fp, m);
1814 	}
1815 	if (e->e_dfp != NULL)
1816 	{
1817 		rewind(e->e_dfp);
1818 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1819 		{
1820 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1821 			    strncmp(buf, "From ", 5) == 0)
1822 				(void) putc('>', fp);
1823 			putline(buf, fp, m);
1824 		}
1825 
1826 		if (ferror(e->e_dfp))
1827 		{
1828 			syserr("putbody: read error");
1829 			ExitStat = EX_IOERR;
1830 		}
1831 	}
1832 
1833 	(void) fflush(fp);
1834 	if (ferror(fp) && errno != EPIPE)
1835 	{
1836 		syserr("putbody: write error");
1837 		ExitStat = EX_IOERR;
1838 	}
1839 	errno = 0;
1840 }
1841 /*
1842 **  MAILFILE -- Send a message to a file.
1843 **
1844 **	If the file has the setuid/setgid bits set, but NO execute
1845 **	bits, sendmail will try to become the owner of that file
1846 **	rather than the real user.  Obviously, this only works if
1847 **	sendmail runs as root.
1848 **
1849 **	This could be done as a subordinate mailer, except that it
1850 **	is used implicitly to save messages in ~/dead.letter.  We
1851 **	view this as being sufficiently important as to include it
1852 **	here.  For example, if the system is dying, we shouldn't have
1853 **	to create another process plus some pipes to save the message.
1854 **
1855 **	Parameters:
1856 **		filename -- the name of the file to send to.
1857 **		ctladdr -- the controlling address header -- includes
1858 **			the userid/groupid to be when sending.
1859 **
1860 **	Returns:
1861 **		The exit code associated with the operation.
1862 **
1863 **	Side Effects:
1864 **		none.
1865 */
1866 
1867 mailfile(filename, ctladdr, e)
1868 	char *filename;
1869 	ADDRESS *ctladdr;
1870 	register ENVELOPE *e;
1871 {
1872 	register FILE *f;
1873 	register int pid;
1874 	int mode;
1875 
1876 	/*
1877 	**  Fork so we can change permissions here.
1878 	**	Note that we MUST use fork, not vfork, because of
1879 	**	the complications of calling subroutines, etc.
1880 	*/
1881 
1882 	DOFORK(fork);
1883 
1884 	if (pid < 0)
1885 		return (EX_OSERR);
1886 	else if (pid == 0)
1887 	{
1888 		/* child -- actually write to file */
1889 		struct stat stb;
1890 
1891 		(void) signal(SIGINT, SIG_DFL);
1892 		(void) signal(SIGHUP, SIG_DFL);
1893 		(void) signal(SIGTERM, SIG_DFL);
1894 		(void) umask(OldUmask);
1895 
1896 		if (stat(filename, &stb) < 0)
1897 			stb.st_mode = 0666;
1898 		mode = stb.st_mode;
1899 
1900 		/* limit the errors to those actually caused in the child */
1901 		errno = 0;
1902 		ExitStat = EX_OK;
1903 
1904 		if (bitset(0111, stb.st_mode))
1905 			exit(EX_CANTCREAT);
1906 		if (ctladdr == NULL)
1907 			ctladdr = &e->e_from;
1908 		else
1909 		{
1910 			/* ignore setuid and setgid bits */
1911 			mode &= ~(S_ISGID|S_ISUID);
1912 		}
1913 
1914 		/* we have to open the dfile BEFORE setuid */
1915 		if (e->e_dfp == NULL && e->e_df != NULL)
1916 		{
1917 			e->e_dfp = fopen(e->e_df, "r");
1918 			if (e->e_dfp == NULL)
1919 			{
1920 				syserr("mailfile: Cannot open %s for %s from %s",
1921 					e->e_df, e->e_to, e->e_from);
1922 			}
1923 		}
1924 
1925 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
1926 		{
1927 			if (ctladdr->q_uid == 0)
1928 			{
1929 				(void) setgid(DefGid);
1930 				(void) initgroups(DefUser, DefGid);
1931 			}
1932 			else
1933 			{
1934 				(void) setgid(ctladdr->q_gid);
1935 				(void) initgroups(ctladdr->q_ruser ?
1936 					ctladdr->q_ruser : ctladdr->q_user,
1937 					ctladdr->q_gid);
1938 			}
1939 		}
1940 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
1941 		{
1942 			if (ctladdr->q_uid == 0)
1943 				(void) setuid(DefUid);
1944 			else
1945 				(void) setuid(ctladdr->q_uid);
1946 		}
1947 		FileName = filename;
1948 		LineNumber = 0;
1949 		f = dfopen(filename, "a");
1950 		if (f == NULL)
1951 		{
1952 			message("554 cannot open");
1953 			exit(EX_CANTCREAT);
1954 		}
1955 
1956 		putfromline(f, ProgMailer, e);
1957 		(*e->e_puthdr)(f, ProgMailer, e);
1958 		putline("\n", f, ProgMailer);
1959 		(*e->e_putbody)(f, ProgMailer, e);
1960 		putline("\n", f, ProgMailer);
1961 		if (ferror(f))
1962 		{
1963 			message("451 I/O error");
1964 			setstat(EX_IOERR);
1965 		}
1966 		(void) xfclose(f, "mailfile", filename);
1967 		(void) fflush(stdout);
1968 
1969 		/* reset ISUID & ISGID bits for paranoid systems */
1970 		(void) chmod(filename, (int) stb.st_mode);
1971 		exit(ExitStat);
1972 		/*NOTREACHED*/
1973 	}
1974 	else
1975 	{
1976 		/* parent -- wait for exit status */
1977 		int st;
1978 
1979 		st = waitfor(pid);
1980 		if ((st & 0377) != 0)
1981 			return (EX_UNAVAILABLE);
1982 		else
1983 			return ((st >> 8) & 0377);
1984 		/*NOTREACHED*/
1985 	}
1986 }
1987 /*
1988 **  HOSTSIGNATURE -- return the "signature" for a host.
1989 **
1990 **	The signature describes how we are going to send this -- it
1991 **	can be just the hostname (for non-Internet hosts) or can be
1992 **	an ordered list of MX hosts.
1993 **
1994 **	Parameters:
1995 **		m -- the mailer describing this host.
1996 **		host -- the host name.
1997 **		e -- the current envelope.
1998 **
1999 **	Returns:
2000 **		The signature for this host.
2001 **
2002 **	Side Effects:
2003 **		Can tweak the symbol table.
2004 */
2005 
2006 char *
2007 hostsignature(m, host, e)
2008 	register MAILER *m;
2009 	char *host;
2010 	ENVELOPE *e;
2011 {
2012 	register char *p;
2013 	register STAB *s;
2014 	int i;
2015 	int len;
2016 #ifdef NAMED_BIND
2017 	int nmx;
2018 	auto int rcode;
2019 	char *hp;
2020 	char *endp;
2021 	int oldoptions;
2022 	char *mxhosts[MAXMXHOSTS + 1];
2023 	static char myhostbuf[MAXNAME];
2024 #endif
2025 
2026 	/*
2027 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2028 	*/
2029 
2030 	p = m->m_mailer;
2031 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2032 	{
2033 		/* just an ordinary mailer */
2034 		return host;
2035 	}
2036 
2037 	/*
2038 	**  If it is a numeric address, just return it.
2039 	*/
2040 
2041 	if (host[0] == '[')
2042 		return host;
2043 
2044 	/*
2045 	**  Look it up in the symbol table.
2046 	*/
2047 
2048 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2049 	if (s->s_hostsig != NULL)
2050 		return s->s_hostsig;
2051 
2052 	/*
2053 	**  Not already there -- create a signature.
2054 	*/
2055 
2056 #ifdef NAMED_BIND
2057 	if (ConfigLevel < 2)
2058 	{
2059 		oldoptions = _res.options;
2060 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2061 	}
2062 
2063 	if (myhostbuf[0] == '\0')
2064 		expand("\201j", myhostbuf, &myhostbuf[sizeof myhostbuf - 1], e);
2065 
2066 	for (hp = host; hp != NULL; hp = endp)
2067 	{
2068 		endp = strchr(hp, ':');
2069 		if (endp != NULL)
2070 			*endp = '\0';
2071 
2072 		nmx = getmxrr(hp, mxhosts, myhostbuf, &rcode);
2073 
2074 		if (nmx <= 0)
2075 		{
2076 			register MCI *mci;
2077 			extern int errno;
2078 			extern MCI *mci_get();
2079 
2080 			/* update the connection info for this host */
2081 			mci = mci_get(hp, m);
2082 			mci->mci_exitstat = rcode;
2083 			mci->mci_errno = errno;
2084 
2085 			/* and return the original host name as the signature */
2086 			nmx = 1;
2087 			mxhosts[0] = hp;
2088 		}
2089 
2090 		len = 0;
2091 		for (i = 0; i < nmx; i++)
2092 		{
2093 			len += strlen(mxhosts[i]) + 1;
2094 		}
2095 		if (s->s_hostsig != NULL)
2096 			len += strlen(s->s_hostsig) + 1;
2097 		p = xalloc(len);
2098 		if (s->s_hostsig != NULL)
2099 		{
2100 			(void) strcpy(p, s->s_hostsig);
2101 			free(s->s_hostsig);
2102 			s->s_hostsig = p;
2103 			p += strlen(p);
2104 			*p++ = ':';
2105 		}
2106 		else
2107 			s->s_hostsig = p;
2108 		for (i = 0; i < nmx; i++)
2109 		{
2110 			if (i != 0)
2111 				*p++ = ':';
2112 			strcpy(p, mxhosts[i]);
2113 			p += strlen(p);
2114 		}
2115 		if (endp != NULL)
2116 			*endp++ = ':';
2117 	}
2118 	makelower(s->s_hostsig);
2119 	if (ConfigLevel < 2)
2120 		_res.options = oldoptions;
2121 #else
2122 	/* not using BIND -- the signature is just the host name */
2123 	s->s_hostsig = host;
2124 #endif
2125 	if (tTd(17, 1))
2126 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2127 	return s->s_hostsig;
2128 }
2129