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