1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)deliver.c	8.62 (Berkeley) 01/12/94";
11 #endif /* not lint */
12 
13 #include "sendmail.h"
14 #include <netdb.h>
15 #include <errno.h>
16 #ifdef NAMED_BIND
17 #include <arpa/nameser.h>
18 #include <resolv.h>
19 
20 extern int	h_errno;
21 #endif
22 
23 extern char	SmtpError[];
24 
25 /*
26 **  SENDALL -- actually send all the messages.
27 **
28 **	Parameters:
29 **		e -- the envelope to send.
30 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
31 **			the current e->e_sendmode.
32 **
33 **	Returns:
34 **		none.
35 **
36 **	Side Effects:
37 **		Scans the send lists and sends everything it finds.
38 **		Delivers any appropriate error messages.
39 **		If we are running in a non-interactive mode, takes the
40 **			appropriate action.
41 */
42 
43 sendall(e, mode)
44 	ENVELOPE *e;
45 	char mode;
46 {
47 	register ADDRESS *q;
48 	char *owner;
49 	int otherowners;
50 	register ENVELOPE *ee;
51 	ENVELOPE *splitenv = NULL;
52 	bool announcequeueup;
53 
54 	/*
55 	**  If we have had global, fatal errors, don't bother sending
56 	**  the message at all if we are in SMTP mode.  Local errors
57 	**  (e.g., a single address failing) will still cause the other
58 	**  addresses to be sent.
59 	*/
60 
61 	if (bitset(EF_FATALERRS, e->e_flags) &&
62 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
63 	{
64 		e->e_flags |= EF_CLRQUEUE;
65 		return;
66 	}
67 
68 	/* determine actual delivery mode */
69 	CurrentLA = getla();
70 	if (mode == SM_DEFAULT)
71 	{
72 		mode = e->e_sendmode;
73 		if (mode != SM_VERIFY &&
74 		    shouldqueue(e->e_msgpriority, e->e_ctime))
75 			mode = SM_QUEUE;
76 		announcequeueup = mode == SM_QUEUE;
77 	}
78 	else
79 		announcequeueup = FALSE;
80 
81 	if (tTd(13, 1))
82 	{
83 		printf("\n===== SENDALL: mode %c, id %s, e_from ",
84 			mode, e->e_id);
85 		printaddr(&e->e_from, FALSE);
86 		printf("sendqueue:\n");
87 		printaddr(e->e_sendqueue, TRUE);
88 	}
89 
90 	/*
91 	**  Do any preprocessing necessary for the mode we are running.
92 	**	Check to make sure the hop count is reasonable.
93 	**	Delete sends to the sender in mailing lists.
94 	*/
95 
96 	CurEnv = e;
97 
98 	if (e->e_hopcount > MaxHopCount)
99 	{
100 		errno = 0;
101 		syserr("554 too many hops %d (%d max): from %s via %s, to %s",
102 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
103 			RealHostName, e->e_sendqueue->q_paddr);
104 		return;
105 	}
106 
107 	/*
108 	**  Do sender deletion.
109 	**
110 	**	If the sender has the QQUEUEUP flag set, skip this.
111 	**	This can happen if the name server is hosed when you
112 	**	are trying to send mail.  The result is that the sender
113 	**	is instantiated in the queue as a recipient.
114 	*/
115 
116 	if (!bitset(EF_METOO, e->e_flags) &&
117 	    !bitset(QQUEUEUP, e->e_from.q_flags))
118 	{
119 		if (tTd(13, 5))
120 		{
121 			printf("sendall: QDONTSEND ");
122 			printaddr(&e->e_from, FALSE);
123 		}
124 		e->e_from.q_flags |= QDONTSEND;
125 		(void) recipient(&e->e_from, &e->e_sendqueue, e);
126 	}
127 
128 	/*
129 	**  Handle alias owners.
130 	**
131 	**	We scan up the q_alias chain looking for owners.
132 	**	We discard owners that are the same as the return path.
133 	*/
134 
135 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
136 	{
137 		register struct address *a;
138 
139 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
140 			continue;
141 		if (a != NULL)
142 			q->q_owner = a->q_owner;
143 
144 		if (q->q_owner != NULL &&
145 		    !bitset(QDONTSEND, q->q_flags) &&
146 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
147 			q->q_owner = NULL;
148 	}
149 
150 	owner = "";
151 	otherowners = 1;
152 	while (owner != NULL && otherowners > 0)
153 	{
154 		owner = NULL;
155 		otherowners = 0;
156 
157 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
158 		{
159 			if (bitset(QDONTSEND, q->q_flags))
160 				continue;
161 
162 			if (q->q_owner != NULL)
163 			{
164 				if (owner == NULL)
165 					owner = q->q_owner;
166 				else if (owner != q->q_owner)
167 				{
168 					if (strcmp(owner, q->q_owner) == 0)
169 					{
170 						/* make future comparisons cheap */
171 						q->q_owner = owner;
172 					}
173 					else
174 					{
175 						otherowners++;
176 					}
177 					owner = q->q_owner;
178 				}
179 			}
180 			else
181 			{
182 				otherowners++;
183 			}
184 		}
185 
186 		if (owner != NULL && otherowners > 0)
187 		{
188 			extern HDR *copyheader();
189 			extern ADDRESS *copyqueue();
190 
191 			/*
192 			**  Split this envelope into two.
193 			*/
194 
195 			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
196 			*ee = *e;
197 			ee->e_id = NULL;
198 			(void) queuename(ee, '\0');
199 
200 			if (tTd(13, 1))
201 				printf("sendall: split %s into %s\n",
202 					e->e_id, ee->e_id);
203 
204 			ee->e_header = copyheader(e->e_header);
205 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
206 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
207 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS);
208 			setsender(owner, ee, NULL, TRUE);
209 			if (tTd(13, 5))
210 			{
211 				printf("sendall(split): QDONTSEND ");
212 				printaddr(&ee->e_from, FALSE);
213 			}
214 			ee->e_from.q_flags |= QDONTSEND;
215 			ee->e_dfp = NULL;
216 			ee->e_xfp = NULL;
217 			ee->e_df = NULL;
218 			ee->e_errormode = EM_MAIL;
219 			ee->e_sibling = splitenv;
220 			splitenv = ee;
221 
222 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
223 				if (q->q_owner == owner)
224 					q->q_flags |= QDONTSEND;
225 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
226 				if (q->q_owner != owner)
227 					q->q_flags |= QDONTSEND;
228 
229 			if (e->e_df != NULL && mode != SM_VERIFY)
230 			{
231 				ee->e_dfp = NULL;
232 				ee->e_df = queuename(ee, 'd');
233 				ee->e_df = newstr(ee->e_df);
234 				if (link(e->e_df, ee->e_df) < 0)
235 				{
236 					syserr("sendall: link(%s, %s)",
237 						e->e_df, ee->e_df);
238 				}
239 			}
240 
241 			if (mode != SM_VERIFY)
242 				openxscript(ee);
243 #ifdef LOG
244 			if (LogLevel > 4)
245 				syslog(LOG_INFO, "%s: clone %s",
246 					ee->e_id, e->e_id);
247 #endif
248 		}
249 	}
250 
251 	if (owner != NULL)
252 	{
253 		setsender(owner, e, NULL, TRUE);
254 		if (tTd(13, 5))
255 		{
256 			printf("sendall(owner): QDONTSEND ");
257 			printaddr(&e->e_from, FALSE);
258 		}
259 		e->e_from.q_flags |= QDONTSEND;
260 		e->e_errormode = EM_MAIL;
261 	}
262 
263 # ifdef QUEUE
264 	if ((mode == SM_QUEUE || mode == SM_FORK ||
265 	     (mode != SM_VERIFY && SuperSafe)) &&
266 	    !bitset(EF_INQUEUE, e->e_flags))
267 	{
268 		/* be sure everything is instantiated in the queue */
269 		queueup(e, TRUE, announcequeueup);
270 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
271 			queueup(ee, TRUE, announcequeueup);
272 	}
273 #endif /* QUEUE */
274 
275 	if (splitenv != NULL)
276 	{
277 		if (tTd(13, 1))
278 		{
279 			printf("\nsendall: Split queue; remaining queue:\n");
280 			printaddr(e->e_sendqueue, TRUE);
281 		}
282 
283 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
284 		{
285 			CurEnv = ee;
286 			sendenvelope(ee, mode);
287 		}
288 
289 		CurEnv = e;
290 	}
291 	sendenvelope(e, mode);
292 
293 	for (; splitenv != NULL; splitenv = splitenv->e_sibling)
294 		dropenvelope(splitenv);
295 }
296 
297 sendenvelope(e, mode)
298 	register ENVELOPE *e;
299 	char mode;
300 {
301 	bool oldverbose;
302 	int pid;
303 	register ADDRESS *q;
304 	char *qf;
305 	char *id;
306 
307 	/*
308 	**  If we have had global, fatal errors, don't bother sending
309 	**  the message at all if we are in SMTP mode.  Local errors
310 	**  (e.g., a single address failing) will still cause the other
311 	**  addresses to be sent.
312 	*/
313 
314 	if (bitset(EF_FATALERRS, e->e_flags) &&
315 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
316 	{
317 		e->e_flags |= EF_CLRQUEUE;
318 		return;
319 	}
320 
321 	oldverbose = Verbose;
322 	switch (mode)
323 	{
324 	  case SM_VERIFY:
325 		Verbose = TRUE;
326 		break;
327 
328 	  case SM_QUEUE:
329   queueonly:
330 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
331 		return;
332 
333 	  case SM_FORK:
334 		if (e->e_xfp != NULL)
335 			(void) fflush(e->e_xfp);
336 
337 # ifndef HASFLOCK
338 		/*
339 		**  Since fcntl locking has the interesting semantic that
340 		**  the lock is owned by a process, not by an open file
341 		**  descriptor, we have to flush this to the queue, and
342 		**  then restart from scratch in the child.
343 		*/
344 
345 		/* save id for future use */
346 		id = e->e_id;
347 
348 		/* now drop the envelope in the parent */
349 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
350 		dropenvelope(e);
351 
352 		/* and reacquire in the child */
353 		(void) dowork(id, TRUE, FALSE, e);
354 
355 		return;
356 
357 # else /* HASFLOCK */
358 
359 		pid = fork();
360 		if (pid < 0)
361 		{
362 			goto queueonly;
363 		}
364 		else if (pid > 0)
365 		{
366 			/* be sure we leave the temp files to our child */
367 			/* can't call unlockqueue to avoid unlink of xfp */
368 			if (e->e_lockfp != NULL)
369 				(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
370 			e->e_lockfp = NULL;
371 
372 			/* close any random open files in the envelope */
373 			closexscript(e);
374 			if (e->e_dfp != NULL)
375 				(void) xfclose(e->e_dfp, "sendenvelope", e->e_df);
376 			e->e_dfp = NULL;
377 			e->e_id = e->e_df = NULL;
378 			return;
379 		}
380 
381 		/* double fork to avoid zombies */
382 		if (fork() > 0)
383 			exit(EX_OK);
384 
385 		/* be sure we are immune from the terminal */
386 		disconnect(1, e);
387 
388 		/*
389 		**  Close any cached connections.
390 		**
391 		**	We don't send the QUIT protocol because the parent
392 		**	still knows about the connection.
393 		**
394 		**	This should only happen when delivering an error
395 		**	message.
396 		*/
397 
398 		mci_flush(FALSE, NULL);
399 
400 # endif /* HASFLOCK */
401 
402 		break;
403 	}
404 
405 	/*
406 	**  Run through the list and send everything.
407 	**
408 	**	Set EF_GLOBALERRS so that error messages during delivery
409 	**	result in returned mail.
410 	*/
411 
412 	e->e_nsent = 0;
413 	e->e_flags |= EF_GLOBALERRS;
414 
415 	/* now run through the queue */
416 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
417 	{
418 #ifdef XDEBUG
419 		char wbuf[MAXNAME + 20];
420 
421 		(void) sprintf(wbuf, "sendall(%s)", q->q_paddr);
422 		checkfd012(wbuf);
423 #endif
424 		if (mode == SM_VERIFY)
425 		{
426 			e->e_to = q->q_paddr;
427 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
428 			{
429 				if (q->q_host != NULL && q->q_host[0] != '\0')
430 					message("deliverable: mailer %s, host %s, user %s",
431 						q->q_mailer->m_name,
432 						q->q_host,
433 						q->q_user);
434 				else
435 					message("deliverable: mailer %s, user %s",
436 						q->q_mailer->m_name,
437 						q->q_user);
438 			}
439 		}
440 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
441 		{
442 # ifdef QUEUE
443 			/*
444 			**  Checkpoint the send list every few addresses
445 			*/
446 
447 			if (e->e_nsent >= CheckpointInterval)
448 			{
449 				queueup(e, TRUE, FALSE);
450 				e->e_nsent = 0;
451 			}
452 # endif /* QUEUE */
453 			(void) deliver(e, q);
454 		}
455 	}
456 	Verbose = oldverbose;
457 
458 #ifdef XDEBUG
459 	checkfd012("end of sendenvelope");
460 #endif
461 
462 	if (mode == SM_FORK)
463 		finis();
464 }
465 /*
466 **  DOFORK -- do a fork, retrying a couple of times on failure.
467 **
468 **	This MUST be a macro, since after a vfork we are running
469 **	two processes on the same stack!!!
470 **
471 **	Parameters:
472 **		none.
473 **
474 **	Returns:
475 **		From a macro???  You've got to be kidding!
476 **
477 **	Side Effects:
478 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
479 **			pid of child in parent, zero in child.
480 **			-1 on unrecoverable error.
481 **
482 **	Notes:
483 **		I'm awfully sorry this looks so awful.  That's
484 **		vfork for you.....
485 */
486 
487 # define NFORKTRIES	5
488 
489 # ifndef FORK
490 # define FORK	fork
491 # endif
492 
493 # define DOFORK(fORKfN) \
494 {\
495 	register int i;\
496 \
497 	for (i = NFORKTRIES; --i >= 0; )\
498 	{\
499 		pid = fORKfN();\
500 		if (pid >= 0)\
501 			break;\
502 		if (i > 0)\
503 			sleep((unsigned) NFORKTRIES - i);\
504 	}\
505 }
506 /*
507 **  DOFORK -- simple fork interface to DOFORK.
508 **
509 **	Parameters:
510 **		none.
511 **
512 **	Returns:
513 **		pid of child in parent.
514 **		zero in child.
515 **		-1 on error.
516 **
517 **	Side Effects:
518 **		returns twice, once in parent and once in child.
519 */
520 
521 dofork()
522 {
523 	register int pid;
524 
525 	DOFORK(fork);
526 	return (pid);
527 }
528 /*
529 **  DELIVER -- Deliver a message to a list of addresses.
530 **
531 **	This routine delivers to everyone on the same host as the
532 **	user on the head of the list.  It is clever about mailers
533 **	that don't handle multiple users.  It is NOT guaranteed
534 **	that it will deliver to all these addresses however -- so
535 **	deliver should be called once for each address on the
536 **	list.
537 **
538 **	Parameters:
539 **		e -- the envelope to deliver.
540 **		firstto -- head of the address list to deliver to.
541 **
542 **	Returns:
543 **		zero -- successfully delivered.
544 **		else -- some failure, see ExitStat for more info.
545 **
546 **	Side Effects:
547 **		The standard input is passed off to someone.
548 */
549 
550 deliver(e, firstto)
551 	register ENVELOPE *e;
552 	ADDRESS *firstto;
553 {
554 	char *host;			/* host being sent to */
555 	char *user;			/* user being sent to */
556 	char **pvp;
557 	register char **mvp;
558 	register char *p;
559 	register MAILER *m;		/* mailer for this recipient */
560 	ADDRESS *ctladdr;
561 	register MCI *mci;
562 	register ADDRESS *to = firstto;
563 	bool clever = FALSE;		/* running user smtp to this mailer */
564 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
565 	int rcode;			/* response code */
566 	char *firstsig;			/* signature of firstto */
567 	int pid;
568 	char *curhost;
569 	int mpvect[2];
570 	int rpvect[2];
571 	char *pv[MAXPV+1];
572 	char tobuf[TOBUFSIZE];		/* text line of to people */
573 	char buf[MAXNAME];
574 	char rpathbuf[MAXNAME];		/* translated return path */
575 	extern int checkcompat();
576 
577 	errno = 0;
578 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
579 		return (0);
580 
581 #ifdef NAMED_BIND
582 	/* unless interactive, try twice, over a minute */
583 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
584 	{
585 		_res.retrans = 30;
586 		_res.retry = 2;
587 	}
588 #endif
589 
590 	m = to->q_mailer;
591 	host = to->q_host;
592 	CurEnv = e;			/* just in case */
593 	e->e_statmsg = NULL;
594 	SmtpError[0] = '\0';
595 
596 	if (tTd(10, 1))
597 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
598 			m->m_mno, host, to->q_user);
599 	if (tTd(10, 100))
600 		printopenfds(FALSE);
601 
602 	/*
603 	**  If this mailer is expensive, and if we don't want to make
604 	**  connections now, just mark these addresses and return.
605 	**	This is useful if we want to batch connections to
606 	**	reduce load.  This will cause the messages to be
607 	**	queued up, and a daemon will come along to send the
608 	**	messages later.
609 	**		This should be on a per-mailer basis.
610 	*/
611 
612 	if (NoConnect && bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
613 	{
614 		for (; to != NULL; to = to->q_next)
615 		{
616 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
617 			    to->q_mailer != m)
618 				continue;
619 			to->q_flags |= QQUEUEUP;
620 			e->e_to = to->q_paddr;
621 			message("queued");
622 			if (LogLevel > 8)
623 				logdelivery(m, NULL, "queued", NULL, e);
624 		}
625 		e->e_to = NULL;
626 		return (0);
627 	}
628 
629 	/*
630 	**  Do initial argv setup.
631 	**	Insert the mailer name.  Notice that $x expansion is
632 	**	NOT done on the mailer name.  Then, if the mailer has
633 	**	a picky -f flag, we insert it as appropriate.  This
634 	**	code does not check for 'pv' overflow; this places a
635 	**	manifest lower limit of 4 for MAXPV.
636 	**		The from address rewrite is expected to make
637 	**		the address relative to the other end.
638 	*/
639 
640 	/* rewrite from address, using rewriting rules */
641 	rcode = EX_OK;
642 	(void) strcpy(rpathbuf, remotename(e->e_from.q_paddr, m,
643 					   RF_SENDERADDR|RF_CANONICAL,
644 					   &rcode, e));
645 	define('g', rpathbuf, e);		/* translated return path */
646 	define('h', host, e);			/* to host */
647 	Errors = 0;
648 	pvp = pv;
649 	*pvp++ = m->m_argv[0];
650 
651 	/* insert -f or -r flag as appropriate */
652 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
653 	{
654 		if (bitnset(M_FOPT, m->m_flags))
655 			*pvp++ = "-f";
656 		else
657 			*pvp++ = "-r";
658 		*pvp++ = newstr(rpathbuf);
659 	}
660 
661 	/*
662 	**  Append the other fixed parts of the argv.  These run
663 	**  up to the first entry containing "$u".  There can only
664 	**  be one of these, and there are only a few more slots
665 	**  in the pv after it.
666 	*/
667 
668 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
669 	{
670 		/* can't use strchr here because of sign extension problems */
671 		while (*p != '\0')
672 		{
673 			if ((*p++ & 0377) == MACROEXPAND)
674 			{
675 				if (*p == 'u')
676 					break;
677 			}
678 		}
679 
680 		if (*p != '\0')
681 			break;
682 
683 		/* this entry is safe -- go ahead and process it */
684 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
685 		*pvp++ = newstr(buf);
686 		if (pvp >= &pv[MAXPV - 3])
687 		{
688 			syserr("554 Too many parameters to %s before $u", pv[0]);
689 			return (-1);
690 		}
691 	}
692 
693 	/*
694 	**  If we have no substitution for the user name in the argument
695 	**  list, we know that we must supply the names otherwise -- and
696 	**  SMTP is the answer!!
697 	*/
698 
699 	if (*mvp == NULL)
700 	{
701 		/* running SMTP */
702 # ifdef SMTP
703 		clever = TRUE;
704 		*pvp = NULL;
705 # else /* SMTP */
706 		/* oops!  we don't implement SMTP */
707 		syserr("554 SMTP style mailer not implemented");
708 		return (EX_SOFTWARE);
709 # endif /* SMTP */
710 	}
711 
712 	/*
713 	**  At this point *mvp points to the argument with $u.  We
714 	**  run through our address list and append all the addresses
715 	**  we can.  If we run out of space, do not fret!  We can
716 	**  always send another copy later.
717 	*/
718 
719 	tobuf[0] = '\0';
720 	e->e_to = tobuf;
721 	ctladdr = NULL;
722 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
723 	for (; to != NULL; to = to->q_next)
724 	{
725 		/* avoid sending multiple recipients to dumb mailers */
726 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
727 			break;
728 
729 		/* if already sent or not for this host, don't send */
730 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
731 		    to->q_mailer != firstto->q_mailer ||
732 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
733 			continue;
734 
735 		/* avoid overflowing tobuf */
736 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
737 			break;
738 
739 		if (tTd(10, 1))
740 		{
741 			printf("\nsend to ");
742 			printaddr(to, FALSE);
743 		}
744 
745 		/* compute effective uid/gid when sending */
746 		/* XXX perhaps this should be to->q_mailer != LocalMailer ?? */
747 		/* XXX perhaps it should be a mailer flag? */
748 		if (to->q_mailer == ProgMailer || to->q_mailer == FileMailer)
749 			ctladdr = getctladdr(to);
750 
751 		user = to->q_user;
752 		e->e_to = to->q_paddr;
753 		if (tTd(10, 5))
754 		{
755 			printf("deliver: QDONTSEND ");
756 			printaddr(to, FALSE);
757 		}
758 		to->q_flags |= QDONTSEND;
759 
760 		/*
761 		**  Check to see that these people are allowed to
762 		**  talk to each other.
763 		*/
764 
765 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
766 		{
767 			NoReturn = TRUE;
768 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
769 			giveresponse(EX_UNAVAILABLE, m, NULL, ctladdr, e);
770 			continue;
771 		}
772 		rcode = checkcompat(to, e);
773 		if (rcode != EX_OK)
774 		{
775 			markfailure(e, to, rcode);
776 			giveresponse(rcode, m, NULL, ctladdr, e);
777 			continue;
778 		}
779 
780 		/*
781 		**  Strip quote bits from names if the mailer is dumb
782 		**	about them.
783 		*/
784 
785 		if (bitnset(M_STRIPQ, m->m_flags))
786 		{
787 			stripquotes(user);
788 			stripquotes(host);
789 		}
790 
791 		/* hack attack -- delivermail compatibility */
792 		if (m == ProgMailer && *user == '|')
793 			user++;
794 
795 		/*
796 		**  If an error message has already been given, don't
797 		**	bother to send to this address.
798 		**
799 		**	>>>>>>>>>> This clause assumes that the local mailer
800 		**	>> NOTE >> cannot do any further aliasing; that
801 		**	>>>>>>>>>> function is subsumed by sendmail.
802 		*/
803 
804 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
805 			continue;
806 
807 		/* save statistics.... */
808 		markstats(e, to);
809 
810 		/*
811 		**  See if this user name is "special".
812 		**	If the user name has a slash in it, assume that this
813 		**	is a file -- send it off without further ado.  Note
814 		**	that this type of addresses is not processed along
815 		**	with the others, so we fudge on the To person.
816 		*/
817 
818 		if (m == FileMailer)
819 		{
820 			rcode = mailfile(user, ctladdr, e);
821 			giveresponse(rcode, m, NULL, ctladdr, e);
822 			if (rcode == EX_OK)
823 				to->q_flags |= QSENT;
824 			continue;
825 		}
826 
827 		/*
828 		**  Address is verified -- add this user to mailer
829 		**  argv, and add it to the print list of recipients.
830 		*/
831 
832 		/* link together the chain of recipients */
833 		to->q_tchain = tochain;
834 		tochain = to;
835 
836 		/* create list of users for error messages */
837 		(void) strcat(tobuf, ",");
838 		(void) strcat(tobuf, to->q_paddr);
839 		define('u', user, e);		/* to user */
840 		p = to->q_home;
841 		if (p == NULL && ctladdr != NULL)
842 			p = ctladdr->q_home;
843 		define('z', p, e);	/* user's home */
844 
845 		/*
846 		**  Expand out this user into argument list.
847 		*/
848 
849 		if (!clever)
850 		{
851 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
852 			*pvp++ = newstr(buf);
853 			if (pvp >= &pv[MAXPV - 2])
854 			{
855 				/* allow some space for trailing parms */
856 				break;
857 			}
858 		}
859 	}
860 
861 	/* see if any addresses still exist */
862 	if (tobuf[0] == '\0')
863 	{
864 		define('g', (char *) NULL, e);
865 		return (0);
866 	}
867 
868 	/* print out messages as full list */
869 	e->e_to = tobuf + 1;
870 
871 	/*
872 	**  Fill out any parameters after the $u parameter.
873 	*/
874 
875 	while (!clever && *++mvp != NULL)
876 	{
877 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
878 		*pvp++ = newstr(buf);
879 		if (pvp >= &pv[MAXPV])
880 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
881 	}
882 	*pvp++ = NULL;
883 
884 	/*
885 	**  Call the mailer.
886 	**	The argument vector gets built, pipes
887 	**	are created as necessary, and we fork & exec as
888 	**	appropriate.
889 	**	If we are running SMTP, we just need to clean up.
890 	*/
891 
892 	/*XXX this seems a bit wierd */
893 	if (ctladdr == NULL && bitset(QGOODUID, e->e_from.q_flags))
894 		ctladdr = &e->e_from;
895 
896 #ifdef NAMED_BIND
897 	if (ConfigLevel < 2)
898 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
899 #endif
900 
901 	if (tTd(11, 1))
902 	{
903 		printf("openmailer:");
904 		printav(pv);
905 	}
906 	errno = 0;
907 
908 	CurHostName = m->m_mailer;
909 
910 	/*
911 	**  Deal with the special case of mail handled through an IPC
912 	**  connection.
913 	**	In this case we don't actually fork.  We must be
914 	**	running SMTP for this to work.  We will return a
915 	**	zero pid to indicate that we are running IPC.
916 	**  We also handle a debug version that just talks to stdin/out.
917 	*/
918 
919 	curhost = NULL;
920 	SmtpPhase = NULL;
921 	mci = NULL;
922 
923 #ifdef XDEBUG
924 	{
925 		char wbuf[MAXLINE];
926 
927 		/* make absolutely certain 0, 1, and 2 are in use */
928 		sprintf(wbuf, "%s... openmailer(%s)", e->e_to, m->m_name);
929 		checkfd012(wbuf);
930 	}
931 #endif
932 
933 	/* check for Local Person Communication -- not for mortals!!! */
934 	if (strcmp(m->m_mailer, "[LPC]") == 0)
935 	{
936 		mci = (MCI *) xalloc(sizeof *mci);
937 		bzero((char *) mci, sizeof *mci);
938 		mci->mci_in = stdin;
939 		mci->mci_out = stdout;
940 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
941 		mci->mci_mailer = m;
942 	}
943 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
944 		 strcmp(m->m_mailer, "[TCP]") == 0)
945 	{
946 #ifdef DAEMON
947 		register int i;
948 		register u_short port;
949 
950 		if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
951 		{
952 			syserr("null host name for %s mailer", m->m_mailer);
953 			rcode = EX_CONFIG;
954 			goto give_up;
955 		}
956 
957 		CurHostName = pv[1];
958 		curhost = hostsignature(m, pv[1], e);
959 
960 		if (curhost == NULL || curhost[0] == '\0')
961 		{
962 			syserr("null host signature for %s", pv[1]);
963 			rcode = EX_OSERR;
964 			goto give_up;
965 		}
966 
967 		if (!clever)
968 		{
969 			syserr("554 non-clever IPC");
970 			rcode = EX_CONFIG;
971 			goto give_up;
972 		}
973 		if (pv[2] != NULL)
974 			port = atoi(pv[2]);
975 		else
976 			port = 0;
977 tryhost:
978 		while (*curhost != '\0')
979 		{
980 			register char *p;
981 			static char hostbuf[MAXNAME];
982 
983 			/* pull the next host from the signature */
984 			p = strchr(curhost, ':');
985 			if (p == NULL)
986 				p = &curhost[strlen(curhost)];
987 			if (p == curhost)
988 			{
989 				syserr("deliver: null host name in signature");
990 				curhost++;
991 				continue;
992 			}
993 			strncpy(hostbuf, curhost, p - curhost);
994 			hostbuf[p - curhost] = '\0';
995 			if (*p != '\0')
996 				p++;
997 			curhost = p;
998 
999 			/* see if we already know that this host is fried */
1000 			CurHostName = hostbuf;
1001 			mci = mci_get(hostbuf, m);
1002 			if (mci->mci_state != MCIS_CLOSED)
1003 			{
1004 				if (tTd(11, 1))
1005 				{
1006 					printf("openmailer: ");
1007 					mci_dump(mci, FALSE);
1008 				}
1009 				CurHostName = mci->mci_host;
1010 				break;
1011 			}
1012 			mci->mci_mailer = m;
1013 			if (mci->mci_exitstat != EX_OK)
1014 				continue;
1015 
1016 			/* try the connection */
1017 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
1018 			message("Connecting to %s (%s)...",
1019 				hostbuf, m->m_name);
1020 			i = makeconnection(hostbuf, port, mci,
1021 				bitnset(M_SECURE_PORT, m->m_flags));
1022 			mci->mci_exitstat = i;
1023 			mci->mci_errno = errno;
1024 #ifdef NAMED_BIND
1025 			mci->mci_herrno = h_errno;
1026 #endif
1027 			if (i == EX_OK)
1028 			{
1029 				mci->mci_state = MCIS_OPENING;
1030 				mci_cache(mci);
1031 				if (TrafficLogFile != NULL)
1032 					fprintf(TrafficLogFile, "%05d == CONNECT %s\n",
1033 						getpid(), hostbuf);
1034 				break;
1035 			}
1036 			else if (tTd(11, 1))
1037 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1038 					i, errno);
1039 
1040 			/* enter status of this host */
1041 			setstat(i);
1042 
1043 			/* should print some message here for -v mode */
1044 		}
1045 		if (mci == NULL)
1046 		{
1047 			syserr("deliver: no host name");
1048 			rcode = EX_OSERR;
1049 			goto give_up;
1050 		}
1051 		mci->mci_pid = 0;
1052 #else /* no DAEMON */
1053 		syserr("554 openmailer: no IPC");
1054 		if (tTd(11, 1))
1055 			printf("openmailer: NULL\n");
1056 		rcode = EX_UNAVAILABLE;
1057 		goto give_up;
1058 #endif /* DAEMON */
1059 	}
1060 	else
1061 	{
1062 		if (TrafficLogFile != NULL)
1063 		{
1064 			char **av;
1065 
1066 			fprintf(TrafficLogFile, "%05d === EXEC", getpid());
1067 			for (av = pv; *av != NULL; av++)
1068 				fprintf(TrafficLogFile, " %s", *av);
1069 			fprintf(TrafficLogFile, "\n");
1070 		}
1071 
1072 		/* create a pipe to shove the mail through */
1073 		if (pipe(mpvect) < 0)
1074 		{
1075 			syserr("%s... openmailer(%s): pipe (to mailer)",
1076 				e->e_to, m->m_name);
1077 			if (tTd(11, 1))
1078 				printf("openmailer: NULL\n");
1079 			rcode = EX_OSERR;
1080 			goto give_up;
1081 		}
1082 
1083 		/* if this mailer speaks smtp, create a return pipe */
1084 		if (clever && pipe(rpvect) < 0)
1085 		{
1086 			syserr("%s... openmailer(%s): pipe (from mailer)",
1087 				e->e_to, m->m_name);
1088 			(void) close(mpvect[0]);
1089 			(void) close(mpvect[1]);
1090 			if (tTd(11, 1))
1091 				printf("openmailer: NULL\n");
1092 			rcode = EX_OSERR;
1093 			goto give_up;
1094 		}
1095 
1096 		/*
1097 		**  Actually fork the mailer process.
1098 		**	DOFORK is clever about retrying.
1099 		**
1100 		**	Dispose of SIGCHLD signal catchers that may be laying
1101 		**	around so that endmail will get it.
1102 		*/
1103 
1104 		if (e->e_xfp != NULL)
1105 			(void) fflush(e->e_xfp);		/* for debugging */
1106 		(void) fflush(stdout);
1107 # ifdef SIGCHLD
1108 		(void) setsignal(SIGCHLD, SIG_DFL);
1109 # endif /* SIGCHLD */
1110 		DOFORK(FORK);
1111 		/* pid is set by DOFORK */
1112 		if (pid < 0)
1113 		{
1114 			/* failure */
1115 			syserr("%s... openmailer(%s): cannot fork",
1116 				e->e_to, m->m_name);
1117 			(void) close(mpvect[0]);
1118 			(void) close(mpvect[1]);
1119 			if (clever)
1120 			{
1121 				(void) close(rpvect[0]);
1122 				(void) close(rpvect[1]);
1123 			}
1124 			if (tTd(11, 1))
1125 				printf("openmailer: NULL\n");
1126 			rcode = EX_OSERR;
1127 			goto give_up;
1128 		}
1129 		else if (pid == 0)
1130 		{
1131 			int i;
1132 			int saveerrno;
1133 			char **ep;
1134 			char *env[MAXUSERENVIRON];
1135 			extern char **environ;
1136 			extern int DtableSize;
1137 
1138 			/* child -- set up input & exec mailer */
1139 			(void) setsignal(SIGINT, SIG_IGN);
1140 			(void) setsignal(SIGHUP, SIG_IGN);
1141 			(void) setsignal(SIGTERM, SIG_DFL);
1142 
1143 			/* reset user and group */
1144 			if (!bitnset(M_RESTR, m->m_flags))
1145 			{
1146 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1147 				{
1148 					(void) initgroups(DefUser, DefGid);
1149 					(void) setgid(DefGid);
1150 					(void) setuid(DefUid);
1151 				}
1152 				else
1153 				{
1154 					(void) initgroups(ctladdr->q_ruser?
1155 						ctladdr->q_ruser: ctladdr->q_user,
1156 						ctladdr->q_gid);
1157 					(void) setgid(ctladdr->q_gid);
1158 					(void) setuid(ctladdr->q_uid);
1159 				}
1160 			}
1161 
1162 			if (tTd(11, 2))
1163 				printf("openmailer: running as r/euid=%d/%d\n",
1164 					getuid(), geteuid());
1165 
1166 			/* move into some "safe" directory */
1167 			if (m->m_execdir != NULL)
1168 			{
1169 				char *p, *q;
1170 				char buf[MAXLINE];
1171 
1172 				for (p = m->m_execdir; p != NULL; p = q)
1173 				{
1174 					q = strchr(p, ':');
1175 					if (q != NULL)
1176 						*q = '\0';
1177 					expand(p, buf, &buf[sizeof buf] - 1, e);
1178 					if (q != NULL)
1179 						*q++ = ':';
1180 					if (tTd(11, 20))
1181 						printf("openmailer: trydir %s\n",
1182 							buf);
1183 					if (buf[0] != '\0' && chdir(buf) >= 0)
1184 						break;
1185 				}
1186 			}
1187 
1188 			/* arrange to filter std & diag output of command */
1189 			if (clever)
1190 			{
1191 				(void) close(rpvect[0]);
1192 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1193 				{
1194 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1195 						e->e_to, m->m_name, rpvect[1]);
1196 					_exit(EX_OSERR);
1197 				}
1198 				(void) close(rpvect[1]);
1199 			}
1200 			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON || HoldErrs)
1201 			{
1202 				/* put mailer output in transcript */
1203 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1204 				{
1205 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1206 						e->e_to, m->m_name,
1207 						fileno(e->e_xfp));
1208 					_exit(EX_OSERR);
1209 				}
1210 			}
1211 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1212 			{
1213 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1214 					e->e_to, m->m_name);
1215 				_exit(EX_OSERR);
1216 			}
1217 
1218 			/* arrange to get standard input */
1219 			(void) close(mpvect[1]);
1220 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1221 			{
1222 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1223 					e->e_to, m->m_name, mpvect[0]);
1224 				_exit(EX_OSERR);
1225 			}
1226 			(void) close(mpvect[0]);
1227 
1228 			/* arrange for all the files to be closed */
1229 			for (i = 3; i < DtableSize; i++)
1230 			{
1231 				register int j;
1232 
1233 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1234 					(void) fcntl(i, F_SETFD, j | 1);
1235 			}
1236 
1237 			/* set up the mailer environment */
1238 			i = 0;
1239 			env[i++] = "AGENT=sendmail";
1240 			for (ep = environ; *ep != NULL; ep++)
1241 			{
1242 				if (strncmp(*ep, "TZ=", 3) == 0)
1243 					env[i++] = *ep;
1244 			}
1245 			env[i++] = NULL;
1246 
1247 			/* try to execute the mailer */
1248 			execve(m->m_mailer, pv, env);
1249 			saveerrno = errno;
1250 			syserr("Cannot exec %s", m->m_mailer);
1251 			if (m == LocalMailer || transienterror(saveerrno))
1252 				_exit(EX_OSERR);
1253 			_exit(EX_UNAVAILABLE);
1254 		}
1255 
1256 		/*
1257 		**  Set up return value.
1258 		*/
1259 
1260 		mci = (MCI *) xalloc(sizeof *mci);
1261 		bzero((char *) mci, sizeof *mci);
1262 		mci->mci_mailer = m;
1263 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1264 		mci->mci_pid = pid;
1265 		(void) close(mpvect[0]);
1266 		mci->mci_out = fdopen(mpvect[1], "w");
1267 		if (mci->mci_out == NULL)
1268 		{
1269 			syserr("deliver: cannot create mailer output channel, fd=%d",
1270 				mpvect[1]);
1271 			(void) close(mpvect[1]);
1272 			if (clever)
1273 			{
1274 				(void) close(rpvect[0]);
1275 				(void) close(rpvect[1]);
1276 			}
1277 			rcode = EX_OSERR;
1278 			goto give_up;
1279 		}
1280 		if (clever)
1281 		{
1282 			(void) close(rpvect[1]);
1283 			mci->mci_in = fdopen(rpvect[0], "r");
1284 			if (mci->mci_in == NULL)
1285 			{
1286 				syserr("deliver: cannot create mailer input channel, fd=%d",
1287 					mpvect[1]);
1288 				(void) close(rpvect[0]);
1289 				fclose(mci->mci_out);
1290 				mci->mci_out = NULL;
1291 				rcode = EX_OSERR;
1292 				goto give_up;
1293 			}
1294 		}
1295 		else
1296 		{
1297 			mci->mci_flags |= MCIF_TEMP;
1298 			mci->mci_in = NULL;
1299 		}
1300 	}
1301 
1302 	/*
1303 	**  If we are in SMTP opening state, send initial protocol.
1304 	*/
1305 
1306 	if (clever && mci->mci_state != MCIS_CLOSED)
1307 	{
1308 		smtpinit(m, mci, e);
1309 	}
1310 	if (tTd(11, 1))
1311 	{
1312 		printf("openmailer: ");
1313 		mci_dump(mci, FALSE);
1314 	}
1315 
1316 	if (mci->mci_state != MCIS_OPEN)
1317 	{
1318 		/* couldn't open the mailer */
1319 		rcode = mci->mci_exitstat;
1320 		errno = mci->mci_errno;
1321 #ifdef NAMED_BIND
1322 		h_errno = mci->mci_herrno;
1323 #endif
1324 		if (rcode == EX_OK)
1325 		{
1326 			/* shouldn't happen */
1327 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1328 				rcode, mci->mci_state, firstsig);
1329 			rcode = EX_SOFTWARE;
1330 		}
1331 		else if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
1332 		{
1333 			/* try next MX site */
1334 			goto tryhost;
1335 		}
1336 	}
1337 	else if (!clever)
1338 	{
1339 		/*
1340 		**  Format and send message.
1341 		*/
1342 
1343 		putfromline(mci->mci_out, m, e);
1344 		(*e->e_puthdr)(mci->mci_out, m, e);
1345 		putline("\n", mci->mci_out, m);
1346 		(*e->e_putbody)(mci->mci_out, m, e, NULL);
1347 
1348 		/* get the exit status */
1349 		rcode = endmailer(mci, e, pv);
1350 	}
1351 	else
1352 #ifdef SMTP
1353 	{
1354 		/*
1355 		**  Send the MAIL FROM: protocol
1356 		*/
1357 
1358 		rcode = smtpmailfrom(m, mci, e);
1359 		if (rcode == EX_OK)
1360 		{
1361 			register char *t = tobuf;
1362 			register int i;
1363 
1364 			/* send the recipient list */
1365 			tobuf[0] = '\0';
1366 			for (to = tochain; to != NULL; to = to->q_tchain)
1367 			{
1368 				e->e_to = to->q_paddr;
1369 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1370 				{
1371 					markfailure(e, to, i);
1372 					giveresponse(i, m, mci, ctladdr, e);
1373 				}
1374 				else
1375 				{
1376 					*t++ = ',';
1377 					for (p = to->q_paddr; *p; *t++ = *p++)
1378 						continue;
1379 					*t = '\0';
1380 				}
1381 			}
1382 
1383 			/* now send the data */
1384 			if (tobuf[0] == '\0')
1385 			{
1386 				rcode = EX_OK;
1387 				e->e_to = NULL;
1388 				if (bitset(MCIF_CACHED, mci->mci_flags))
1389 					smtprset(m, mci, e);
1390 			}
1391 			else
1392 			{
1393 				e->e_to = tobuf + 1;
1394 				rcode = smtpdata(m, mci, e);
1395 			}
1396 
1397 			/* now close the connection */
1398 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1399 				smtpquit(m, mci, e);
1400 		}
1401 		if (rcode != EX_OK && curhost != NULL && *curhost != '\0')
1402 		{
1403 			/* try next MX site */
1404 			goto tryhost;
1405 		}
1406 	}
1407 #else /* not SMTP */
1408 	{
1409 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1410 		rcode = EX_CONFIG;
1411 		goto give_up;
1412 	}
1413 #endif /* SMTP */
1414 #ifdef NAMED_BIND
1415 	if (ConfigLevel < 2)
1416 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1417 #endif
1418 
1419 	/* arrange a return receipt if requested */
1420 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1421 	    bitnset(M_LOCALMAILER, m->m_flags))
1422 	{
1423 		e->e_flags |= EF_SENDRECEIPT;
1424 		/* do we want to send back more info? */
1425 	}
1426 
1427 	/*
1428 	**  Do final status disposal.
1429 	**	We check for something in tobuf for the SMTP case.
1430 	**	If we got a temporary failure, arrange to queue the
1431 	**		addressees.
1432 	*/
1433 
1434   give_up:
1435 	if (tobuf[0] != '\0')
1436 		giveresponse(rcode, m, mci, ctladdr, e);
1437 	for (to = tochain; to != NULL; to = to->q_tchain)
1438 	{
1439 		if (rcode != EX_OK)
1440 			markfailure(e, to, rcode);
1441 		else
1442 		{
1443 			to->q_flags |= QSENT;
1444 			e->e_nsent++;
1445 			if (e->e_receiptto != NULL &&
1446 			    bitnset(M_LOCALMAILER, m->m_flags))
1447 			{
1448 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1449 					to->q_paddr);
1450 			}
1451 		}
1452 	}
1453 
1454 	/*
1455 	**  Restore state and return.
1456 	*/
1457 
1458 #ifdef XDEBUG
1459 	{
1460 		char wbuf[MAXLINE];
1461 
1462 		/* make absolutely certain 0, 1, and 2 are in use */
1463 		sprintf(wbuf, "%s... end of deliver(%s)",
1464 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1465 			m->m_name);
1466 		checkfd012(wbuf);
1467 	}
1468 #endif
1469 
1470 	errno = 0;
1471 	define('g', (char *) NULL, e);
1472 	return (rcode);
1473 }
1474 /*
1475 **  MARKFAILURE -- mark a failure on a specific address.
1476 **
1477 **	Parameters:
1478 **		e -- the envelope we are sending.
1479 **		q -- the address to mark.
1480 **		rcode -- the code signifying the particular failure.
1481 **
1482 **	Returns:
1483 **		none.
1484 **
1485 **	Side Effects:
1486 **		marks the address (and possibly the envelope) with the
1487 **			failure so that an error will be returned or
1488 **			the message will be queued, as appropriate.
1489 */
1490 
1491 markfailure(e, q, rcode)
1492 	register ENVELOPE *e;
1493 	register ADDRESS *q;
1494 	int rcode;
1495 {
1496 	char buf[MAXLINE];
1497 
1498 	switch (rcode)
1499 	{
1500 	  case EX_OK:
1501 		break;
1502 
1503 	  case EX_TEMPFAIL:
1504 	  case EX_IOERR:
1505 	  case EX_OSERR:
1506 		q->q_flags |= QQUEUEUP;
1507 		break;
1508 
1509 	  default:
1510 		q->q_flags |= QBADADDR;
1511 		break;
1512 	}
1513 }
1514 /*
1515 **  ENDMAILER -- Wait for mailer to terminate.
1516 **
1517 **	We should never get fatal errors (e.g., segmentation
1518 **	violation), so we report those specially.  For other
1519 **	errors, we choose a status message (into statmsg),
1520 **	and if it represents an error, we print it.
1521 **
1522 **	Parameters:
1523 **		pid -- pid of mailer.
1524 **		e -- the current envelope.
1525 **		pv -- the parameter vector that invoked the mailer
1526 **			(for error messages).
1527 **
1528 **	Returns:
1529 **		exit code of mailer.
1530 **
1531 **	Side Effects:
1532 **		none.
1533 */
1534 
1535 endmailer(mci, e, pv)
1536 	register MCI *mci;
1537 	register ENVELOPE *e;
1538 	char **pv;
1539 {
1540 	int st;
1541 
1542 	/* close any connections */
1543 	if (mci->mci_in != NULL)
1544 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1545 	if (mci->mci_out != NULL)
1546 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1547 	mci->mci_in = mci->mci_out = NULL;
1548 	mci->mci_state = MCIS_CLOSED;
1549 
1550 	/* in the IPC case there is nothing to wait for */
1551 	if (mci->mci_pid == 0)
1552 		return (EX_OK);
1553 
1554 	/* wait for the mailer process to die and collect status */
1555 	st = waitfor(mci->mci_pid);
1556 	if (st == -1)
1557 	{
1558 		syserr("endmailer %s: wait", pv[0]);
1559 		return (EX_SOFTWARE);
1560 	}
1561 
1562 	if (WIFEXITED(st))
1563 	{
1564 		/* normal death -- return status */
1565 		return (WEXITSTATUS(st));
1566 	}
1567 
1568 	/* it died a horrid death */
1569 	syserr("451 mailer %s died with signal %o",
1570 		mci->mci_mailer->m_name, st);
1571 
1572 	/* log the arguments */
1573 	if (pv != NULL && e->e_xfp != NULL)
1574 	{
1575 		register char **av;
1576 
1577 		fprintf(e->e_xfp, "Arguments:");
1578 		for (av = pv; *av != NULL; av++)
1579 			fprintf(e->e_xfp, " %s", *av);
1580 		fprintf(e->e_xfp, "\n");
1581 	}
1582 
1583 	ExitStat = EX_TEMPFAIL;
1584 	return (EX_TEMPFAIL);
1585 }
1586 /*
1587 **  GIVERESPONSE -- Interpret an error response from a mailer
1588 **
1589 **	Parameters:
1590 **		stat -- the status code from the mailer (high byte
1591 **			only; core dumps must have been taken care of
1592 **			already).
1593 **		m -- the mailer info for this mailer.
1594 **		mci -- the mailer connection info -- can be NULL if the
1595 **			response is given before the connection is made.
1596 **		ctladdr -- the controlling address for the recipient
1597 **			address(es).
1598 **		e -- the current envelope.
1599 **
1600 **	Returns:
1601 **		none.
1602 **
1603 **	Side Effects:
1604 **		Errors may be incremented.
1605 **		ExitStat may be set.
1606 */
1607 
1608 giveresponse(stat, m, mci, ctladdr, e)
1609 	int stat;
1610 	register MAILER *m;
1611 	register MCI *mci;
1612 	ADDRESS *ctladdr;
1613 	ENVELOPE *e;
1614 {
1615 	register const char *statmsg;
1616 	extern char *SysExMsg[];
1617 	register int i;
1618 	extern int N_SysEx;
1619 	char buf[MAXLINE];
1620 
1621 	/*
1622 	**  Compute status message from code.
1623 	*/
1624 
1625 	i = stat - EX__BASE;
1626 	if (stat == 0)
1627 	{
1628 		statmsg = "250 Sent";
1629 		if (e->e_statmsg != NULL)
1630 		{
1631 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1632 			statmsg = buf;
1633 		}
1634 	}
1635 	else if (i < 0 || i > N_SysEx)
1636 	{
1637 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1638 		stat = EX_UNAVAILABLE;
1639 		statmsg = buf;
1640 	}
1641 	else if (stat == EX_TEMPFAIL)
1642 	{
1643 		(void) strcpy(buf, SysExMsg[i] + 1);
1644 #ifdef NAMED_BIND
1645 		if (h_errno == TRY_AGAIN)
1646 			statmsg = errstring(h_errno+E_DNSBASE);
1647 		else
1648 #endif
1649 		{
1650 			if (errno != 0)
1651 				statmsg = errstring(errno);
1652 			else
1653 			{
1654 #ifdef SMTP
1655 				statmsg = SmtpError;
1656 #else /* SMTP */
1657 				statmsg = NULL;
1658 #endif /* SMTP */
1659 			}
1660 		}
1661 		if (statmsg != NULL && statmsg[0] != '\0')
1662 		{
1663 			(void) strcat(buf, ": ");
1664 			(void) strcat(buf, statmsg);
1665 		}
1666 		statmsg = buf;
1667 	}
1668 #ifdef NAMED_BIND
1669 	else if (stat == EX_NOHOST && h_errno != 0)
1670 	{
1671 		statmsg = errstring(h_errno + E_DNSBASE);
1672 		(void) sprintf(buf, "%s (%s)", SysExMsg[i], statmsg);
1673 		statmsg = buf;
1674 	}
1675 #endif
1676 	else
1677 	{
1678 		statmsg = SysExMsg[i];
1679 		if (*statmsg++ == ':')
1680 		{
1681 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1682 			statmsg = buf;
1683 		}
1684 	}
1685 
1686 	/*
1687 	**  Print the message as appropriate
1688 	*/
1689 
1690 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1691 	{
1692 		extern char MsgBuf[];
1693 
1694 		message(&statmsg[4], errstring(errno));
1695 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1696 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1697 	}
1698 	else
1699 	{
1700 		Errors++;
1701 		usrerr(statmsg, errstring(errno));
1702 	}
1703 
1704 	/*
1705 	**  Final cleanup.
1706 	**	Log a record of the transaction.  Compute the new
1707 	**	ExitStat -- if we already had an error, stick with
1708 	**	that.
1709 	*/
1710 
1711 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1712 		logdelivery(m, mci, &statmsg[4], ctladdr, e);
1713 
1714 	if (stat != EX_TEMPFAIL)
1715 		setstat(stat);
1716 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1717 	{
1718 		if (e->e_message != NULL)
1719 			free(e->e_message);
1720 		e->e_message = newstr(&statmsg[4]);
1721 	}
1722 	errno = 0;
1723 #ifdef NAMED_BIND
1724 	h_errno = 0;
1725 #endif
1726 }
1727 /*
1728 **  LOGDELIVERY -- log the delivery in the system log
1729 **
1730 **	Care is taken to avoid logging lines that are too long, because
1731 **	some versions of syslog have an unfortunate proclivity for core
1732 **	dumping.  This is a hack, to be sure, that is at best empirical.
1733 **
1734 **	Parameters:
1735 **		m -- the mailer info.  Can be NULL for initial queue.
1736 **		mci -- the mailer connection info -- can be NULL if the
1737 **			log is occuring when no connection is active.
1738 **		stat -- the message to print for the status.
1739 **		ctladdr -- the controlling address for the to list.
1740 **		e -- the current envelope.
1741 **
1742 **	Returns:
1743 **		none
1744 **
1745 **	Side Effects:
1746 **		none
1747 */
1748 
1749 logdelivery(m, mci, stat, ctladdr, e)
1750 	MAILER *m;
1751 	register MCI *mci;
1752 	char *stat;
1753 	ADDRESS *ctladdr;
1754 	register ENVELOPE *e;
1755 {
1756 # ifdef LOG
1757 	register char *bp;
1758 	register char *p;
1759 	int l;
1760 	char buf[512];
1761 
1762 #  if (SYSLOG_BUFSIZE) >= 256
1763 	bp = buf;
1764 	if (ctladdr != NULL)
1765 	{
1766 		strcpy(bp, ", ctladdr=");
1767 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
1768 		bp += strlen(bp);
1769 		if (bitset(QGOODUID, ctladdr->q_flags))
1770 		{
1771 			(void) sprintf(bp, " (%d/%d)",
1772 					ctladdr->q_uid, ctladdr->q_gid);
1773 			bp += strlen(bp);
1774 		}
1775 	}
1776 
1777 	(void) sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1778 	bp += strlen(bp);
1779 
1780 	if (m != NULL)
1781 	{
1782 		(void) strcpy(bp, ", mailer=");
1783 		(void) strcat(bp, m->m_name);
1784 		bp += strlen(bp);
1785 	}
1786 
1787 	if (mci != NULL && mci->mci_host != NULL)
1788 	{
1789 # ifdef DAEMON
1790 		extern SOCKADDR CurHostAddr;
1791 # endif
1792 
1793 		(void) strcpy(bp, ", relay=");
1794 		(void) strcat(bp, mci->mci_host);
1795 
1796 # ifdef DAEMON
1797 		(void) strcat(bp, " (");
1798 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1799 		(void) strcat(bp, ")");
1800 # endif
1801 	}
1802 	else
1803 	{
1804 		char *p = macvalue('h', e);
1805 
1806 		if (p != NULL && p[0] != '\0')
1807 		{
1808 			(void) strcpy(bp, ", relay=");
1809 			(void) strcat(bp, p);
1810 		}
1811 	}
1812 	bp += strlen(bp);
1813 
1814 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
1815 #if (STATLEN) < 63
1816 # undef STATLEN
1817 # define STATLEN	63
1818 #endif
1819 #if (STATLEN) > 203
1820 # undef STATLEN
1821 # define STATLEN	203
1822 #endif
1823 
1824 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
1825 	{
1826 		/* desperation move -- truncate data */
1827 		bp = buf + sizeof buf - ((STATLEN) + 17);
1828 		strcpy(bp, "...");
1829 		bp += 3;
1830 	}
1831 
1832 	(void) strcpy(bp, ", stat=");
1833 	bp += strlen(bp);
1834 
1835 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
1836 
1837 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
1838 	p = e->e_to;
1839 	while (strlen(p) >= l)
1840 	{
1841 		register char *q = strchr(p + l, ',');
1842 
1843 		if (q == NULL)
1844 			break;
1845 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
1846 			e->e_id, ++q - p, p, buf);
1847 		p = q;
1848 	}
1849 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
1850 
1851 #  else		/* we have a very short log buffer size */
1852 
1853 	l = SYSLOG_BUFSIZE - 80;
1854 	p = e->e_to;
1855 	while (strlen(p) >= l)
1856 	{
1857 		register char *q = strchr(p + l, ',');
1858 
1859 		if (q == NULL)
1860 			break;
1861 		syslog(LOG_INFO, "%s: to=%.*s [more]",
1862 			e->e_id, ++q - p, p);
1863 		p = q;
1864 	}
1865 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
1866 
1867 	if (ctladdr != NULL)
1868 	{
1869 		bp = buf;
1870 		strcpy(buf, "ctladdr=");
1871 		bp += strlen(buf);
1872 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
1873 		bp += strlen(buf);
1874 		if (bitset(QGOODUID, ctladdr->q_flags))
1875 		{
1876 			(void) sprintf(bp, " (%d/%d)",
1877 					ctladdr->q_uid, ctladdr->q_gid);
1878 			bp += strlen(bp);
1879 		}
1880 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1881 	}
1882 	bp = buf;
1883 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1884 	bp += strlen(bp);
1885 
1886 	if (m != NULL)
1887 	{
1888 		sprintf(bp, ", mailer=%s", m->m_name);
1889 		bp += strlen(bp);
1890 	}
1891 
1892 	if (mci != NULL && mci->mci_host != NULL)
1893 	{
1894 # ifdef DAEMON
1895 		extern SOCKADDR CurHostAddr;
1896 # endif
1897 
1898 		sprintf(bp, ", relay=%s", mci->mci_host);
1899 
1900 # ifdef DAEMON
1901 		(void) strcat(bp, " (");
1902 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1903 		(void) strcat(bp, ")");
1904 # endif
1905 	}
1906 	else
1907 	{
1908 		char *p = macvalue('h', e);
1909 
1910 		if (p != NULL && p[0] != '\0')
1911 			sprintf(bp, ", relay=%s", p);
1912 	}
1913 	syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1914 
1915 	syslog(LOG_INFO, "%s: stat=%s", e->e_id, shortenstring(stat, 63));
1916 #  endif /* short log buffer */
1917 # endif /* LOG */
1918 }
1919 /*
1920 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1921 **
1922 **	This can be made an arbitrary message separator by changing $l
1923 **
1924 **	One of the ugliest hacks seen by human eyes is contained herein:
1925 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1926 **	does a well-meaning programmer such as myself have to deal with
1927 **	this kind of antique garbage????
1928 **
1929 **	Parameters:
1930 **		fp -- the file to output to.
1931 **		m -- the mailer describing this entry.
1932 **
1933 **	Returns:
1934 **		none
1935 **
1936 **	Side Effects:
1937 **		outputs some text to fp.
1938 */
1939 
1940 putfromline(fp, m, e)
1941 	register FILE *fp;
1942 	register MAILER *m;
1943 	ENVELOPE *e;
1944 {
1945 	char *template = "\201l\n";
1946 	char buf[MAXLINE];
1947 
1948 	if (bitnset(M_NHDR, m->m_flags))
1949 		return;
1950 
1951 # ifdef UGLYUUCP
1952 	if (bitnset(M_UGLYUUCP, m->m_flags))
1953 	{
1954 		char *bang;
1955 		char xbuf[MAXLINE];
1956 
1957 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1958 		bang = strchr(buf, '!');
1959 		if (bang == NULL)
1960 		{
1961 			errno = 0;
1962 			syserr("554 No ! in UUCP From address! (%s given)", buf);
1963 		}
1964 		else
1965 		{
1966 			*bang++ = '\0';
1967 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1968 			template = xbuf;
1969 		}
1970 	}
1971 # endif /* UGLYUUCP */
1972 	expand(template, buf, &buf[sizeof buf - 1], e);
1973 	putline(buf, fp, m);
1974 }
1975 /*
1976 **  PUTBODY -- put the body of a message.
1977 **
1978 **	Parameters:
1979 **		fp -- file to output onto.
1980 **		m -- a mailer descriptor to control output format.
1981 **		e -- the envelope to put out.
1982 **		separator -- if non-NULL, a message separator that must
1983 **			not be permitted in the resulting message.
1984 **
1985 **	Returns:
1986 **		none.
1987 **
1988 **	Side Effects:
1989 **		The message is written onto fp.
1990 */
1991 
1992 putbody(fp, m, e, separator)
1993 	FILE *fp;
1994 	MAILER *m;
1995 	register ENVELOPE *e;
1996 	char *separator;
1997 {
1998 	char buf[MAXLINE];
1999 
2000 	/*
2001 	**  Output the body of the message
2002 	*/
2003 
2004 	if (e->e_dfp == NULL)
2005 	{
2006 		if (e->e_df != NULL)
2007 		{
2008 			e->e_dfp = fopen(e->e_df, "r");
2009 			if (e->e_dfp == NULL)
2010 				syserr("putbody: Cannot open %s for %s from %s",
2011 				e->e_df, e->e_to, e->e_from.q_paddr);
2012 		}
2013 		else
2014 			putline("<<< No Message Collected >>>", fp, m);
2015 	}
2016 	if (e->e_dfp != NULL)
2017 	{
2018 		rewind(e->e_dfp);
2019 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
2020 		{
2021 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
2022 			    strncmp(buf, "From ", 5) == 0)
2023 				(void) putc('>', fp);
2024 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
2025 			{
2026 				/* possible separator */
2027 				int sl = strlen(separator);
2028 
2029 				if (strncmp(&buf[2], separator, sl) == 0)
2030 					(void) putc(' ', fp);
2031 			}
2032 			putline(buf, fp, m);
2033 		}
2034 
2035 		if (ferror(e->e_dfp))
2036 		{
2037 			syserr("putbody: %s: read error", e->e_df);
2038 			ExitStat = EX_IOERR;
2039 		}
2040 	}
2041 
2042 	/* some mailers want extra blank line at end of message */
2043 	if (bitnset(M_BLANKEND, m->m_flags) && buf[0] != '\0' && buf[0] != '\n')
2044 		putline("", fp, m);
2045 
2046 	(void) fflush(fp);
2047 	if (ferror(fp) && errno != EPIPE)
2048 	{
2049 		syserr("putbody: write error");
2050 		ExitStat = EX_IOERR;
2051 	}
2052 	errno = 0;
2053 }
2054 /*
2055 **  MAILFILE -- Send a message to a file.
2056 **
2057 **	If the file has the setuid/setgid bits set, but NO execute
2058 **	bits, sendmail will try to become the owner of that file
2059 **	rather than the real user.  Obviously, this only works if
2060 **	sendmail runs as root.
2061 **
2062 **	This could be done as a subordinate mailer, except that it
2063 **	is used implicitly to save messages in ~/dead.letter.  We
2064 **	view this as being sufficiently important as to include it
2065 **	here.  For example, if the system is dying, we shouldn't have
2066 **	to create another process plus some pipes to save the message.
2067 **
2068 **	Parameters:
2069 **		filename -- the name of the file to send to.
2070 **		ctladdr -- the controlling address header -- includes
2071 **			the userid/groupid to be when sending.
2072 **
2073 **	Returns:
2074 **		The exit code associated with the operation.
2075 **
2076 **	Side Effects:
2077 **		none.
2078 */
2079 
2080 mailfile(filename, ctladdr, e)
2081 	char *filename;
2082 	ADDRESS *ctladdr;
2083 	register ENVELOPE *e;
2084 {
2085 	register FILE *f;
2086 	register int pid;
2087 	int mode;
2088 
2089 	if (tTd(11, 1))
2090 	{
2091 		printf("mailfile %s\n  ctladdr=", filename);
2092 		printaddr(ctladdr, FALSE);
2093 	}
2094 
2095 	if (e->e_xfp != NULL)
2096 		fflush(e->e_xfp);
2097 
2098 	/*
2099 	**  Fork so we can change permissions here.
2100 	**	Note that we MUST use fork, not vfork, because of
2101 	**	the complications of calling subroutines, etc.
2102 	*/
2103 
2104 	DOFORK(fork);
2105 
2106 	if (pid < 0)
2107 		return (EX_OSERR);
2108 	else if (pid == 0)
2109 	{
2110 		/* child -- actually write to file */
2111 		struct stat stb;
2112 
2113 		(void) setsignal(SIGINT, SIG_DFL);
2114 		(void) setsignal(SIGHUP, SIG_DFL);
2115 		(void) setsignal(SIGTERM, SIG_DFL);
2116 		(void) umask(OldUmask);
2117 
2118 		if (stat(filename, &stb) < 0)
2119 			stb.st_mode = FileMode;
2120 		mode = stb.st_mode;
2121 
2122 		/* limit the errors to those actually caused in the child */
2123 		errno = 0;
2124 		ExitStat = EX_OK;
2125 
2126 		if (bitset(0111, stb.st_mode))
2127 			exit(EX_CANTCREAT);
2128 		if (ctladdr != NULL)
2129 		{
2130 			/* ignore setuid and setgid bits */
2131 			mode &= ~(S_ISGID|S_ISUID);
2132 		}
2133 
2134 		/* we have to open the dfile BEFORE setuid */
2135 		if (e->e_dfp == NULL && e->e_df != NULL)
2136 		{
2137 			e->e_dfp = fopen(e->e_df, "r");
2138 			if (e->e_dfp == NULL)
2139 			{
2140 				syserr("mailfile: Cannot open %s for %s from %s",
2141 					e->e_df, e->e_to, e->e_from.q_paddr);
2142 			}
2143 		}
2144 
2145 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
2146 		{
2147 			if (ctladdr == NULL || ctladdr->q_uid == 0)
2148 			{
2149 				(void) initgroups(DefUser, DefGid);
2150 			}
2151 			else
2152 			{
2153 				(void) initgroups(ctladdr->q_ruser ?
2154 					ctladdr->q_ruser : ctladdr->q_user,
2155 					ctladdr->q_gid);
2156 			}
2157 		}
2158 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
2159 		{
2160 			if (ctladdr == NULL || ctladdr->q_uid == 0)
2161 				(void) setuid(DefUid);
2162 			else
2163 				(void) setuid(ctladdr->q_uid);
2164 		}
2165 		FileName = filename;
2166 		LineNumber = 0;
2167 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
2168 		if (f == NULL)
2169 		{
2170 			message("554 cannot open: %s", errstring(errno));
2171 			exit(EX_CANTCREAT);
2172 		}
2173 
2174 		putfromline(f, FileMailer, e);
2175 		(*e->e_puthdr)(f, FileMailer, e);
2176 		putline("\n", f, FileMailer);
2177 		(*e->e_putbody)(f, FileMailer, e, NULL);
2178 		putline("\n", f, FileMailer);
2179 		if (ferror(f))
2180 		{
2181 			message("451 I/O error: %s", errstring(errno));
2182 			setstat(EX_IOERR);
2183 		}
2184 		(void) xfclose(f, "mailfile", filename);
2185 		(void) fflush(stdout);
2186 
2187 		/* reset ISUID & ISGID bits for paranoid systems */
2188 		(void) chmod(filename, (int) stb.st_mode);
2189 		exit(ExitStat);
2190 		/*NOTREACHED*/
2191 	}
2192 	else
2193 	{
2194 		/* parent -- wait for exit status */
2195 		int st;
2196 
2197 		st = waitfor(pid);
2198 		if (WIFEXITED(st))
2199 			return (WEXITSTATUS(st));
2200 		else
2201 		{
2202 			syserr("child died on signal %d", st);
2203 			return (EX_UNAVAILABLE);
2204 		}
2205 		/*NOTREACHED*/
2206 	}
2207 }
2208 /*
2209 **  HOSTSIGNATURE -- return the "signature" for a host.
2210 **
2211 **	The signature describes how we are going to send this -- it
2212 **	can be just the hostname (for non-Internet hosts) or can be
2213 **	an ordered list of MX hosts.
2214 **
2215 **	Parameters:
2216 **		m -- the mailer describing this host.
2217 **		host -- the host name.
2218 **		e -- the current envelope.
2219 **
2220 **	Returns:
2221 **		The signature for this host.
2222 **
2223 **	Side Effects:
2224 **		Can tweak the symbol table.
2225 */
2226 
2227 char *
2228 hostsignature(m, host, e)
2229 	register MAILER *m;
2230 	char *host;
2231 	ENVELOPE *e;
2232 {
2233 	register char *p;
2234 	register STAB *s;
2235 	int i;
2236 	int len;
2237 #ifdef NAMED_BIND
2238 	int nmx;
2239 	auto int rcode;
2240 	char *hp;
2241 	char *endp;
2242 	int oldoptions;
2243 	char *mxhosts[MAXMXHOSTS + 1];
2244 #endif
2245 
2246 	/*
2247 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2248 	*/
2249 
2250 	p = m->m_mailer;
2251 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2252 	{
2253 		/* just an ordinary mailer */
2254 		return host;
2255 	}
2256 
2257 	/*
2258 	**  Look it up in the symbol table.
2259 	*/
2260 
2261 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2262 	if (s->s_hostsig != NULL)
2263 		return s->s_hostsig;
2264 
2265 	/*
2266 	**  Not already there -- create a signature.
2267 	*/
2268 
2269 #ifdef NAMED_BIND
2270 	if (ConfigLevel < 2)
2271 	{
2272 		oldoptions = _res.options;
2273 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2274 	}
2275 
2276 	for (hp = host; hp != NULL; hp = endp)
2277 	{
2278 		endp = strchr(hp, ':');
2279 		if (endp != NULL)
2280 			*endp = '\0';
2281 
2282 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2283 
2284 		if (nmx <= 0)
2285 		{
2286 			register MCI *mci;
2287 
2288 			/* update the connection info for this host */
2289 			mci = mci_get(hp, m);
2290 			mci->mci_exitstat = rcode;
2291 			mci->mci_errno = errno;
2292 #ifdef NAMED_BIND
2293 			mci->mci_herrno = h_errno;
2294 #endif
2295 
2296 			/* and return the original host name as the signature */
2297 			nmx = 1;
2298 			mxhosts[0] = hp;
2299 		}
2300 
2301 		len = 0;
2302 		for (i = 0; i < nmx; i++)
2303 		{
2304 			len += strlen(mxhosts[i]) + 1;
2305 		}
2306 		if (s->s_hostsig != NULL)
2307 			len += strlen(s->s_hostsig) + 1;
2308 		p = xalloc(len);
2309 		if (s->s_hostsig != NULL)
2310 		{
2311 			(void) strcpy(p, s->s_hostsig);
2312 			free(s->s_hostsig);
2313 			s->s_hostsig = p;
2314 			p += strlen(p);
2315 			*p++ = ':';
2316 		}
2317 		else
2318 			s->s_hostsig = p;
2319 		for (i = 0; i < nmx; i++)
2320 		{
2321 			if (i != 0)
2322 				*p++ = ':';
2323 			strcpy(p, mxhosts[i]);
2324 			p += strlen(p);
2325 		}
2326 		if (endp != NULL)
2327 			*endp++ = ':';
2328 	}
2329 	makelower(s->s_hostsig);
2330 	if (ConfigLevel < 2)
2331 		_res.options = oldoptions;
2332 #else
2333 	/* not using BIND -- the signature is just the host name */
2334 	s->s_hostsig = host;
2335 #endif
2336 	if (tTd(17, 1))
2337 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2338 	return s->s_hostsig;
2339 }
2340