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