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