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