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