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