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