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