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