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