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