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.13 (Berkeley) 01/28/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 = -1;
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 = -1;
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 				return mci;
790 			}
791 			mci->mci_mailer = m;
792 			if (mci->mci_exitstat != EX_OK)
793 				continue;
794 
795 			/* try the connection */
796 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
797 			message(Arpa_Info, "Connecting to %s (%s)...",
798 				hostbuf, m->m_name);
799 			i = makeconnection(hostbuf, port, mci,
800 				bitnset(M_SECURE_PORT, m->m_flags));
801 			mci->mci_exitstat = i;
802 			mci->mci_errno = errno;
803 			if (i == EX_OK)
804 			{
805 				mci->mci_state = MCIS_OPENING;
806 				mci_cache(mci);
807 				break;
808 			}
809 			else if (tTd(11, 1))
810 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
811 					i, errno);
812 
813 
814 			/* enter status of this host */
815 			setstat(i);
816 		}
817 		mci->mci_pid = 0;
818 #else /* no DAEMON */
819 		syserr("openmailer: no IPC");
820 		if (tTd(11, 1))
821 			printf("openmailer: NULL\n");
822 		return NULL;
823 #endif /* DAEMON */
824 	}
825 	else
826 	{
827 		/* create a pipe to shove the mail through */
828 		if (pipe(mpvect) < 0)
829 		{
830 			syserr("openmailer: pipe (to mailer)");
831 			if (tTd(11, 1))
832 				printf("openmailer: NULL\n");
833 			return NULL;
834 		}
835 
836 		/* if this mailer speaks smtp, create a return pipe */
837 		if (clever && pipe(rpvect) < 0)
838 		{
839 			syserr("openmailer: pipe (from mailer)");
840 			(void) close(mpvect[0]);
841 			(void) close(mpvect[1]);
842 			if (tTd(11, 1))
843 				printf("openmailer: NULL\n");
844 			return NULL;
845 		}
846 
847 		/*
848 		**  Actually fork the mailer process.
849 		**	DOFORK is clever about retrying.
850 		**
851 		**	Dispose of SIGCHLD signal catchers that may be laying
852 		**	around so that endmail will get it.
853 		*/
854 
855 		if (e->e_xfp != NULL)
856 			(void) fflush(e->e_xfp);		/* for debugging */
857 		(void) fflush(stdout);
858 # ifdef SIGCHLD
859 		(void) signal(SIGCHLD, SIG_DFL);
860 # endif /* SIGCHLD */
861 		DOFORK(FORK);
862 		/* pid is set by DOFORK */
863 		if (pid < 0)
864 		{
865 			/* failure */
866 			syserr("openmailer: cannot fork");
867 			(void) close(mpvect[0]);
868 			(void) close(mpvect[1]);
869 			if (clever)
870 			{
871 				(void) close(rpvect[0]);
872 				(void) close(rpvect[1]);
873 			}
874 			if (tTd(11, 1))
875 				printf("openmailer: NULL\n");
876 			return NULL;
877 		}
878 		else if (pid == 0)
879 		{
880 			int i;
881 			int saveerrno;
882 			char *env[2];
883 			extern int DtableSize;
884 
885 			/* child -- set up input & exec mailer */
886 			/* make diagnostic output be standard output */
887 			(void) signal(SIGINT, SIG_IGN);
888 			(void) signal(SIGHUP, SIG_IGN);
889 			(void) signal(SIGTERM, SIG_DFL);
890 
891 			/* arrange to filter std & diag output of command */
892 			if (clever)
893 			{
894 				(void) close(rpvect[0]);
895 				(void) close(1);
896 				(void) dup(rpvect[1]);
897 				(void) close(rpvect[1]);
898 			}
899 			else if (OpMode == MD_SMTP || HoldErrs)
900 			{
901 				/* put mailer output in transcript */
902 				(void) close(1);
903 				(void) dup(fileno(e->e_xfp));
904 			}
905 			(void) close(2);
906 			(void) dup(1);
907 
908 			/* arrange to get standard input */
909 			(void) close(mpvect[1]);
910 			(void) close(0);
911 			if (dup(mpvect[0]) < 0)
912 			{
913 				syserr("Cannot dup to zero!");
914 				_exit(EX_OSERR);
915 			}
916 			(void) close(mpvect[0]);
917 			if (!bitnset(M_RESTR, m->m_flags))
918 			{
919 				if (ctladdr == NULL || ctladdr->q_uid == 0)
920 				{
921 					(void) setgid(DefGid);
922 #ifndef SYSTEM5
923 					(void) initgroups(DefUser, DefGid);
924 #endif
925 					(void) setuid(DefUid);
926 				}
927 				else
928 				{
929 					(void) setgid(ctladdr->q_gid);
930 #ifndef SYSTEM5
931 					(void) initgroups(ctladdr->q_ruser?
932 						ctladdr->q_ruser: ctladdr->q_user,
933 						ctladdr->q_gid);
934 #endif
935 					(void) setuid(ctladdr->q_uid);
936 				}
937 			}
938 
939 			/* arrange for all the files to be closed */
940 			for (i = 3; i < DtableSize; i++)
941 			{
942 				register int j;
943 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
944 					(void)fcntl(i, F_SETFD, j|1);
945 			}
946 
947 			/* try to execute the mailer */
948 			env[0] = "AGENT=sendmail";
949 			env[1] = NULL;
950 			execve(m->m_mailer, pvp, env);
951 			saveerrno = errno;
952 			syserr("Cannot exec %s", m->m_mailer);
953 			if (m == LocalMailer)
954 				_exit(EX_TEMPFAIL);
955 			switch (saveerrno)
956 			{
957 			  case EIO:
958 			  case EAGAIN:
959 			  case ENOMEM:
960 # ifdef EPROCLIM
961 			  case EPROCLIM:
962 # endif
963 				_exit(EX_TEMPFAIL);
964 			}
965 			_exit(EX_UNAVAILABLE);
966 		}
967 
968 		/*
969 		**  Set up return value.
970 		*/
971 
972 		mci = (MCI *) xalloc(sizeof *mci);
973 		bzero((char *) mci, sizeof *mci);
974 		mci->mci_mailer = m;
975 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
976 		mci->mci_pid = pid;
977 		(void) close(mpvect[0]);
978 		mci->mci_out = fdopen(mpvect[1], "w");
979 		if (clever)
980 		{
981 			(void) close(rpvect[1]);
982 			mci->mci_in = fdopen(rpvect[0], "r");
983 		}
984 		else
985 		{
986 			mci->mci_flags |= MCIF_TEMP;
987 			mci->mci_in = NULL;
988 		}
989 	}
990 
991 	/*
992 	**  If we are in SMTP opening state, send initial protocol.
993 	*/
994 
995 	if (clever && mci->mci_state != MCIS_CLOSED)
996 	{
997 		smtpinit(m, mci, e);
998 	}
999 	if (tTd(11, 1))
1000 	{
1001 		printf("openmailer: ");
1002 		mci_dump(mci);
1003 	}
1004 
1005 	return mci;
1006 }
1007 /*
1008 **  GIVERESPONSE -- Interpret an error response from a mailer
1009 **
1010 **	Parameters:
1011 **		stat -- the status code from the mailer (high byte
1012 **			only; core dumps must have been taken care of
1013 **			already).
1014 **		m -- the mailer descriptor for this mailer.
1015 **
1016 **	Returns:
1017 **		none.
1018 **
1019 **	Side Effects:
1020 **		Errors may be incremented.
1021 **		ExitStat may be set.
1022 */
1023 
1024 giveresponse(stat, m, e)
1025 	int stat;
1026 	register MAILER *m;
1027 	ENVELOPE *e;
1028 {
1029 	register char *statmsg;
1030 	extern char *SysExMsg[];
1031 	register int i;
1032 	extern int N_SysEx;
1033 #ifdef NAMED_BIND
1034 	extern int h_errno;
1035 #endif
1036 	char buf[MAXLINE];
1037 
1038 #ifdef lint
1039 	if (m == NULL)
1040 		return;
1041 #endif lint
1042 
1043 	/*
1044 	**  Compute status message from code.
1045 	*/
1046 
1047 	i = stat - EX__BASE;
1048 	if (stat == 0)
1049 		statmsg = "250 Sent";
1050 	else if (i < 0 || i > N_SysEx)
1051 	{
1052 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1053 		stat = EX_UNAVAILABLE;
1054 		statmsg = buf;
1055 	}
1056 	else if (stat == EX_TEMPFAIL)
1057 	{
1058 		(void) strcpy(buf, SysExMsg[i]);
1059 #ifdef NAMED_BIND
1060 		if (h_errno == TRY_AGAIN)
1061 		{
1062 			extern char *errstring();
1063 
1064 			statmsg = errstring(h_errno+MAX_ERRNO);
1065 		}
1066 		else
1067 #endif
1068 		{
1069 			if (errno != 0)
1070 			{
1071 				extern char *errstring();
1072 
1073 				statmsg = errstring(errno);
1074 			}
1075 			else
1076 			{
1077 #ifdef SMTP
1078 				extern char SmtpError[];
1079 
1080 				statmsg = SmtpError;
1081 #else /* SMTP */
1082 				statmsg = NULL;
1083 #endif /* SMTP */
1084 			}
1085 		}
1086 		if (statmsg != NULL && statmsg[0] != '\0')
1087 		{
1088 			(void) strcat(buf, ": ");
1089 			(void) strcat(buf, statmsg);
1090 		}
1091 		statmsg = buf;
1092 	}
1093 	else
1094 	{
1095 		statmsg = SysExMsg[i];
1096 	}
1097 
1098 	/*
1099 	**  Print the message as appropriate
1100 	*/
1101 
1102 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1103 		message(Arpa_Info, &statmsg[4]);
1104 	else
1105 	{
1106 		Errors++;
1107 		usrerr(statmsg);
1108 	}
1109 
1110 	/*
1111 	**  Final cleanup.
1112 	**	Log a record of the transaction.  Compute the new
1113 	**	ExitStat -- if we already had an error, stick with
1114 	**	that.
1115 	*/
1116 
1117 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
1118 		logdelivery(&statmsg[4], e);
1119 
1120 	if (stat != EX_TEMPFAIL)
1121 		setstat(stat);
1122 	if (stat != EX_OK)
1123 	{
1124 		if (e->e_message != NULL)
1125 			free(e->e_message);
1126 		e->e_message = newstr(&statmsg[4]);
1127 	}
1128 	errno = 0;
1129 #ifdef NAMED_BIND
1130 	h_errno = 0;
1131 #endif
1132 }
1133 /*
1134 **  LOGDELIVERY -- log the delivery in the system log
1135 **
1136 **	Parameters:
1137 **		stat -- the message to print for the status
1138 **
1139 **	Returns:
1140 **		none
1141 **
1142 **	Side Effects:
1143 **		none
1144 */
1145 
1146 logdelivery(stat, e)
1147 	char *stat;
1148 	register ENVELOPE *e;
1149 {
1150 	extern char *pintvl();
1151 
1152 # ifdef LOG
1153 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", e->e_id,
1154 	       e->e_to, pintvl(curtime() - e->e_ctime, TRUE), stat);
1155 # endif /* LOG */
1156 }
1157 /*
1158 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1159 **
1160 **	This can be made an arbitrary message separator by changing $l
1161 **
1162 **	One of the ugliest hacks seen by human eyes is contained herein:
1163 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1164 **	does a well-meaning programmer such as myself have to deal with
1165 **	this kind of antique garbage????
1166 **
1167 **	Parameters:
1168 **		fp -- the file to output to.
1169 **		m -- the mailer describing this entry.
1170 **
1171 **	Returns:
1172 **		none
1173 **
1174 **	Side Effects:
1175 **		outputs some text to fp.
1176 */
1177 
1178 putfromline(fp, m, e)
1179 	register FILE *fp;
1180 	register MAILER *m;
1181 	ENVELOPE *e;
1182 {
1183 	char *template = "\001l\n";
1184 	char buf[MAXLINE];
1185 
1186 	if (bitnset(M_NHDR, m->m_flags))
1187 		return;
1188 
1189 # ifdef UGLYUUCP
1190 	if (bitnset(M_UGLYUUCP, m->m_flags))
1191 	{
1192 		char *bang;
1193 		char xbuf[MAXLINE];
1194 
1195 		expand("\001<", buf, &buf[sizeof buf - 1], e);
1196 		bang = strchr(buf, '!');
1197 		if (bang == NULL)
1198 			syserr("No ! in UUCP! (%s)", buf);
1199 		else
1200 		{
1201 			*bang++ = '\0';
1202 			(void) sprintf(xbuf, "From %s  \001d remote from %s\n", bang, buf);
1203 			template = xbuf;
1204 		}
1205 	}
1206 # endif /* UGLYUUCP */
1207 	expand(template, buf, &buf[sizeof buf - 1], e);
1208 	putline(buf, fp, m);
1209 }
1210 /*
1211 **  PUTBODY -- put the body of a message.
1212 **
1213 **	Parameters:
1214 **		fp -- file to output onto.
1215 **		m -- a mailer descriptor to control output format.
1216 **		e -- the envelope to put out.
1217 **
1218 **	Returns:
1219 **		none.
1220 **
1221 **	Side Effects:
1222 **		The message is written onto fp.
1223 */
1224 
1225 putbody(fp, m, e)
1226 	FILE *fp;
1227 	MAILER *m;
1228 	register ENVELOPE *e;
1229 {
1230 	char buf[MAXLINE];
1231 
1232 	/*
1233 	**  Output the body of the message
1234 	*/
1235 
1236 	if (e->e_dfp == NULL)
1237 	{
1238 		if (e->e_df != NULL)
1239 		{
1240 			e->e_dfp = fopen(e->e_df, "r");
1241 			if (e->e_dfp == NULL)
1242 				syserr("putbody: Cannot open %s for %s from %s",
1243 				e->e_df, e->e_to, e->e_from);
1244 		}
1245 		else
1246 			putline("<<< No Message Collected >>>", fp, m);
1247 	}
1248 	if (e->e_dfp != NULL)
1249 	{
1250 		rewind(e->e_dfp);
1251 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1252 		{
1253 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1254 			    strncmp(buf, "From ", 5) == 0)
1255 				(void) putc('>', fp);
1256 			putline(buf, fp, m);
1257 		}
1258 
1259 		if (ferror(e->e_dfp))
1260 		{
1261 			syserr("putbody: read error");
1262 			ExitStat = EX_IOERR;
1263 		}
1264 	}
1265 
1266 	(void) fflush(fp);
1267 	if (ferror(fp) && errno != EPIPE)
1268 	{
1269 		syserr("putbody: write error");
1270 		ExitStat = EX_IOERR;
1271 	}
1272 	errno = 0;
1273 }
1274 /*
1275 **  MAILFILE -- Send a message to a file.
1276 **
1277 **	If the file has the setuid/setgid bits set, but NO execute
1278 **	bits, sendmail will try to become the owner of that file
1279 **	rather than the real user.  Obviously, this only works if
1280 **	sendmail runs as root.
1281 **
1282 **	This could be done as a subordinate mailer, except that it
1283 **	is used implicitly to save messages in ~/dead.letter.  We
1284 **	view this as being sufficiently important as to include it
1285 **	here.  For example, if the system is dying, we shouldn't have
1286 **	to create another process plus some pipes to save the message.
1287 **
1288 **	Parameters:
1289 **		filename -- the name of the file to send to.
1290 **		ctladdr -- the controlling address header -- includes
1291 **			the userid/groupid to be when sending.
1292 **
1293 **	Returns:
1294 **		The exit code associated with the operation.
1295 **
1296 **	Side Effects:
1297 **		none.
1298 */
1299 
1300 mailfile(filename, ctladdr, e)
1301 	char *filename;
1302 	ADDRESS *ctladdr;
1303 	register ENVELOPE *e;
1304 {
1305 	register FILE *f;
1306 	register int pid;
1307 	int mode;
1308 
1309 	/*
1310 	**  Fork so we can change permissions here.
1311 	**	Note that we MUST use fork, not vfork, because of
1312 	**	the complications of calling subroutines, etc.
1313 	*/
1314 
1315 	DOFORK(fork);
1316 
1317 	if (pid < 0)
1318 		return (EX_OSERR);
1319 	else if (pid == 0)
1320 	{
1321 		/* child -- actually write to file */
1322 		struct stat stb;
1323 
1324 		(void) signal(SIGINT, SIG_DFL);
1325 		(void) signal(SIGHUP, SIG_DFL);
1326 		(void) signal(SIGTERM, SIG_DFL);
1327 		(void) umask(OldUmask);
1328 
1329 		if (stat(filename, &stb) < 0)
1330 			stb.st_mode = 0666;
1331 		mode = stb.st_mode;
1332 
1333 		/* limit the errors to those actually caused in the child */
1334 		errno = 0;
1335 		ExitStat = EX_OK;
1336 
1337 		if (bitset(0111, stb.st_mode))
1338 			exit(EX_CANTCREAT);
1339 		if (ctladdr == NULL)
1340 			ctladdr = &e->e_from;
1341 		else
1342 		{
1343 			/* ignore setuid and setgid bits */
1344 			mode &= ~(S_ISGID|S_ISUID);
1345 		}
1346 
1347 		/* we have to open the dfile BEFORE setuid */
1348 		if (e->e_dfp == NULL && e->e_df != NULL)
1349 		{
1350 			e->e_dfp = fopen(e->e_df, "r");
1351 			if (e->e_dfp == NULL)
1352 			{
1353 				syserr("mailfile: Cannot open %s for %s from %s",
1354 					e->e_df, e->e_to, e->e_from);
1355 			}
1356 		}
1357 
1358 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
1359 		{
1360 			if (ctladdr->q_uid == 0)
1361 			{
1362 				(void) setgid(DefGid);
1363 #ifndef SYSTEM5
1364 				(void) initgroups(DefUser, DefGid);
1365 #endif
1366 			}
1367 			else
1368 			{
1369 				(void) setgid(ctladdr->q_gid);
1370 #ifndef SYSTEM5
1371 				(void) initgroups(ctladdr->q_ruser ?
1372 					ctladdr->q_ruser : ctladdr->q_user,
1373 					ctladdr->q_gid);
1374 #endif
1375 			}
1376 		}
1377 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
1378 		{
1379 			if (ctladdr->q_uid == 0)
1380 				(void) setuid(DefUid);
1381 			else
1382 				(void) setuid(ctladdr->q_uid);
1383 		}
1384 		FileName = filename;
1385 		LineNumber = 0;
1386 		f = dfopen(filename, "a");
1387 		if (f == NULL)
1388 		{
1389 			message("cannot open");
1390 			exit(EX_CANTCREAT);
1391 		}
1392 
1393 		putfromline(f, ProgMailer, e);
1394 		(*e->e_puthdr)(f, ProgMailer, e);
1395 		putline("\n", f, ProgMailer);
1396 		(*e->e_putbody)(f, ProgMailer, e);
1397 		putline("\n", f, ProgMailer);
1398 		if (ferror(f))
1399 		{
1400 			message("I/O error");
1401 			setstat(EX_IOERR);
1402 		}
1403 		(void) fclose(f);
1404 		(void) fflush(stdout);
1405 
1406 		/* reset ISUID & ISGID bits for paranoid systems */
1407 		(void) chmod(filename, (int) stb.st_mode);
1408 		exit(ExitStat);
1409 		/*NOTREACHED*/
1410 	}
1411 	else
1412 	{
1413 		/* parent -- wait for exit status */
1414 		int st;
1415 
1416 		st = waitfor(pid);
1417 		if ((st & 0377) != 0)
1418 			return (EX_UNAVAILABLE);
1419 		else
1420 			return ((st >> 8) & 0377);
1421 		/*NOTREACHED*/
1422 	}
1423 }
1424 /*
1425 **  SENDALL -- actually send all the messages.
1426 **
1427 **	Parameters:
1428 **		e -- the envelope to send.
1429 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
1430 **			the current SendMode.
1431 **
1432 **	Returns:
1433 **		none.
1434 **
1435 **	Side Effects:
1436 **		Scans the send lists and sends everything it finds.
1437 **		Delivers any appropriate error messages.
1438 **		If we are running in a non-interactive mode, takes the
1439 **			appropriate action.
1440 */
1441 
1442 sendall(e, mode)
1443 	ENVELOPE *e;
1444 	char mode;
1445 {
1446 	register ADDRESS *q;
1447 	bool oldverbose;
1448 	int pid;
1449 # ifdef LOCKF
1450 	struct flock lfd;
1451 # endif
1452 
1453 	/* determine actual delivery mode */
1454 	if (mode == SM_DEFAULT)
1455 	{
1456 		extern bool shouldqueue();
1457 
1458 		if (shouldqueue(e->e_msgpriority, e->e_ctime))
1459 			mode = SM_QUEUE;
1460 		else
1461 			mode = SendMode;
1462 	}
1463 
1464 	if (tTd(13, 1))
1465 	{
1466 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1467 		printaddr(e->e_sendqueue, TRUE);
1468 	}
1469 
1470 	/*
1471 	**  Do any preprocessing necessary for the mode we are running.
1472 	**	Check to make sure the hop count is reasonable.
1473 	**	Delete sends to the sender in mailing lists.
1474 	*/
1475 
1476 	CurEnv = e;
1477 
1478 	if (e->e_hopcount > MaxHopCount)
1479 	{
1480 		errno = 0;
1481 		syserr("sendall: too many hops %d (%d max): from %s, to %s",
1482 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
1483 			e->e_sendqueue->q_paddr);
1484 		return;
1485 	}
1486 
1487 	if (!MeToo)
1488 	{
1489 		extern ADDRESS *recipient();
1490 
1491 		e->e_from.q_flags |= QDONTSEND;
1492 		if (tTd(13, 5))
1493 		{
1494 			printf("sendall: QDONTSEND ");
1495 			printaddr(&e->e_from, FALSE);
1496 		}
1497 		(void) recipient(&e->e_from, &e->e_sendqueue, e);
1498 	}
1499 
1500 # ifdef QUEUE
1501 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1502 	     (mode != SM_VERIFY && SuperSafe)) &&
1503 	    !bitset(EF_INQUEUE, e->e_flags))
1504 		queueup(e, TRUE, mode == SM_QUEUE);
1505 #endif /* QUEUE */
1506 
1507 	oldverbose = Verbose;
1508 	switch (mode)
1509 	{
1510 	  case SM_VERIFY:
1511 		Verbose = TRUE;
1512 		break;
1513 
1514 	  case SM_QUEUE:
1515   queueonly:
1516 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1517 		return;
1518 
1519 	  case SM_FORK:
1520 		if (e->e_xfp != NULL)
1521 			(void) fflush(e->e_xfp);
1522 
1523 # ifdef LOCKF
1524 		/*
1525 		**  Since lockf has the interesting semantic that the
1526 		**  lock is lost when we fork, we have to risk losing
1527 		**  the lock here by closing before the fork, and then
1528 		**  trying to get it back in the child.
1529 		*/
1530 
1531 		if (e->e_lockfp != NULL)
1532 		{
1533 			(void) fclose(e->e_lockfp);
1534 			e->e_lockfp = NULL;
1535 		}
1536 # endif /* LOCKF */
1537 
1538 		pid = fork();
1539 		if (pid < 0)
1540 		{
1541 			goto queueonly;
1542 		}
1543 		else if (pid > 0)
1544 		{
1545 			/* be sure we leave the temp files to our child */
1546 			e->e_id = e->e_df = NULL;
1547 # ifndef LOCKF
1548 			if (e->e_lockfp != NULL)
1549 			{
1550 				(void) fclose(e->e_lockfp);
1551 				e->e_lockfp = NULL;
1552 			}
1553 # endif
1554 
1555 			/* close any random open files in the envelope */
1556 			if (e->e_dfp != NULL)
1557 			{
1558 				(void) fclose(e->e_dfp);
1559 				e->e_dfp = NULL;
1560 			}
1561 			if (e->e_xfp != NULL)
1562 			{
1563 				(void) fclose(e->e_xfp);
1564 				e->e_xfp = NULL;
1565 			}
1566 			return;
1567 		}
1568 
1569 		/* double fork to avoid zombies */
1570 		if (fork() > 0)
1571 			exit(EX_OK);
1572 
1573 		/* be sure we are immune from the terminal */
1574 		disconnect(FALSE);
1575 
1576 # ifdef LOCKF
1577 		/*
1578 		**  Now try to get our lock back.
1579 		*/
1580 
1581 		lfd.l_type = F_WRLCK;
1582 		lfd.l_whence = lfd.l_start = lfd.l_len = 0;
1583 		e->e_lockfp = fopen(queuename(e, 'q'), "r+");
1584 		if (e->e_lockfp == NULL ||
1585 		    fcntl(fileno(e->e_lockfp), F_SETLK, &lfd) < 0)
1586 		{
1587 			/* oops....  lost it */
1588 # ifdef LOG
1589 			if (LogLevel > 5)
1590 				syslog(LOG_NOTICE, "%s: lost lock: %m",
1591 					e->e_id);
1592 # endif /* LOG */
1593 			exit(EX_OK);
1594 		}
1595 # endif /* LOCKF */
1596 
1597 		break;
1598 	}
1599 
1600 	/*
1601 	**  Run through the list and send everything.
1602 	*/
1603 
1604 	e->e_nsent = 0;
1605 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1606 	{
1607 		if (mode == SM_VERIFY)
1608 		{
1609 			e->e_to = q->q_paddr;
1610 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1611 				message(Arpa_Info, "deliverable");
1612 		}
1613 		else if (!bitset(QDONTSEND, q->q_flags))
1614 		{
1615 # ifdef QUEUE
1616 			/*
1617 			**  Checkpoint the send list every few addresses
1618 			*/
1619 
1620 			if (e->e_nsent >= CheckpointInterval)
1621 			{
1622 				queueup(e, TRUE, FALSE);
1623 				e->e_nsent = 0;
1624 			}
1625 # endif /* QUEUE */
1626 			(void) deliver(e, q);
1627 		}
1628 	}
1629 	Verbose = oldverbose;
1630 
1631 	/*
1632 	**  Now run through and check for errors.
1633 	*/
1634 
1635 	if (mode == SM_VERIFY)
1636 		return;
1637 
1638 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1639 	{
1640 		register ADDRESS *qq;
1641 
1642 		if (tTd(13, 3))
1643 		{
1644 			printf("Checking ");
1645 			printaddr(q, FALSE);
1646 		}
1647 
1648 		/* only send errors if the message failed */
1649 		if (!bitset(QBADADDR, q->q_flags))
1650 			continue;
1651 
1652 		/* we have an address that failed -- find the parent */
1653 		for (qq = q; qq != NULL; qq = qq->q_alias)
1654 		{
1655 			char obuf[MAXNAME + 6];
1656 			extern char *aliaslookup();
1657 
1658 			/* we can only have owners for local addresses */
1659 			if (!bitnset(M_LOCAL, qq->q_mailer->m_flags))
1660 				continue;
1661 
1662 			/* see if the owner list exists */
1663 			(void) strcpy(obuf, "owner-");
1664 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1665 				(void) strcat(obuf, "owner");
1666 			else
1667 				(void) strcat(obuf, qq->q_user);
1668 			if (!bitnset(M_USR_UPPER, qq->q_mailer->m_flags))
1669 				makelower(obuf);
1670 			if (aliaslookup(obuf) == NULL)
1671 				continue;
1672 
1673 			if (tTd(13, 4))
1674 				printf("Errors to %s\n", obuf);
1675 
1676 			/* owner list exists -- add it to the error queue */
1677 			sendtolist(obuf, (ADDRESS *) NULL, &e->e_errorqueue, e);
1678 
1679 			/* and set the return path to point to it */
1680 			e->e_returnpath = newstr(obuf);
1681 
1682 			ErrorMode = EM_MAIL;
1683 			break;
1684 		}
1685 
1686 		/* if we did not find an owner, send to the sender */
1687 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1688 			sendtolist(e->e_from.q_paddr, qq, &e->e_errorqueue, e);
1689 	}
1690 
1691 	if (mode == SM_FORK)
1692 		finis();
1693 }
1694 /*
1695 **  HOSTSIGNATURE -- return the "signature" for a host.
1696 **
1697 **	The signature describes how we are going to send this -- it
1698 **	can be just the hostname (for non-Internet hosts) or can be
1699 **	an ordered list of MX hosts.
1700 **
1701 **	Parameters:
1702 **		m -- the mailer describing this host.
1703 **		host -- the host name.
1704 **		e -- the current envelope.
1705 **
1706 **	Returns:
1707 **		The signature for this host.
1708 **
1709 **	Side Effects:
1710 **		Can tweak the symbol table.
1711 */
1712 
1713 char *
1714 hostsignature(m, host, e)
1715 	register MAILER *m;
1716 	char *host;
1717 	ENVELOPE *e;
1718 {
1719 	register char *p;
1720 	register STAB *s;
1721 	int i;
1722 	int len;
1723 #ifdef NAMED_BIND
1724 	int nmx;
1725 	auto int rcode;
1726 	char *mxhosts[MAXMXHOSTS + 1];
1727 	static char myhostbuf[MAXNAME];
1728 #endif
1729 
1730 	/*
1731 	**  Check to see if this uses IPC -- if not, it can't have MX records.
1732 	*/
1733 
1734 	p = m->m_mailer;
1735 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
1736 	{
1737 		/* just an ordinary mailer */
1738 		return host;
1739 	}
1740 
1741 	/*
1742 	**  If it is a numeric address, just return it.
1743 	*/
1744 
1745 	if (host[0] == '[')
1746 		return host;
1747 
1748 	/*
1749 	**  Look it up in the symbol table.
1750 	*/
1751 
1752 	s = stab(host, ST_HOSTSIG, ST_ENTER);
1753 	if (s->s_hostsig != NULL)
1754 		return s->s_hostsig;
1755 
1756 	/*
1757 	**  Not already there -- create a signature.
1758 	*/
1759 
1760 #ifdef NAMED_BIND
1761 	if (myhostbuf[0] == '\0')
1762 		expand("\001j", myhostbuf, &myhostbuf[sizeof myhostbuf - 1], e);
1763 
1764 	nmx = getmxrr(host, mxhosts, myhostbuf, &rcode);
1765 	if (nmx <= 0)
1766 	{
1767 		register MCI *mci;
1768 		extern int errno;
1769 		extern MCI *mci_get();
1770 
1771 		/* update the connection info for this host */
1772 		mci = mci_get(host, m);
1773 		mci->mci_exitstat = rcode;
1774 		mci->mci_errno = errno;
1775 
1776 		/* and return the original host name as the signature */
1777 		s->s_hostsig = host;
1778 		return host;
1779 	}
1780 
1781 	len = 0;
1782 	for (i = 0; i < nmx; i++)
1783 	{
1784 		len += strlen(mxhosts[i]) + 1;
1785 	}
1786 	s->s_hostsig = p = xalloc(len);
1787 	for (i = 0; i < nmx; i++)
1788 	{
1789 		if (i != 0)
1790 			*p++ = ':';
1791 		strcpy(p, mxhosts[i]);
1792 		p += strlen(p);
1793 	}
1794 	makelower(s->s_hostsig);
1795 #else
1796 	/* not using BIND -- the signature is just the host name */
1797 	s->s_hostsig = host;
1798 #endif
1799 	if (tTd(17, 1))
1800 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
1801 	return s->s_hostsig;
1802 }
1803