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.34 (Berkeley) 10/17/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 	if (tTd(10, 100))
592 		printopenfds(FALSE);
593 
594 	/*
595 	**  If this mailer is expensive, and if we don't want to make
596 	**  connections now, just mark these addresses and return.
597 	**	This is useful if we want to batch connections to
598 	**	reduce load.  This will cause the messages to be
599 	**	queued up, and a daemon will come along to send the
600 	**	messages later.
601 	**		This should be on a per-mailer basis.
602 	*/
603 
604 	if (NoConnect && bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
605 	{
606 		for (; to != NULL; to = to->q_next)
607 		{
608 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
609 			    to->q_mailer != m)
610 				continue;
611 			to->q_flags |= QQUEUEUP;
612 			e->e_to = to->q_paddr;
613 			message("queued");
614 			if (LogLevel > 8)
615 				logdelivery(m, NULL, "queued", e);
616 		}
617 		e->e_to = NULL;
618 		return (0);
619 	}
620 
621 	/*
622 	**  Do initial argv setup.
623 	**	Insert the mailer name.  Notice that $x expansion is
624 	**	NOT done on the mailer name.  Then, if the mailer has
625 	**	a picky -f flag, we insert it as appropriate.  This
626 	**	code does not check for 'pv' overflow; this places a
627 	**	manifest lower limit of 4 for MAXPV.
628 	**		The from address rewrite is expected to make
629 	**		the address relative to the other end.
630 	*/
631 
632 	/* rewrite from address, using rewriting rules */
633 	rcode = EX_OK;
634 	(void) strcpy(rpathbuf, remotename(e->e_from.q_paddr, m,
635 					   RF_SENDERADDR|RF_CANONICAL,
636 					   &rcode, e));
637 	define('g', rpathbuf, e);		/* translated return path */
638 	define('h', host, e);			/* to host */
639 	Errors = 0;
640 	pvp = pv;
641 	*pvp++ = m->m_argv[0];
642 
643 	/* insert -f or -r flag as appropriate */
644 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
645 	{
646 		if (bitnset(M_FOPT, m->m_flags))
647 			*pvp++ = "-f";
648 		else
649 			*pvp++ = "-r";
650 		*pvp++ = newstr(rpathbuf);
651 	}
652 
653 	/*
654 	**  Append the other fixed parts of the argv.  These run
655 	**  up to the first entry containing "$u".  There can only
656 	**  be one of these, and there are only a few more slots
657 	**  in the pv after it.
658 	*/
659 
660 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
661 	{
662 		/* can't use strchr here because of sign extension problems */
663 		while (*p != '\0')
664 		{
665 			if ((*p++ & 0377) == MACROEXPAND)
666 			{
667 				if (*p == 'u')
668 					break;
669 			}
670 		}
671 
672 		if (*p != '\0')
673 			break;
674 
675 		/* this entry is safe -- go ahead and process it */
676 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
677 		*pvp++ = newstr(buf);
678 		if (pvp >= &pv[MAXPV - 3])
679 		{
680 			syserr("554 Too many parameters to %s before $u", pv[0]);
681 			return (-1);
682 		}
683 	}
684 
685 	/*
686 	**  If we have no substitution for the user name in the argument
687 	**  list, we know that we must supply the names otherwise -- and
688 	**  SMTP is the answer!!
689 	*/
690 
691 	if (*mvp == NULL)
692 	{
693 		/* running SMTP */
694 # ifdef SMTP
695 		clever = TRUE;
696 		*pvp = NULL;
697 # else /* SMTP */
698 		/* oops!  we don't implement SMTP */
699 		syserr("554 SMTP style mailer not implemented");
700 		return (EX_SOFTWARE);
701 # endif /* SMTP */
702 	}
703 
704 	/*
705 	**  At this point *mvp points to the argument with $u.  We
706 	**  run through our address list and append all the addresses
707 	**  we can.  If we run out of space, do not fret!  We can
708 	**  always send another copy later.
709 	*/
710 
711 	tobuf[0] = '\0';
712 	e->e_to = tobuf;
713 	ctladdr = NULL;
714 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
715 	for (; to != NULL; to = to->q_next)
716 	{
717 		/* avoid sending multiple recipients to dumb mailers */
718 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
719 			break;
720 
721 		/* if already sent or not for this host, don't send */
722 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
723 		    to->q_mailer != firstto->q_mailer ||
724 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
725 			continue;
726 
727 		/* avoid overflowing tobuf */
728 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
729 			break;
730 
731 		if (tTd(10, 1))
732 		{
733 			printf("\nsend to ");
734 			printaddr(to, FALSE);
735 		}
736 
737 		/* compute effective uid/gid when sending */
738 		if (to->q_mailer == ProgMailer)
739 			ctladdr = getctladdr(to);
740 
741 		user = to->q_user;
742 		e->e_to = to->q_paddr;
743 		if (tTd(10, 5))
744 		{
745 			printf("deliver: QDONTSEND ");
746 			printaddr(to, FALSE);
747 		}
748 		to->q_flags |= QDONTSEND;
749 
750 		/*
751 		**  Check to see that these people are allowed to
752 		**  talk to each other.
753 		*/
754 
755 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
756 		{
757 			NoReturn = TRUE;
758 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
759 			giveresponse(EX_UNAVAILABLE, m, NULL, e);
760 			continue;
761 		}
762 		rcode = checkcompat(to, e);
763 		if (rcode != EX_OK)
764 		{
765 			markfailure(e, to, rcode);
766 			giveresponse(rcode, m, NULL, e);
767 			continue;
768 		}
769 
770 		/*
771 		**  Strip quote bits from names if the mailer is dumb
772 		**	about them.
773 		*/
774 
775 		if (bitnset(M_STRIPQ, m->m_flags))
776 		{
777 			stripquotes(user);
778 			stripquotes(host);
779 		}
780 
781 		/* hack attack -- delivermail compatibility */
782 		if (m == ProgMailer && *user == '|')
783 			user++;
784 
785 		/*
786 		**  If an error message has already been given, don't
787 		**	bother to send to this address.
788 		**
789 		**	>>>>>>>>>> This clause assumes that the local mailer
790 		**	>> NOTE >> cannot do any further aliasing; that
791 		**	>>>>>>>>>> function is subsumed by sendmail.
792 		*/
793 
794 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
795 			continue;
796 
797 		/* save statistics.... */
798 		markstats(e, to);
799 
800 		/*
801 		**  See if this user name is "special".
802 		**	If the user name has a slash in it, assume that this
803 		**	is a file -- send it off without further ado.  Note
804 		**	that this type of addresses is not processed along
805 		**	with the others, so we fudge on the To person.
806 		*/
807 
808 		if (m == FileMailer)
809 		{
810 			rcode = mailfile(user, getctladdr(to), e);
811 			giveresponse(rcode, m, NULL, e);
812 			if (rcode == EX_OK)
813 				to->q_flags |= QSENT;
814 			continue;
815 		}
816 
817 		/*
818 		**  Address is verified -- add this user to mailer
819 		**  argv, and add it to the print list of recipients.
820 		*/
821 
822 		/* link together the chain of recipients */
823 		to->q_tchain = tochain;
824 		tochain = to;
825 
826 		/* create list of users for error messages */
827 		(void) strcat(tobuf, ",");
828 		(void) strcat(tobuf, to->q_paddr);
829 		define('u', user, e);		/* to user */
830 		p = to->q_home;
831 		if (p == NULL && ctladdr != NULL)
832 			p = ctladdr->q_home;
833 		define('z', p, e);	/* user's home */
834 
835 		/*
836 		**  Expand out this user into argument list.
837 		*/
838 
839 		if (!clever)
840 		{
841 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
842 			*pvp++ = newstr(buf);
843 			if (pvp >= &pv[MAXPV - 2])
844 			{
845 				/* allow some space for trailing parms */
846 				break;
847 			}
848 		}
849 	}
850 
851 	/* see if any addresses still exist */
852 	if (tobuf[0] == '\0')
853 	{
854 		define('g', (char *) NULL, e);
855 		return (0);
856 	}
857 
858 	/* print out messages as full list */
859 	e->e_to = tobuf + 1;
860 
861 	/*
862 	**  Fill out any parameters after the $u parameter.
863 	*/
864 
865 	while (!clever && *++mvp != NULL)
866 	{
867 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
868 		*pvp++ = newstr(buf);
869 		if (pvp >= &pv[MAXPV])
870 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
871 	}
872 	*pvp++ = NULL;
873 
874 	/*
875 	**  Call the mailer.
876 	**	The argument vector gets built, pipes
877 	**	are created as necessary, and we fork & exec as
878 	**	appropriate.
879 	**	If we are running SMTP, we just need to clean up.
880 	*/
881 
882 	if (ctladdr == NULL && m != ProgMailer)
883 		ctladdr = &e->e_from;
884 #ifdef NAMED_BIND
885 	if (ConfigLevel < 2)
886 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
887 #endif
888 
889 	if (tTd(11, 1))
890 	{
891 		printf("openmailer:");
892 		printav(pv);
893 	}
894 	errno = 0;
895 
896 	CurHostName = m->m_mailer;
897 
898 	/*
899 	**  Deal with the special case of mail handled through an IPC
900 	**  connection.
901 	**	In this case we don't actually fork.  We must be
902 	**	running SMTP for this to work.  We will return a
903 	**	zero pid to indicate that we are running IPC.
904 	**  We also handle a debug version that just talks to stdin/out.
905 	*/
906 
907 	curhost = NULL;
908 	SmtpPhase = NULL;
909 	mci = NULL;
910 
911 #ifdef XDEBUG
912 	{
913 		char wbuf[MAXLINE];
914 
915 		/* make absolutely certain 0, 1, and 2 are in use */
916 		sprintf(wbuf, "%s... openmailer(%s)", e->e_to, m->m_name);
917 		checkfd012(wbuf);
918 	}
919 #endif
920 
921 	/* check for Local Person Communication -- not for mortals!!! */
922 	if (strcmp(m->m_mailer, "[LPC]") == 0)
923 	{
924 		mci = (MCI *) xalloc(sizeof *mci);
925 		bzero((char *) mci, sizeof *mci);
926 		mci->mci_in = stdin;
927 		mci->mci_out = stdout;
928 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
929 		mci->mci_mailer = m;
930 	}
931 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
932 		 strcmp(m->m_mailer, "[TCP]") == 0)
933 	{
934 #ifdef DAEMON
935 		register int i;
936 		register u_short port;
937 
938 		CurHostName = pv[1];
939 		curhost = hostsignature(m, pv[1], e);
940 
941 		if (curhost == NULL || curhost[0] == '\0')
942 		{
943 			syserr("null signature");
944 			rcode = EX_OSERR;
945 			goto give_up;
946 		}
947 
948 		if (!clever)
949 		{
950 			syserr("554 non-clever IPC");
951 			rcode = EX_CONFIG;
952 			goto give_up;
953 		}
954 		if (pv[2] != NULL)
955 			port = atoi(pv[2]);
956 		else
957 			port = 0;
958 tryhost:
959 		while (*curhost != '\0')
960 		{
961 			register char *p;
962 			static char hostbuf[MAXNAME];
963 
964 			/* pull the next host from the signature */
965 			p = strchr(curhost, ':');
966 			if (p == NULL)
967 				p = &curhost[strlen(curhost)];
968 			if (p == curhost)
969 			{
970 				syserr("deliver: null host name in signature");
971 				curhost++;
972 				continue;
973 			}
974 			strncpy(hostbuf, curhost, p - curhost);
975 			hostbuf[p - curhost] = '\0';
976 			if (*p != '\0')
977 				p++;
978 			curhost = p;
979 
980 			/* see if we already know that this host is fried */
981 			CurHostName = hostbuf;
982 			mci = mci_get(hostbuf, m);
983 			if (mci->mci_state != MCIS_CLOSED)
984 			{
985 				if (tTd(11, 1))
986 				{
987 					printf("openmailer: ");
988 					mci_dump(mci);
989 				}
990 				CurHostName = mci->mci_host;
991 				break;
992 			}
993 			mci->mci_mailer = m;
994 			if (mci->mci_exitstat != EX_OK)
995 				continue;
996 
997 			/* try the connection */
998 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
999 			message("Connecting to %s (%s)...",
1000 				hostbuf, m->m_name);
1001 			i = makeconnection(hostbuf, port, mci,
1002 				bitnset(M_SECURE_PORT, m->m_flags));
1003 			mci->mci_exitstat = i;
1004 			mci->mci_errno = errno;
1005 #ifdef NAMED_BIND
1006 			mci->mci_herrno = h_errno;
1007 #endif
1008 			if (i == EX_OK)
1009 			{
1010 				mci->mci_state = MCIS_OPENING;
1011 				mci_cache(mci);
1012 				if (TrafficLogFile != NULL)
1013 					fprintf(TrafficLogFile, "%05d == CONNECT %s\n",
1014 						getpid(), hostbuf);
1015 				break;
1016 			}
1017 			else if (tTd(11, 1))
1018 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1019 					i, errno);
1020 
1021 			/* enter status of this host */
1022 			setstat(i);
1023 
1024 			/* should print some message here for -v mode */
1025 		}
1026 		if (mci == NULL)
1027 		{
1028 			syserr("deliver: no host name");
1029 			rcode = EX_OSERR;
1030 			goto give_up;
1031 		}
1032 		mci->mci_pid = 0;
1033 #else /* no DAEMON */
1034 		syserr("554 openmailer: no IPC");
1035 		if (tTd(11, 1))
1036 			printf("openmailer: NULL\n");
1037 		rcode = EX_UNAVAILABLE;
1038 		goto give_up;
1039 #endif /* DAEMON */
1040 	}
1041 	else
1042 	{
1043 		if (TrafficLogFile != NULL)
1044 		{
1045 			char **av;
1046 
1047 			fprintf(TrafficLogFile, "%05d === EXEC", getpid());
1048 			for (av = pv; *av != NULL; av++)
1049 				fprintf(TrafficLogFile, " %s", *av);
1050 			fprintf(TrafficLogFile, "\n");
1051 		}
1052 
1053 		/* create a pipe to shove the mail through */
1054 		if (pipe(mpvect) < 0)
1055 		{
1056 			syserr("%s... openmailer(%s): pipe (to mailer)",
1057 				e->e_to, m->m_name);
1058 			if (tTd(11, 1))
1059 				printf("openmailer: NULL\n");
1060 			rcode = EX_OSERR;
1061 			goto give_up;
1062 		}
1063 
1064 		/* if this mailer speaks smtp, create a return pipe */
1065 		if (clever && pipe(rpvect) < 0)
1066 		{
1067 			syserr("%s... openmailer(%s): pipe (from mailer)",
1068 				e->e_to, m->m_name);
1069 			(void) close(mpvect[0]);
1070 			(void) close(mpvect[1]);
1071 			if (tTd(11, 1))
1072 				printf("openmailer: NULL\n");
1073 			rcode = EX_OSERR;
1074 			goto give_up;
1075 		}
1076 
1077 		/*
1078 		**  Actually fork the mailer process.
1079 		**	DOFORK is clever about retrying.
1080 		**
1081 		**	Dispose of SIGCHLD signal catchers that may be laying
1082 		**	around so that endmail will get it.
1083 		*/
1084 
1085 		if (e->e_xfp != NULL)
1086 			(void) fflush(e->e_xfp);		/* for debugging */
1087 		(void) fflush(stdout);
1088 # ifdef SIGCHLD
1089 		(void) setsignal(SIGCHLD, SIG_DFL);
1090 # endif /* SIGCHLD */
1091 		DOFORK(FORK);
1092 		/* pid is set by DOFORK */
1093 		if (pid < 0)
1094 		{
1095 			/* failure */
1096 			syserr("%s... openmailer(%s): cannot fork",
1097 				e->e_to, m->m_name);
1098 			(void) close(mpvect[0]);
1099 			(void) close(mpvect[1]);
1100 			if (clever)
1101 			{
1102 				(void) close(rpvect[0]);
1103 				(void) close(rpvect[1]);
1104 			}
1105 			if (tTd(11, 1))
1106 				printf("openmailer: NULL\n");
1107 			rcode = EX_OSERR;
1108 			goto give_up;
1109 		}
1110 		else if (pid == 0)
1111 		{
1112 			int i;
1113 			int saveerrno;
1114 			char **ep;
1115 			char *env[MAXUSERENVIRON];
1116 			extern char **environ;
1117 			extern int DtableSize;
1118 
1119 			/* child -- set up input & exec mailer */
1120 			(void) setsignal(SIGINT, SIG_IGN);
1121 			(void) setsignal(SIGHUP, SIG_IGN);
1122 			(void) setsignal(SIGTERM, SIG_DFL);
1123 
1124 			/* close any other cached connections */
1125 			mci_flush(FALSE, mci);
1126 
1127 			/* reset user and group */
1128 			if (!bitnset(M_RESTR, m->m_flags))
1129 			{
1130 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1131 				{
1132 					(void) initgroups(DefUser, DefGid);
1133 					(void) setuid(DefUid);
1134 				}
1135 				else
1136 				{
1137 					(void) initgroups(ctladdr->q_ruser?
1138 						ctladdr->q_ruser: ctladdr->q_user,
1139 						ctladdr->q_gid);
1140 					(void) setuid(ctladdr->q_uid);
1141 				}
1142 			}
1143 
1144 			if (tTd(11, 2))
1145 				printf("openmailer: running as r/euid=%d/%d\n",
1146 					getuid(), geteuid());
1147 
1148 			/* move into some "safe" directory */
1149 			if (m->m_execdir != NULL)
1150 			{
1151 				char *p, *q;
1152 				char buf[MAXLINE];
1153 
1154 				for (p = m->m_execdir; p != NULL; p = q)
1155 				{
1156 					q = strchr(p, ':');
1157 					if (q != NULL)
1158 						*q = '\0';
1159 					expand(p, buf, &buf[sizeof buf] - 1, e);
1160 					if (q != NULL)
1161 						*q++ = ':';
1162 					if (tTd(11, 20))
1163 						printf("openmailer: trydir %s\n",
1164 							buf);
1165 					if (buf[0] != '\0' && chdir(buf) >= 0)
1166 						break;
1167 				}
1168 			}
1169 
1170 			/* arrange to filter std & diag output of command */
1171 			if (clever)
1172 			{
1173 				(void) close(rpvect[0]);
1174 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1175 				{
1176 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1177 						e->e_to, m->m_name, rpvect[1]);
1178 					_exit(EX_OSERR);
1179 				}
1180 				(void) close(rpvect[1]);
1181 			}
1182 			else if (OpMode == MD_SMTP || HoldErrs)
1183 			{
1184 				/* put mailer output in transcript */
1185 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1186 				{
1187 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1188 						e->e_to, m->m_name,
1189 						fileno(e->e_xfp));
1190 					_exit(EX_OSERR);
1191 				}
1192 			}
1193 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1194 			{
1195 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1196 					e->e_to, m->m_name);
1197 				_exit(EX_OSERR);
1198 			}
1199 
1200 			/* arrange to get standard input */
1201 			(void) close(mpvect[1]);
1202 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1203 			{
1204 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1205 					e->e_to, m->m_name, mpvect[0]);
1206 				_exit(EX_OSERR);
1207 			}
1208 			(void) close(mpvect[0]);
1209 
1210 			/* arrange for all the files to be closed */
1211 			for (i = 3; i < DtableSize; i++)
1212 			{
1213 				register int j;
1214 
1215 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1216 					(void) fcntl(i, F_SETFD, j | 1);
1217 			}
1218 
1219 			/* set up the mailer environment */
1220 			i = 0;
1221 			env[i++] = "AGENT=sendmail";
1222 			for (ep = environ; *ep != NULL; ep++)
1223 			{
1224 				if (strncmp(*ep, "TZ=", 3) == 0)
1225 					env[i++] = *ep;
1226 			}
1227 			env[i++] = NULL;
1228 
1229 			/* try to execute the mailer */
1230 			execve(m->m_mailer, pv, env);
1231 			saveerrno = errno;
1232 			syserr("Cannot exec %s", m->m_mailer);
1233 			if (m == LocalMailer || transienterror(saveerrno))
1234 				_exit(EX_OSERR);
1235 			_exit(EX_UNAVAILABLE);
1236 		}
1237 
1238 		/*
1239 		**  Set up return value.
1240 		*/
1241 
1242 		mci = (MCI *) xalloc(sizeof *mci);
1243 		bzero((char *) mci, sizeof *mci);
1244 		mci->mci_mailer = m;
1245 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1246 		mci->mci_pid = pid;
1247 		(void) close(mpvect[0]);
1248 		mci->mci_out = fdopen(mpvect[1], "w");
1249 		if (mci->mci_out == NULL)
1250 		{
1251 			syserr("deliver: cannot create mailer output channel, fd=%d",
1252 				mpvect[1]);
1253 			(void) close(mpvect[1]);
1254 			if (clever)
1255 			{
1256 				(void) close(rpvect[0]);
1257 				(void) close(rpvect[1]);
1258 			}
1259 			rcode = EX_OSERR;
1260 			goto give_up;
1261 		}
1262 		if (clever)
1263 		{
1264 			(void) close(rpvect[1]);
1265 			mci->mci_in = fdopen(rpvect[0], "r");
1266 			if (mci->mci_in == NULL)
1267 			{
1268 				syserr("deliver: cannot create mailer input channel, fd=%d",
1269 					mpvect[1]);
1270 				(void) close(rpvect[0]);
1271 				fclose(mci->mci_out);
1272 				mci->mci_out = NULL;
1273 				rcode = EX_OSERR;
1274 				goto give_up;
1275 			}
1276 		}
1277 		else
1278 		{
1279 			mci->mci_flags |= MCIF_TEMP;
1280 			mci->mci_in = NULL;
1281 		}
1282 	}
1283 
1284 	/*
1285 	**  If we are in SMTP opening state, send initial protocol.
1286 	*/
1287 
1288 	if (clever && mci->mci_state != MCIS_CLOSED)
1289 	{
1290 		smtpinit(m, mci, e);
1291 	}
1292 	if (tTd(11, 1))
1293 	{
1294 		printf("openmailer: ");
1295 		mci_dump(mci);
1296 	}
1297 
1298 	if (mci->mci_state != MCIS_OPEN)
1299 	{
1300 		/* couldn't open the mailer */
1301 		rcode = mci->mci_exitstat;
1302 		errno = mci->mci_errno;
1303 #ifdef NAMED_BIND
1304 		h_errno = mci->mci_herrno;
1305 #endif
1306 		if (rcode == EX_OK)
1307 		{
1308 			/* shouldn't happen */
1309 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1310 				rcode, mci->mci_state, firstsig);
1311 			rcode = EX_SOFTWARE;
1312 		}
1313 		else if (rcode == EX_TEMPFAIL && *curhost != '\0')
1314 		{
1315 			/* try next MX site */
1316 			goto tryhost;
1317 		}
1318 	}
1319 	else if (!clever)
1320 	{
1321 		/*
1322 		**  Format and send message.
1323 		*/
1324 
1325 		putfromline(mci->mci_out, m, e);
1326 		(*e->e_puthdr)(mci->mci_out, m, e);
1327 		putline("\n", mci->mci_out, m);
1328 		(*e->e_putbody)(mci->mci_out, m, e, NULL);
1329 
1330 		/* get the exit status */
1331 		rcode = endmailer(mci, e, pv);
1332 	}
1333 	else
1334 #ifdef SMTP
1335 	{
1336 		/*
1337 		**  Send the MAIL FROM: protocol
1338 		*/
1339 
1340 		rcode = smtpmailfrom(m, mci, e);
1341 		if (rcode == EX_OK)
1342 		{
1343 			register char *t = tobuf;
1344 			register int i;
1345 
1346 			/* send the recipient list */
1347 			tobuf[0] = '\0';
1348 			for (to = tochain; to != NULL; to = to->q_tchain)
1349 			{
1350 				e->e_to = to->q_paddr;
1351 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1352 				{
1353 					markfailure(e, to, i);
1354 					giveresponse(i, m, mci, e);
1355 				}
1356 				else
1357 				{
1358 					*t++ = ',';
1359 					for (p = to->q_paddr; *p; *t++ = *p++)
1360 						continue;
1361 					*t = '\0';
1362 				}
1363 			}
1364 
1365 			/* now send the data */
1366 			if (tobuf[0] == '\0')
1367 			{
1368 				rcode = EX_OK;
1369 				e->e_to = NULL;
1370 				if (bitset(MCIF_CACHED, mci->mci_flags))
1371 					smtprset(m, mci, e);
1372 			}
1373 			else
1374 			{
1375 				e->e_to = tobuf + 1;
1376 				rcode = smtpdata(m, mci, e);
1377 			}
1378 
1379 			/* now close the connection */
1380 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1381 				smtpquit(m, mci, e);
1382 		}
1383 		if (rcode != EX_OK && *curhost != '\0')
1384 		{
1385 			/* try next MX site */
1386 			goto tryhost;
1387 		}
1388 	}
1389 #else /* not SMTP */
1390 	{
1391 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1392 		rcode = EX_CONFIG;
1393 		goto give_up;
1394 	}
1395 #endif /* SMTP */
1396 #ifdef NAMED_BIND
1397 	if (ConfigLevel < 2)
1398 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1399 #endif
1400 
1401 	/* arrange a return receipt if requested */
1402 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1403 	    bitnset(M_LOCALMAILER, m->m_flags))
1404 	{
1405 		e->e_flags |= EF_SENDRECEIPT;
1406 		/* do we want to send back more info? */
1407 	}
1408 
1409 	/*
1410 	**  Do final status disposal.
1411 	**	We check for something in tobuf for the SMTP case.
1412 	**	If we got a temporary failure, arrange to queue the
1413 	**		addressees.
1414 	*/
1415 
1416   give_up:
1417 	if (tobuf[0] != '\0')
1418 		giveresponse(rcode, m, mci, e);
1419 	for (to = tochain; to != NULL; to = to->q_tchain)
1420 	{
1421 		if (rcode != EX_OK)
1422 			markfailure(e, to, rcode);
1423 		else
1424 		{
1425 			to->q_flags |= QSENT;
1426 			e->e_nsent++;
1427 			if (e->e_receiptto != NULL &&
1428 			    bitnset(M_LOCALMAILER, m->m_flags))
1429 			{
1430 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1431 					to->q_paddr);
1432 			}
1433 		}
1434 	}
1435 
1436 	/*
1437 	**  Restore state and return.
1438 	*/
1439 
1440 #ifdef XDEBUG
1441 	{
1442 		char wbuf[MAXLINE];
1443 
1444 		/* make absolutely certain 0, 1, and 2 are in use */
1445 		sprintf(wbuf, "%s... end of deliver(%s)",
1446 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1447 			m->m_name);
1448 		checkfd012(wbuf);
1449 	}
1450 #endif
1451 
1452 	errno = 0;
1453 	define('g', (char *) NULL, e);
1454 	return (rcode);
1455 }
1456 /*
1457 **  MARKFAILURE -- mark a failure on a specific address.
1458 **
1459 **	Parameters:
1460 **		e -- the envelope we are sending.
1461 **		q -- the address to mark.
1462 **		rcode -- the code signifying the particular failure.
1463 **
1464 **	Returns:
1465 **		none.
1466 **
1467 **	Side Effects:
1468 **		marks the address (and possibly the envelope) with the
1469 **			failure so that an error will be returned or
1470 **			the message will be queued, as appropriate.
1471 */
1472 
1473 markfailure(e, q, rcode)
1474 	register ENVELOPE *e;
1475 	register ADDRESS *q;
1476 	int rcode;
1477 {
1478 	char buf[MAXLINE];
1479 
1480 	if (rcode == EX_OK)
1481 		return;
1482 	else if (rcode == EX_TEMPFAIL)
1483 		q->q_flags |= QQUEUEUP;
1484 	else if (rcode != EX_IOERR && rcode != EX_OSERR)
1485 		q->q_flags |= QBADADDR;
1486 }
1487 /*
1488 **  ENDMAILER -- Wait for mailer to terminate.
1489 **
1490 **	We should never get fatal errors (e.g., segmentation
1491 **	violation), so we report those specially.  For other
1492 **	errors, we choose a status message (into statmsg),
1493 **	and if it represents an error, we print it.
1494 **
1495 **	Parameters:
1496 **		pid -- pid of mailer.
1497 **		e -- the current envelope.
1498 **		pv -- the parameter vector that invoked the mailer
1499 **			(for error messages).
1500 **
1501 **	Returns:
1502 **		exit code of mailer.
1503 **
1504 **	Side Effects:
1505 **		none.
1506 */
1507 
1508 endmailer(mci, e, pv)
1509 	register MCI *mci;
1510 	register ENVELOPE *e;
1511 	char **pv;
1512 {
1513 	int st;
1514 
1515 	/* close any connections */
1516 	if (mci->mci_in != NULL)
1517 		(void) xfclose(mci->mci_in, pv[0], "mci_in");
1518 	if (mci->mci_out != NULL)
1519 		(void) xfclose(mci->mci_out, pv[0], "mci_out");
1520 	mci->mci_in = mci->mci_out = NULL;
1521 	mci->mci_state = MCIS_CLOSED;
1522 
1523 	/* in the IPC case there is nothing to wait for */
1524 	if (mci->mci_pid == 0)
1525 		return (EX_OK);
1526 
1527 	/* wait for the mailer process to die and collect status */
1528 	st = waitfor(mci->mci_pid);
1529 	if (st == -1)
1530 	{
1531 		syserr("endmailer %s: wait", pv[0]);
1532 		return (EX_SOFTWARE);
1533 	}
1534 
1535 	if (WIFEXITED(st))
1536 	{
1537 		/* normal death -- return status */
1538 		return (WEXITSTATUS(st));
1539 	}
1540 
1541 	/* it died a horrid death */
1542 	syserr("mailer %s died with signal %o", pv[0], st);
1543 
1544 	/* log the arguments */
1545 	if (e->e_xfp != NULL)
1546 	{
1547 		register char **av;
1548 
1549 		fprintf(e->e_xfp, "Arguments:");
1550 		for (av = pv; *av != NULL; av++)
1551 			fprintf(e->e_xfp, " %s", *av);
1552 		fprintf(e->e_xfp, "\n");
1553 	}
1554 
1555 	ExitStat = EX_TEMPFAIL;
1556 	return (EX_TEMPFAIL);
1557 }
1558 /*
1559 **  GIVERESPONSE -- Interpret an error response from a mailer
1560 **
1561 **	Parameters:
1562 **		stat -- the status code from the mailer (high byte
1563 **			only; core dumps must have been taken care of
1564 **			already).
1565 **		m -- the mailer info for this mailer.
1566 **		mci -- the mailer connection info -- can be NULL if the
1567 **			response is given before the connection is made.
1568 **		e -- the current envelope.
1569 **
1570 **	Returns:
1571 **		none.
1572 **
1573 **	Side Effects:
1574 **		Errors may be incremented.
1575 **		ExitStat may be set.
1576 */
1577 
1578 giveresponse(stat, m, mci, e)
1579 	int stat;
1580 	register MAILER *m;
1581 	register MCI *mci;
1582 	ENVELOPE *e;
1583 {
1584 	register const char *statmsg;
1585 	extern char *SysExMsg[];
1586 	register int i;
1587 	extern int N_SysEx;
1588 	char buf[MAXLINE];
1589 
1590 	/*
1591 	**  Compute status message from code.
1592 	*/
1593 
1594 	i = stat - EX__BASE;
1595 	if (stat == 0)
1596 	{
1597 		statmsg = "250 Sent";
1598 		if (e->e_statmsg != NULL)
1599 		{
1600 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1601 			statmsg = buf;
1602 		}
1603 	}
1604 	else if (i < 0 || i > N_SysEx)
1605 	{
1606 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1607 		stat = EX_UNAVAILABLE;
1608 		statmsg = buf;
1609 	}
1610 	else if (stat == EX_TEMPFAIL)
1611 	{
1612 		(void) strcpy(buf, SysExMsg[i] + 1);
1613 #ifdef NAMED_BIND
1614 		if (h_errno == TRY_AGAIN)
1615 			statmsg = errstring(h_errno+E_DNSBASE);
1616 		else
1617 #endif
1618 		{
1619 			if (errno != 0)
1620 				statmsg = errstring(errno);
1621 			else
1622 			{
1623 #ifdef SMTP
1624 				extern char SmtpError[];
1625 
1626 				statmsg = SmtpError;
1627 #else /* SMTP */
1628 				statmsg = NULL;
1629 #endif /* SMTP */
1630 			}
1631 		}
1632 		if (statmsg != NULL && statmsg[0] != '\0')
1633 		{
1634 			(void) strcat(buf, ": ");
1635 			(void) strcat(buf, statmsg);
1636 		}
1637 		statmsg = buf;
1638 	}
1639 #ifdef NAMED_BIND
1640 	else if (stat == EX_NOHOST && h_errno != 0)
1641 	{
1642 		statmsg = errstring(h_errno + E_DNSBASE);
1643 		(void) sprintf(buf, "%s (%s)", SysExMsg[i], statmsg);
1644 		statmsg = buf;
1645 	}
1646 #endif
1647 	else
1648 	{
1649 		statmsg = SysExMsg[i];
1650 		if (*statmsg++ == ':')
1651 		{
1652 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1653 			statmsg = buf;
1654 		}
1655 	}
1656 
1657 	/*
1658 	**  Print the message as appropriate
1659 	*/
1660 
1661 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1662 	{
1663 		extern char MsgBuf[];
1664 
1665 		message(&statmsg[4], errstring(errno));
1666 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1667 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1668 	}
1669 	else
1670 	{
1671 		Errors++;
1672 		usrerr(statmsg, errstring(errno));
1673 	}
1674 
1675 	/*
1676 	**  Final cleanup.
1677 	**	Log a record of the transaction.  Compute the new
1678 	**	ExitStat -- if we already had an error, stick with
1679 	**	that.
1680 	*/
1681 
1682 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1683 		logdelivery(m, mci, &statmsg[4], e);
1684 
1685 	if (stat != EX_TEMPFAIL)
1686 		setstat(stat);
1687 	if (stat != EX_OK)
1688 	{
1689 		if (e->e_message != NULL)
1690 			free(e->e_message);
1691 		e->e_message = newstr(&statmsg[4]);
1692 	}
1693 	errno = 0;
1694 #ifdef NAMED_BIND
1695 	h_errno = 0;
1696 #endif
1697 }
1698 /*
1699 **  LOGDELIVERY -- log the delivery in the system log
1700 **
1701 **	Parameters:
1702 **		m -- the mailer info.  Can be NULL for initial queue.
1703 **		mci -- the mailer connection info -- can be NULL if the
1704 **			log is occuring when no connection is active.
1705 **		stat -- the message to print for the status.
1706 **		e -- the current envelope.
1707 **
1708 **	Returns:
1709 **		none
1710 **
1711 **	Side Effects:
1712 **		none
1713 */
1714 
1715 logdelivery(m, mci, stat, e)
1716 	MAILER *m;
1717 	register MCI *mci;
1718 	char *stat;
1719 	register ENVELOPE *e;
1720 {
1721 # ifdef LOG
1722 	char buf[512];
1723 
1724 	(void) sprintf(buf, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1725 
1726 	if (m != NULL)
1727 	{
1728 		(void) strcat(buf, ", mailer=");
1729 		(void) strcat(buf, m->m_name);
1730 	}
1731 
1732 	if (mci != NULL && mci->mci_host != NULL)
1733 	{
1734 # ifdef DAEMON
1735 		extern SOCKADDR CurHostAddr;
1736 # endif
1737 
1738 		(void) strcat(buf, ", relay=");
1739 		(void) strcat(buf, mci->mci_host);
1740 
1741 # ifdef DAEMON
1742 		(void) strcat(buf, " (");
1743 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
1744 		(void) strcat(buf, ")");
1745 # endif
1746 	}
1747 	else
1748 	{
1749 		char *p = macvalue('h', e);
1750 
1751 		if (p != NULL && p[0] != '\0')
1752 		{
1753 			(void) strcat(buf, ", relay=");
1754 			(void) strcat(buf, p);
1755 		}
1756 	}
1757 
1758 	syslog(LOG_INFO, "%s: to=%s, %s, stat=%s",
1759 	       e->e_id, e->e_to, buf, stat);
1760 # endif /* LOG */
1761 }
1762 /*
1763 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1764 **
1765 **	This can be made an arbitrary message separator by changing $l
1766 **
1767 **	One of the ugliest hacks seen by human eyes is contained herein:
1768 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1769 **	does a well-meaning programmer such as myself have to deal with
1770 **	this kind of antique garbage????
1771 **
1772 **	Parameters:
1773 **		fp -- the file to output to.
1774 **		m -- the mailer describing this entry.
1775 **
1776 **	Returns:
1777 **		none
1778 **
1779 **	Side Effects:
1780 **		outputs some text to fp.
1781 */
1782 
1783 putfromline(fp, m, e)
1784 	register FILE *fp;
1785 	register MAILER *m;
1786 	ENVELOPE *e;
1787 {
1788 	char *template = "\201l\n";
1789 	char buf[MAXLINE];
1790 
1791 	if (bitnset(M_NHDR, m->m_flags))
1792 		return;
1793 
1794 # ifdef UGLYUUCP
1795 	if (bitnset(M_UGLYUUCP, m->m_flags))
1796 	{
1797 		char *bang;
1798 		char xbuf[MAXLINE];
1799 
1800 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1801 		bang = strchr(buf, '!');
1802 		if (bang == NULL)
1803 		{
1804 			errno = 0;
1805 			syserr("554 No ! in UUCP From address! (%s given)", buf);
1806 		}
1807 		else
1808 		{
1809 			*bang++ = '\0';
1810 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1811 			template = xbuf;
1812 		}
1813 	}
1814 # endif /* UGLYUUCP */
1815 	expand(template, buf, &buf[sizeof buf - 1], e);
1816 	putline(buf, fp, m);
1817 }
1818 /*
1819 **  PUTBODY -- put the body of a message.
1820 **
1821 **	Parameters:
1822 **		fp -- file to output onto.
1823 **		m -- a mailer descriptor to control output format.
1824 **		e -- the envelope to put out.
1825 **		separator -- if non-NULL, a message separator that must
1826 **			not be permitted in the resulting message.
1827 **
1828 **	Returns:
1829 **		none.
1830 **
1831 **	Side Effects:
1832 **		The message is written onto fp.
1833 */
1834 
1835 putbody(fp, m, e, separator)
1836 	FILE *fp;
1837 	MAILER *m;
1838 	register ENVELOPE *e;
1839 	char *separator;
1840 {
1841 	char buf[MAXLINE];
1842 
1843 	/*
1844 	**  Output the body of the message
1845 	*/
1846 
1847 	if (e->e_dfp == NULL)
1848 	{
1849 		if (e->e_df != NULL)
1850 		{
1851 			e->e_dfp = fopen(e->e_df, "r");
1852 			if (e->e_dfp == NULL)
1853 				syserr("putbody: Cannot open %s for %s from %s",
1854 				e->e_df, e->e_to, e->e_from.q_paddr);
1855 		}
1856 		else
1857 			putline("<<< No Message Collected >>>", fp, m);
1858 	}
1859 	if (e->e_dfp != NULL)
1860 	{
1861 		rewind(e->e_dfp);
1862 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1863 		{
1864 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1865 			    strncmp(buf, "From ", 5) == 0)
1866 				(void) putc('>', fp);
1867 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
1868 			{
1869 				/* possible separator */
1870 				int sl = strlen(separator);
1871 
1872 				if (strncmp(&buf[2], separator, sl) == 0)
1873 					(void) putc(' ', fp);
1874 			}
1875 			putline(buf, fp, m);
1876 		}
1877 
1878 		if (ferror(e->e_dfp))
1879 		{
1880 			syserr("putbody: %s: read error", e->e_df);
1881 			ExitStat = EX_IOERR;
1882 		}
1883 	}
1884 
1885 	/* some mailers want extra blank line at end of message */
1886 	if (bitnset(M_BLANKEND, m->m_flags) && buf[0] != '\0' && buf[0] != '\n')
1887 		putline("", fp, m);
1888 
1889 	(void) fflush(fp);
1890 	if (ferror(fp) && errno != EPIPE)
1891 	{
1892 		syserr("putbody: write error");
1893 		ExitStat = EX_IOERR;
1894 	}
1895 	errno = 0;
1896 }
1897 /*
1898 **  MAILFILE -- Send a message to a file.
1899 **
1900 **	If the file has the setuid/setgid bits set, but NO execute
1901 **	bits, sendmail will try to become the owner of that file
1902 **	rather than the real user.  Obviously, this only works if
1903 **	sendmail runs as root.
1904 **
1905 **	This could be done as a subordinate mailer, except that it
1906 **	is used implicitly to save messages in ~/dead.letter.  We
1907 **	view this as being sufficiently important as to include it
1908 **	here.  For example, if the system is dying, we shouldn't have
1909 **	to create another process plus some pipes to save the message.
1910 **
1911 **	Parameters:
1912 **		filename -- the name of the file to send to.
1913 **		ctladdr -- the controlling address header -- includes
1914 **			the userid/groupid to be when sending.
1915 **
1916 **	Returns:
1917 **		The exit code associated with the operation.
1918 **
1919 **	Side Effects:
1920 **		none.
1921 */
1922 
1923 mailfile(filename, ctladdr, e)
1924 	char *filename;
1925 	ADDRESS *ctladdr;
1926 	register ENVELOPE *e;
1927 {
1928 	register FILE *f;
1929 	register int pid;
1930 	int mode;
1931 
1932 	if (tTd(11, 1))
1933 	{
1934 		printf("mailfile %s\n  ctladdr=", filename);
1935 		printaddr(ctladdr, FALSE);
1936 	}
1937 
1938 	if (e->e_xfp != NULL)
1939 		fflush(e->e_xfp);
1940 
1941 	/*
1942 	**  Fork so we can change permissions here.
1943 	**	Note that we MUST use fork, not vfork, because of
1944 	**	the complications of calling subroutines, etc.
1945 	*/
1946 
1947 	DOFORK(fork);
1948 
1949 	if (pid < 0)
1950 		return (EX_OSERR);
1951 	else if (pid == 0)
1952 	{
1953 		/* child -- actually write to file */
1954 		struct stat stb;
1955 
1956 		(void) setsignal(SIGINT, SIG_DFL);
1957 		(void) setsignal(SIGHUP, SIG_DFL);
1958 		(void) setsignal(SIGTERM, SIG_DFL);
1959 		(void) umask(OldUmask);
1960 
1961 		if (stat(filename, &stb) < 0)
1962 			stb.st_mode = FileMode;
1963 		mode = stb.st_mode;
1964 
1965 		/* limit the errors to those actually caused in the child */
1966 		errno = 0;
1967 		ExitStat = EX_OK;
1968 
1969 		if (bitset(0111, stb.st_mode))
1970 			exit(EX_CANTCREAT);
1971 		if (ctladdr == NULL)
1972 			ctladdr = &e->e_from;
1973 		else
1974 		{
1975 			/* ignore setuid and setgid bits */
1976 			mode &= ~(S_ISGID|S_ISUID);
1977 		}
1978 
1979 		/* we have to open the dfile BEFORE setuid */
1980 		if (e->e_dfp == NULL && e->e_df != NULL)
1981 		{
1982 			e->e_dfp = fopen(e->e_df, "r");
1983 			if (e->e_dfp == NULL)
1984 			{
1985 				syserr("mailfile: Cannot open %s for %s from %s",
1986 					e->e_df, e->e_to, e->e_from.q_paddr);
1987 			}
1988 		}
1989 
1990 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
1991 		{
1992 			if (ctladdr->q_uid == 0)
1993 			{
1994 				(void) initgroups(DefUser, DefGid);
1995 			}
1996 			else
1997 			{
1998 				(void) initgroups(ctladdr->q_ruser ?
1999 					ctladdr->q_ruser : ctladdr->q_user,
2000 					ctladdr->q_gid);
2001 			}
2002 		}
2003 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
2004 		{
2005 			if (ctladdr->q_uid == 0)
2006 				(void) setuid(DefUid);
2007 			else
2008 				(void) setuid(ctladdr->q_uid);
2009 		}
2010 		FileName = filename;
2011 		LineNumber = 0;
2012 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
2013 		if (f == NULL)
2014 		{
2015 			message("554 cannot open: %s", errstring(errno));
2016 			exit(EX_CANTCREAT);
2017 		}
2018 
2019 		putfromline(f, FileMailer, e);
2020 		(*e->e_puthdr)(f, FileMailer, e);
2021 		putline("\n", f, FileMailer);
2022 		(*e->e_putbody)(f, FileMailer, e, NULL);
2023 		putline("\n", f, FileMailer);
2024 		if (ferror(f))
2025 		{
2026 			message("451 I/O error: %s", errstring(errno));
2027 			setstat(EX_IOERR);
2028 		}
2029 		(void) xfclose(f, "mailfile", filename);
2030 		(void) fflush(stdout);
2031 
2032 		/* reset ISUID & ISGID bits for paranoid systems */
2033 		(void) chmod(filename, (int) stb.st_mode);
2034 		exit(ExitStat);
2035 		/*NOTREACHED*/
2036 	}
2037 	else
2038 	{
2039 		/* parent -- wait for exit status */
2040 		int st;
2041 
2042 		st = waitfor(pid);
2043 		if (WIFEXITED(st))
2044 			return (WEXITSTATUS(st));
2045 		else
2046 		{
2047 			syserr("child died on signal %d", st);
2048 			return (EX_UNAVAILABLE);
2049 		}
2050 		/*NOTREACHED*/
2051 	}
2052 }
2053 /*
2054 **  HOSTSIGNATURE -- return the "signature" for a host.
2055 **
2056 **	The signature describes how we are going to send this -- it
2057 **	can be just the hostname (for non-Internet hosts) or can be
2058 **	an ordered list of MX hosts.
2059 **
2060 **	Parameters:
2061 **		m -- the mailer describing this host.
2062 **		host -- the host name.
2063 **		e -- the current envelope.
2064 **
2065 **	Returns:
2066 **		The signature for this host.
2067 **
2068 **	Side Effects:
2069 **		Can tweak the symbol table.
2070 */
2071 
2072 char *
2073 hostsignature(m, host, e)
2074 	register MAILER *m;
2075 	char *host;
2076 	ENVELOPE *e;
2077 {
2078 	register char *p;
2079 	register STAB *s;
2080 	int i;
2081 	int len;
2082 #ifdef NAMED_BIND
2083 	int nmx;
2084 	auto int rcode;
2085 	char *hp;
2086 	char *endp;
2087 	int oldoptions;
2088 	char *mxhosts[MAXMXHOSTS + 1];
2089 #endif
2090 
2091 	/*
2092 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2093 	*/
2094 
2095 	p = m->m_mailer;
2096 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2097 	{
2098 		/* just an ordinary mailer */
2099 		return host;
2100 	}
2101 
2102 	/*
2103 	**  Look it up in the symbol table.
2104 	*/
2105 
2106 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2107 	if (s->s_hostsig != NULL)
2108 		return s->s_hostsig;
2109 
2110 	/*
2111 	**  Not already there -- create a signature.
2112 	*/
2113 
2114 #ifdef NAMED_BIND
2115 	if (ConfigLevel < 2)
2116 	{
2117 		oldoptions = _res.options;
2118 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2119 	}
2120 
2121 	for (hp = host; hp != NULL; hp = endp)
2122 	{
2123 		endp = strchr(hp, ':');
2124 		if (endp != NULL)
2125 			*endp = '\0';
2126 
2127 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2128 
2129 		if (nmx <= 0)
2130 		{
2131 			register MCI *mci;
2132 			extern int errno;
2133 
2134 			/* update the connection info for this host */
2135 			mci = mci_get(hp, m);
2136 			mci->mci_exitstat = rcode;
2137 			mci->mci_errno = errno;
2138 #ifdef NAMED_BIND
2139 			mci->mci_herrno = h_errno;
2140 #endif
2141 
2142 			/* and return the original host name as the signature */
2143 			nmx = 1;
2144 			mxhosts[0] = hp;
2145 		}
2146 
2147 		len = 0;
2148 		for (i = 0; i < nmx; i++)
2149 		{
2150 			len += strlen(mxhosts[i]) + 1;
2151 		}
2152 		if (s->s_hostsig != NULL)
2153 			len += strlen(s->s_hostsig) + 1;
2154 		p = xalloc(len);
2155 		if (s->s_hostsig != NULL)
2156 		{
2157 			(void) strcpy(p, s->s_hostsig);
2158 			free(s->s_hostsig);
2159 			s->s_hostsig = p;
2160 			p += strlen(p);
2161 			*p++ = ':';
2162 		}
2163 		else
2164 			s->s_hostsig = p;
2165 		for (i = 0; i < nmx; i++)
2166 		{
2167 			if (i != 0)
2168 				*p++ = ':';
2169 			strcpy(p, mxhosts[i]);
2170 			p += strlen(p);
2171 		}
2172 		if (endp != NULL)
2173 			*endp++ = ':';
2174 	}
2175 	makelower(s->s_hostsig);
2176 	if (ConfigLevel < 2)
2177 		_res.options = oldoptions;
2178 #else
2179 	/* not using BIND -- the signature is just the host name */
2180 	s->s_hostsig = host;
2181 #endif
2182 	if (tTd(17, 1))
2183 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2184 	return s->s_hostsig;
2185 }
2186