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