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