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