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