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