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