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.73 (Berkeley) 05/12/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 		else if (rcode == EX_TEMPFAIL)
1275 		{
1276 			/* try next MX site */
1277 			goto tryhost;
1278 		}
1279 	}
1280 	else if (!clever)
1281 	{
1282 		/*
1283 		**  Format and send message.
1284 		*/
1285 
1286 		putfromline(mci->mci_out, m, e);
1287 		(*e->e_puthdr)(mci->mci_out, m, e);
1288 		putline("\n", mci->mci_out, m);
1289 		(*e->e_putbody)(mci->mci_out, m, e, NULL);
1290 
1291 		/* get the exit status */
1292 		rcode = endmailer(mci, e, pv);
1293 	}
1294 	else
1295 #ifdef SMTP
1296 	{
1297 		/*
1298 		**  Send the MAIL FROM: protocol
1299 		*/
1300 
1301 		rcode = smtpmailfrom(m, mci, e);
1302 		if (rcode == EX_OK)
1303 		{
1304 			register char *t = tobuf;
1305 			register int i;
1306 
1307 			/* send the recipient list */
1308 			tobuf[0] = '\0';
1309 			for (to = tochain; to != NULL; to = to->q_tchain)
1310 			{
1311 				e->e_to = to->q_paddr;
1312 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1313 				{
1314 					markfailure(e, to, i);
1315 					giveresponse(i, m, mci, e);
1316 				}
1317 				else
1318 				{
1319 					*t++ = ',';
1320 					for (p = to->q_paddr; *p; *t++ = *p++)
1321 						continue;
1322 				}
1323 			}
1324 
1325 			/* now send the data */
1326 			if (tobuf[0] == '\0')
1327 			{
1328 				rcode = EX_OK;
1329 				e->e_to = NULL;
1330 				if (bitset(MCIF_CACHED, mci->mci_flags))
1331 					smtprset(m, mci, e);
1332 			}
1333 			else
1334 			{
1335 				e->e_to = tobuf + 1;
1336 				rcode = smtpdata(m, mci, e);
1337 			}
1338 
1339 			/* now close the connection */
1340 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1341 				smtpquit(m, mci, e);
1342 		}
1343 		if (rcode != EX_OK && *curhost != '\0')
1344 		{
1345 			/* try next MX site */
1346 			goto tryhost;
1347 		}
1348 	}
1349 #else /* not SMTP */
1350 	{
1351 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1352 		rcode = EX_CONFIG;
1353 		goto give_up;
1354 	}
1355 #endif /* SMTP */
1356 #ifdef NAMED_BIND
1357 	if (ConfigLevel < 2)
1358 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1359 #endif
1360 
1361 	/* arrange a return receipt if requested */
1362 	if (e->e_receiptto != NULL && bitnset(M_LOCALMAILER, m->m_flags))
1363 	{
1364 		e->e_flags |= EF_SENDRECEIPT;
1365 		/* do we want to send back more info? */
1366 	}
1367 
1368 	/*
1369 	**  Do final status disposal.
1370 	**	We check for something in tobuf for the SMTP case.
1371 	**	If we got a temporary failure, arrange to queue the
1372 	**		addressees.
1373 	*/
1374 
1375   give_up:
1376 	if (tobuf[0] != '\0')
1377 		giveresponse(rcode, m, mci, e);
1378 	for (to = tochain; to != NULL; to = to->q_tchain)
1379 	{
1380 		if (rcode != EX_OK)
1381 			markfailure(e, to, rcode);
1382 		else
1383 		{
1384 			to->q_flags |= QSENT;
1385 			e->e_nsent++;
1386 		}
1387 	}
1388 
1389 	/*
1390 	**  Restore state and return.
1391 	*/
1392 
1393 	errno = 0;
1394 	define('g', (char *) NULL, e);
1395 	return (rcode);
1396 }
1397 /*
1398 **  MARKFAILURE -- mark a failure on a specific address.
1399 **
1400 **	Parameters:
1401 **		e -- the envelope we are sending.
1402 **		q -- the address to mark.
1403 **		rcode -- the code signifying the particular failure.
1404 **
1405 **	Returns:
1406 **		none.
1407 **
1408 **	Side Effects:
1409 **		marks the address (and possibly the envelope) with the
1410 **			failure so that an error will be returned or
1411 **			the message will be queued, as appropriate.
1412 */
1413 
1414 markfailure(e, q, rcode)
1415 	register ENVELOPE *e;
1416 	register ADDRESS *q;
1417 	int rcode;
1418 {
1419 	char buf[MAXLINE];
1420 	extern char *pintvl();
1421 
1422 	if (rcode == EX_OK)
1423 		return;
1424 	else if (rcode != EX_TEMPFAIL && rcode != EX_IOERR && rcode != EX_OSERR)
1425 		q->q_flags |= QBADADDR;
1426 	else if (curtime() > e->e_ctime + TimeOuts.to_q_return)
1427 	{
1428 		if (!bitset(EF_TIMEOUT, e->e_flags))
1429 		{
1430 			(void) sprintf(buf, "Cannot send message for %s",
1431 				pintvl(TimeOuts.to_q_return, FALSE));
1432 			if (e->e_message != NULL)
1433 				free(e->e_message);
1434 			e->e_message = newstr(buf);
1435 			message(buf);
1436 		}
1437 		q->q_flags |= QBADADDR;
1438 		e->e_flags |= EF_TIMEOUT;
1439 		fprintf(e->e_xfp, "421 %s... Message timed out\n", q->q_paddr);
1440 	}
1441 	else
1442 	{
1443 		q->q_flags |= QQUEUEUP;
1444 		if (TimeOuts.to_q_warning > 0 &&
1445 		    curtime() > e->e_ctime + TimeOuts.to_q_warning)
1446 		{
1447 			if (!bitset(EF_WARNING, e->e_flags) &&
1448 			    e->e_class >= 0)
1449 			{
1450 				(void) sprintf(buf,
1451 					"warning: cannot send message for %s",
1452 					pintvl(TimeOuts.to_q_warning, FALSE));
1453 				if (e->e_message != NULL)
1454 					free(e->e_message);
1455 				e->e_message = newstr(buf);
1456 				message(buf);
1457 				e->e_flags |= EF_WARNING|EF_TIMEOUT;
1458 			}
1459 			fprintf(e->e_xfp,
1460 				"%s... Warning: message still undelivered after %s\n",
1461 				q->q_paddr, pintvl(TimeOuts.to_q_warning, FALSE));
1462 			fprintf(e->e_xfp, "Will keep trying until message is %s old\n",
1463 				pintvl(TimeOuts.to_q_return, FALSE));
1464 		}
1465 	}
1466 }
1467 /*
1468 **  ENDMAILER -- Wait for mailer to terminate.
1469 **
1470 **	We should never get fatal errors (e.g., segmentation
1471 **	violation), so we report those specially.  For other
1472 **	errors, we choose a status message (into statmsg),
1473 **	and if it represents an error, we print it.
1474 **
1475 **	Parameters:
1476 **		pid -- pid of mailer.
1477 **		e -- the current envelope.
1478 **		pv -- the parameter vector that invoked the mailer
1479 **			(for error messages).
1480 **
1481 **	Returns:
1482 **		exit code of mailer.
1483 **
1484 **	Side Effects:
1485 **		none.
1486 */
1487 
1488 endmailer(mci, e, pv)
1489 	register MCI *mci;
1490 	register ENVELOPE *e;
1491 	char **pv;
1492 {
1493 	int st;
1494 
1495 	/* close any connections */
1496 	if (mci->mci_in != NULL)
1497 		(void) xfclose(mci->mci_in, pv[0], "mci_in");
1498 	if (mci->mci_out != NULL)
1499 		(void) xfclose(mci->mci_out, pv[0], "mci_out");
1500 	mci->mci_in = mci->mci_out = NULL;
1501 	mci->mci_state = MCIS_CLOSED;
1502 
1503 	/* in the IPC case there is nothing to wait for */
1504 	if (mci->mci_pid == 0)
1505 		return (EX_OK);
1506 
1507 	/* wait for the mailer process to die and collect status */
1508 	st = waitfor(mci->mci_pid);
1509 	if (st == -1)
1510 	{
1511 		syserr("endmailer %s: wait", pv[0]);
1512 		return (EX_SOFTWARE);
1513 	}
1514 
1515 	/* see if it died a horrid death */
1516 	if ((st & 0377) != 0)
1517 	{
1518 		syserr("mailer %s died with signal %o", pv[0], st);
1519 
1520 		/* log the arguments */
1521 		if (e->e_xfp != NULL)
1522 		{
1523 			register char **av;
1524 
1525 			fprintf(e->e_xfp, "Arguments:");
1526 			for (av = pv; *av != NULL; av++)
1527 				fprintf(e->e_xfp, " %s", *av);
1528 			fprintf(e->e_xfp, "\n");
1529 		}
1530 
1531 		ExitStat = EX_TEMPFAIL;
1532 		return (EX_TEMPFAIL);
1533 	}
1534 
1535 	/* normal death -- return status */
1536 	st = (st >> 8) & 0377;
1537 	return (st);
1538 }
1539 /*
1540 **  GIVERESPONSE -- Interpret an error response from a mailer
1541 **
1542 **	Parameters:
1543 **		stat -- the status code from the mailer (high byte
1544 **			only; core dumps must have been taken care of
1545 **			already).
1546 **		m -- the mailer info for this mailer.
1547 **		mci -- the mailer connection info -- can be NULL if the
1548 **			response is given before the connection is made.
1549 **		e -- the current envelope.
1550 **
1551 **	Returns:
1552 **		none.
1553 **
1554 **	Side Effects:
1555 **		Errors may be incremented.
1556 **		ExitStat may be set.
1557 */
1558 
1559 giveresponse(stat, m, mci, e)
1560 	int stat;
1561 	register MAILER *m;
1562 	register MCI *mci;
1563 	ENVELOPE *e;
1564 {
1565 	register char *statmsg;
1566 	extern char *SysExMsg[];
1567 	register int i;
1568 	extern int N_SysEx;
1569 #ifdef NAMED_BIND
1570 	extern int h_errno;
1571 #endif
1572 	char buf[MAXLINE];
1573 	extern char *errstring();
1574 
1575 	/*
1576 	**  Compute status message from code.
1577 	*/
1578 
1579 	i = stat - EX__BASE;
1580 	if (stat == 0)
1581 	{
1582 		statmsg = "250 Sent";
1583 		if (e->e_statmsg != NULL)
1584 		{
1585 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1586 			statmsg = buf;
1587 		}
1588 	}
1589 	else if (i < 0 || i > N_SysEx)
1590 	{
1591 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1592 		stat = EX_UNAVAILABLE;
1593 		statmsg = buf;
1594 	}
1595 	else if (stat == EX_TEMPFAIL)
1596 	{
1597 		(void) strcpy(buf, SysExMsg[i] + 1);
1598 #ifdef NAMED_BIND
1599 		if (h_errno == TRY_AGAIN)
1600 			statmsg = errstring(h_errno+MAX_ERRNO);
1601 		else
1602 #endif
1603 		{
1604 			if (errno != 0)
1605 				statmsg = errstring(errno);
1606 			else
1607 			{
1608 #ifdef SMTP
1609 				extern char SmtpError[];
1610 
1611 				statmsg = SmtpError;
1612 #else /* SMTP */
1613 				statmsg = NULL;
1614 #endif /* SMTP */
1615 			}
1616 		}
1617 		if (statmsg != NULL && statmsg[0] != '\0')
1618 		{
1619 			(void) strcat(buf, ": ");
1620 			(void) strcat(buf, statmsg);
1621 		}
1622 		statmsg = buf;
1623 	}
1624 	else
1625 	{
1626 		statmsg = SysExMsg[i];
1627 		if (*statmsg++ == ':')
1628 		{
1629 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1630 			statmsg = buf;
1631 		}
1632 	}
1633 
1634 	/*
1635 	**  Print the message as appropriate
1636 	*/
1637 
1638 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1639 		message(&statmsg[4], errstring(errno));
1640 	else
1641 	{
1642 		Errors++;
1643 		usrerr(statmsg, errstring(errno));
1644 	}
1645 
1646 	/*
1647 	**  Final cleanup.
1648 	**	Log a record of the transaction.  Compute the new
1649 	**	ExitStat -- if we already had an error, stick with
1650 	**	that.
1651 	*/
1652 
1653 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1654 		logdelivery(m, mci, &statmsg[4], e);
1655 
1656 	if (stat != EX_TEMPFAIL)
1657 		setstat(stat);
1658 	if (stat != EX_OK)
1659 	{
1660 		if (e->e_message != NULL)
1661 			free(e->e_message);
1662 		e->e_message = newstr(&statmsg[4]);
1663 	}
1664 	errno = 0;
1665 #ifdef NAMED_BIND
1666 	h_errno = 0;
1667 #endif
1668 }
1669 /*
1670 **  LOGDELIVERY -- log the delivery in the system log
1671 **
1672 **	Parameters:
1673 **		m -- the mailer info.  Can be NULL for initial queue.
1674 **		mci -- the mailer connection info -- can be NULL if the
1675 **			log is occuring when no connection is active.
1676 **		stat -- the message to print for the status.
1677 **		e -- the current envelope.
1678 **
1679 **	Returns:
1680 **		none
1681 **
1682 **	Side Effects:
1683 **		none
1684 */
1685 
1686 logdelivery(m, mci, stat, e)
1687 	MAILER *m;
1688 	register MCI *mci;
1689 	char *stat;
1690 	register ENVELOPE *e;
1691 {
1692 # ifdef LOG
1693 	char *curhost;
1694 	char buf[512];
1695 	extern char *pintvl();
1696 	extern char *macvalue();
1697 
1698 	(void) sprintf(buf, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1699 
1700 	if (m != NULL)
1701 	{
1702 		(void) strcat(buf, ", mailer=");
1703 		(void) strcat(buf, m->m_name);
1704 	}
1705 
1706 	if (mci != NULL && mci->mci_host != NULL)
1707 	{
1708 # ifdef DAEMON
1709 		extern SOCKADDR CurHostAddr;
1710 		extern char *anynet_ntoa();
1711 # endif
1712 
1713 		(void) strcat(buf, ", relay=");
1714 		(void) strcat(buf, mci->mci_host);
1715 
1716 # ifdef DAEMON
1717 		(void) strcat(buf, " (");
1718 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
1719 		(void) strcat(buf, ")");
1720 # endif
1721 	}
1722 	else
1723 	{
1724 		char *p = macvalue('h', e);
1725 
1726 		if (p != NULL && p[0] != '\0')
1727 		{
1728 			(void) strcat(buf, ", relay=");
1729 			(void) strcat(buf, p);
1730 		}
1731 	}
1732 
1733 	syslog(LOG_INFO, "%s: to=%s, %s, stat=%s",
1734 	       e->e_id, e->e_to, buf, stat);
1735 # endif /* LOG */
1736 }
1737 /*
1738 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1739 **
1740 **	This can be made an arbitrary message separator by changing $l
1741 **
1742 **	One of the ugliest hacks seen by human eyes is contained herein:
1743 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1744 **	does a well-meaning programmer such as myself have to deal with
1745 **	this kind of antique garbage????
1746 **
1747 **	Parameters:
1748 **		fp -- the file to output to.
1749 **		m -- the mailer describing this entry.
1750 **
1751 **	Returns:
1752 **		none
1753 **
1754 **	Side Effects:
1755 **		outputs some text to fp.
1756 */
1757 
1758 putfromline(fp, m, e)
1759 	register FILE *fp;
1760 	register MAILER *m;
1761 	ENVELOPE *e;
1762 {
1763 	char *template = "\201l\n";
1764 	char buf[MAXLINE];
1765 
1766 	if (bitnset(M_NHDR, m->m_flags))
1767 		return;
1768 
1769 # ifdef UGLYUUCP
1770 	if (bitnset(M_UGLYUUCP, m->m_flags))
1771 	{
1772 		char *bang;
1773 		char xbuf[MAXLINE];
1774 
1775 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1776 		bang = strchr(buf, '!');
1777 		if (bang == NULL)
1778 			syserr("554 No ! in UUCP! (%s)", buf);
1779 		else
1780 		{
1781 			*bang++ = '\0';
1782 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1783 			template = xbuf;
1784 		}
1785 	}
1786 # endif /* UGLYUUCP */
1787 	expand(template, buf, &buf[sizeof buf - 1], e);
1788 	putline(buf, fp, m);
1789 }
1790 /*
1791 **  PUTBODY -- put the body of a message.
1792 **
1793 **	Parameters:
1794 **		fp -- file to output onto.
1795 **		m -- a mailer descriptor to control output format.
1796 **		e -- the envelope to put out.
1797 **		separator -- if non-NULL, a message separator that must
1798 **			not be permitted in the resulting message.
1799 **
1800 **	Returns:
1801 **		none.
1802 **
1803 **	Side Effects:
1804 **		The message is written onto fp.
1805 */
1806 
1807 putbody(fp, m, e, separator)
1808 	FILE *fp;
1809 	MAILER *m;
1810 	register ENVELOPE *e;
1811 	char *separator;
1812 {
1813 	char buf[MAXLINE];
1814 
1815 	/*
1816 	**  Output the body of the message
1817 	*/
1818 
1819 	if (e->e_dfp == NULL)
1820 	{
1821 		if (e->e_df != NULL)
1822 		{
1823 			e->e_dfp = fopen(e->e_df, "r");
1824 			if (e->e_dfp == NULL)
1825 				syserr("putbody: Cannot open %s for %s from %s",
1826 				e->e_df, e->e_to, e->e_from);
1827 		}
1828 		else
1829 			putline("<<< No Message Collected >>>", fp, m);
1830 	}
1831 	if (e->e_dfp != NULL)
1832 	{
1833 		rewind(e->e_dfp);
1834 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1835 		{
1836 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1837 			    strncmp(buf, "From ", 5) == 0)
1838 				(void) putc('>', fp);
1839 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
1840 			{
1841 				/* possible separator */
1842 				int sl = strlen(separator);
1843 
1844 				if (strncmp(&buf[2], separator, sl) == 0)
1845 					(void) putc(' ', fp);
1846 			}
1847 			putline(buf, fp, m);
1848 		}
1849 
1850 		if (ferror(e->e_dfp))
1851 		{
1852 			syserr("putbody: read error");
1853 			ExitStat = EX_IOERR;
1854 		}
1855 	}
1856 
1857 	/* some mailers want extra blank line at end of message */
1858 	if (bitnset(M_BLANKEND, m->m_flags) && buf[0] != '\0' && buf[0] != '\n')
1859 		putline("", fp, m);
1860 
1861 	(void) fflush(fp);
1862 	if (ferror(fp) && errno != EPIPE)
1863 	{
1864 		syserr("putbody: write error");
1865 		ExitStat = EX_IOERR;
1866 	}
1867 	errno = 0;
1868 }
1869 /*
1870 **  MAILFILE -- Send a message to a file.
1871 **
1872 **	If the file has the setuid/setgid bits set, but NO execute
1873 **	bits, sendmail will try to become the owner of that file
1874 **	rather than the real user.  Obviously, this only works if
1875 **	sendmail runs as root.
1876 **
1877 **	This could be done as a subordinate mailer, except that it
1878 **	is used implicitly to save messages in ~/dead.letter.  We
1879 **	view this as being sufficiently important as to include it
1880 **	here.  For example, if the system is dying, we shouldn't have
1881 **	to create another process plus some pipes to save the message.
1882 **
1883 **	Parameters:
1884 **		filename -- the name of the file to send to.
1885 **		ctladdr -- the controlling address header -- includes
1886 **			the userid/groupid to be when sending.
1887 **
1888 **	Returns:
1889 **		The exit code associated with the operation.
1890 **
1891 **	Side Effects:
1892 **		none.
1893 */
1894 
1895 mailfile(filename, ctladdr, e)
1896 	char *filename;
1897 	ADDRESS *ctladdr;
1898 	register ENVELOPE *e;
1899 {
1900 	register FILE *f;
1901 	register int pid;
1902 	int mode;
1903 
1904 	if (tTd(11, 1))
1905 	{
1906 		printf("mailfile %s\n  ctladdr=", filename);
1907 		printaddr(ctladdr, FALSE);
1908 	}
1909 
1910 	/*
1911 	**  Fork so we can change permissions here.
1912 	**	Note that we MUST use fork, not vfork, because of
1913 	**	the complications of calling subroutines, etc.
1914 	*/
1915 
1916 	DOFORK(fork);
1917 
1918 	if (pid < 0)
1919 		return (EX_OSERR);
1920 	else if (pid == 0)
1921 	{
1922 		/* child -- actually write to file */
1923 		struct stat stb;
1924 
1925 		(void) signal(SIGINT, SIG_DFL);
1926 		(void) signal(SIGHUP, SIG_DFL);
1927 		(void) signal(SIGTERM, SIG_DFL);
1928 		(void) umask(OldUmask);
1929 
1930 		if (stat(filename, &stb) < 0)
1931 			stb.st_mode = FileMode;
1932 		mode = stb.st_mode;
1933 
1934 		/* limit the errors to those actually caused in the child */
1935 		errno = 0;
1936 		ExitStat = EX_OK;
1937 
1938 		if (bitset(0111, stb.st_mode))
1939 			exit(EX_CANTCREAT);
1940 		if (ctladdr == NULL)
1941 			ctladdr = &e->e_from;
1942 		else
1943 		{
1944 			/* ignore setuid and setgid bits */
1945 			mode &= ~(S_ISGID|S_ISUID);
1946 		}
1947 
1948 		/* we have to open the dfile BEFORE setuid */
1949 		if (e->e_dfp == NULL && e->e_df != NULL)
1950 		{
1951 			e->e_dfp = fopen(e->e_df, "r");
1952 			if (e->e_dfp == NULL)
1953 			{
1954 				syserr("mailfile: Cannot open %s for %s from %s",
1955 					e->e_df, e->e_to, e->e_from);
1956 			}
1957 		}
1958 
1959 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
1960 		{
1961 			if (ctladdr->q_uid == 0)
1962 			{
1963 				(void) setgid(DefGid);
1964 				(void) initgroups(DefUser, DefGid);
1965 			}
1966 			else
1967 			{
1968 				(void) setgid(ctladdr->q_gid);
1969 				(void) initgroups(ctladdr->q_ruser ?
1970 					ctladdr->q_ruser : ctladdr->q_user,
1971 					ctladdr->q_gid);
1972 			}
1973 		}
1974 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
1975 		{
1976 			if (ctladdr->q_uid == 0)
1977 				(void) setuid(DefUid);
1978 			else
1979 				(void) setuid(ctladdr->q_uid);
1980 		}
1981 		FileName = filename;
1982 		LineNumber = 0;
1983 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
1984 		if (f == NULL)
1985 		{
1986 			message("554 cannot open");
1987 			exit(EX_CANTCREAT);
1988 		}
1989 
1990 		putfromline(f, FileMailer, e);
1991 		(*e->e_puthdr)(f, FileMailer, e);
1992 		putline("\n", f, FileMailer);
1993 		(*e->e_putbody)(f, FileMailer, e, NULL);
1994 		putline("\n", f, FileMailer);
1995 		if (ferror(f))
1996 		{
1997 			message("451 I/O error");
1998 			setstat(EX_IOERR);
1999 		}
2000 		(void) xfclose(f, "mailfile", filename);
2001 		(void) fflush(stdout);
2002 
2003 		/* reset ISUID & ISGID bits for paranoid systems */
2004 		(void) chmod(filename, (int) stb.st_mode);
2005 		exit(ExitStat);
2006 		/*NOTREACHED*/
2007 	}
2008 	else
2009 	{
2010 		/* parent -- wait for exit status */
2011 		int st;
2012 
2013 		st = waitfor(pid);
2014 		if ((st & 0377) != 0)
2015 			return (EX_UNAVAILABLE);
2016 		else
2017 			return ((st >> 8) & 0377);
2018 		/*NOTREACHED*/
2019 	}
2020 }
2021 /*
2022 **  HOSTSIGNATURE -- return the "signature" for a host.
2023 **
2024 **	The signature describes how we are going to send this -- it
2025 **	can be just the hostname (for non-Internet hosts) or can be
2026 **	an ordered list of MX hosts.
2027 **
2028 **	Parameters:
2029 **		m -- the mailer describing this host.
2030 **		host -- the host name.
2031 **		e -- the current envelope.
2032 **
2033 **	Returns:
2034 **		The signature for this host.
2035 **
2036 **	Side Effects:
2037 **		Can tweak the symbol table.
2038 */
2039 
2040 char *
2041 hostsignature(m, host, e)
2042 	register MAILER *m;
2043 	char *host;
2044 	ENVELOPE *e;
2045 {
2046 	register char *p;
2047 	register STAB *s;
2048 	int i;
2049 	int len;
2050 #ifdef NAMED_BIND
2051 	int nmx;
2052 	auto int rcode;
2053 	char *hp;
2054 	char *endp;
2055 	int oldoptions;
2056 	char *mxhosts[MAXMXHOSTS + 1];
2057 #endif
2058 
2059 	/*
2060 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2061 	*/
2062 
2063 	p = m->m_mailer;
2064 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2065 	{
2066 		/* just an ordinary mailer */
2067 		return host;
2068 	}
2069 
2070 	/*
2071 	**  If it is a numeric address, just return it.
2072 	*/
2073 
2074 	if (host[0] == '[')
2075 		return host;
2076 
2077 	/*
2078 	**  Look it up in the symbol table.
2079 	*/
2080 
2081 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2082 	if (s->s_hostsig != NULL)
2083 		return s->s_hostsig;
2084 
2085 	/*
2086 	**  Not already there -- create a signature.
2087 	*/
2088 
2089 #ifdef NAMED_BIND
2090 	if (ConfigLevel < 2)
2091 	{
2092 		oldoptions = _res.options;
2093 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2094 	}
2095 
2096 	for (hp = host; hp != NULL; hp = endp)
2097 	{
2098 		endp = strchr(hp, ':');
2099 		if (endp != NULL)
2100 			*endp = '\0';
2101 
2102 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2103 
2104 		if (nmx <= 0)
2105 		{
2106 			register MCI *mci;
2107 			extern int errno;
2108 			extern MCI *mci_get();
2109 
2110 			/* update the connection info for this host */
2111 			mci = mci_get(hp, m);
2112 			mci->mci_exitstat = rcode;
2113 			mci->mci_errno = errno;
2114 
2115 			/* and return the original host name as the signature */
2116 			nmx = 1;
2117 			mxhosts[0] = hp;
2118 		}
2119 
2120 		len = 0;
2121 		for (i = 0; i < nmx; i++)
2122 		{
2123 			len += strlen(mxhosts[i]) + 1;
2124 		}
2125 		if (s->s_hostsig != NULL)
2126 			len += strlen(s->s_hostsig) + 1;
2127 		p = xalloc(len);
2128 		if (s->s_hostsig != NULL)
2129 		{
2130 			(void) strcpy(p, s->s_hostsig);
2131 			free(s->s_hostsig);
2132 			s->s_hostsig = p;
2133 			p += strlen(p);
2134 			*p++ = ':';
2135 		}
2136 		else
2137 			s->s_hostsig = p;
2138 		for (i = 0; i < nmx; i++)
2139 		{
2140 			if (i != 0)
2141 				*p++ = ':';
2142 			strcpy(p, mxhosts[i]);
2143 			p += strlen(p);
2144 		}
2145 		if (endp != NULL)
2146 			*endp++ = ':';
2147 	}
2148 	makelower(s->s_hostsig);
2149 	if (ConfigLevel < 2)
2150 		_res.options = oldoptions;
2151 #else
2152 	/* not using BIND -- the signature is just the host name */
2153 	s->s_hostsig = host;
2154 #endif
2155 	if (tTd(17, 1))
2156 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2157 	return s->s_hostsig;
2158 }
2159