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