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