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