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