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.63 (Berkeley) 01/15/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 && m != ProgMailer &&
894 	    bitset(QGOODUID, e->e_from.q_flags))
895 		ctladdr = &e->e_from;
896 
897 #ifdef NAMED_BIND
898 	if (ConfigLevel < 2)
899 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
900 #endif
901 
902 	if (tTd(11, 1))
903 	{
904 		printf("openmailer:");
905 		printav(pv);
906 	}
907 	errno = 0;
908 
909 	CurHostName = m->m_mailer;
910 
911 	/*
912 	**  Deal with the special case of mail handled through an IPC
913 	**  connection.
914 	**	In this case we don't actually fork.  We must be
915 	**	running SMTP for this to work.  We will return a
916 	**	zero pid to indicate that we are running IPC.
917 	**  We also handle a debug version that just talks to stdin/out.
918 	*/
919 
920 	curhost = NULL;
921 	SmtpPhase = NULL;
922 	mci = NULL;
923 
924 #ifdef XDEBUG
925 	{
926 		char wbuf[MAXLINE];
927 
928 		/* make absolutely certain 0, 1, and 2 are in use */
929 		sprintf(wbuf, "%s... openmailer(%s)", e->e_to, m->m_name);
930 		checkfd012(wbuf);
931 	}
932 #endif
933 
934 	/* check for Local Person Communication -- not for mortals!!! */
935 	if (strcmp(m->m_mailer, "[LPC]") == 0)
936 	{
937 		mci = (MCI *) xalloc(sizeof *mci);
938 		bzero((char *) mci, sizeof *mci);
939 		mci->mci_in = stdin;
940 		mci->mci_out = stdout;
941 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
942 		mci->mci_mailer = m;
943 	}
944 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
945 		 strcmp(m->m_mailer, "[TCP]") == 0)
946 	{
947 #ifdef DAEMON
948 		register int i;
949 		register u_short port;
950 
951 		if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
952 		{
953 			syserr("null host name for %s mailer", m->m_mailer);
954 			rcode = EX_CONFIG;
955 			goto give_up;
956 		}
957 
958 		CurHostName = pv[1];
959 		curhost = hostsignature(m, pv[1], e);
960 
961 		if (curhost == NULL || curhost[0] == '\0')
962 		{
963 			syserr("null host signature for %s", pv[1]);
964 			rcode = EX_OSERR;
965 			goto give_up;
966 		}
967 
968 		if (!clever)
969 		{
970 			syserr("554 non-clever IPC");
971 			rcode = EX_CONFIG;
972 			goto give_up;
973 		}
974 		if (pv[2] != NULL)
975 			port = atoi(pv[2]);
976 		else
977 			port = 0;
978 tryhost:
979 		while (*curhost != '\0')
980 		{
981 			register char *p;
982 			static char hostbuf[MAXNAME];
983 
984 			/* pull the next host from the signature */
985 			p = strchr(curhost, ':');
986 			if (p == NULL)
987 				p = &curhost[strlen(curhost)];
988 			if (p == curhost)
989 			{
990 				syserr("deliver: null host name in signature");
991 				curhost++;
992 				continue;
993 			}
994 			strncpy(hostbuf, curhost, p - curhost);
995 			hostbuf[p - curhost] = '\0';
996 			if (*p != '\0')
997 				p++;
998 			curhost = p;
999 
1000 			/* see if we already know that this host is fried */
1001 			CurHostName = hostbuf;
1002 			mci = mci_get(hostbuf, m);
1003 			if (mci->mci_state != MCIS_CLOSED)
1004 			{
1005 				if (tTd(11, 1))
1006 				{
1007 					printf("openmailer: ");
1008 					mci_dump(mci, FALSE);
1009 				}
1010 				CurHostName = mci->mci_host;
1011 				break;
1012 			}
1013 			mci->mci_mailer = m;
1014 			if (mci->mci_exitstat != EX_OK)
1015 				continue;
1016 
1017 			/* try the connection */
1018 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
1019 			message("Connecting to %s (%s)...",
1020 				hostbuf, m->m_name);
1021 			i = makeconnection(hostbuf, port, mci,
1022 				bitnset(M_SECURE_PORT, m->m_flags));
1023 			mci->mci_exitstat = i;
1024 			mci->mci_errno = errno;
1025 #ifdef NAMED_BIND
1026 			mci->mci_herrno = h_errno;
1027 #endif
1028 			if (i == EX_OK)
1029 			{
1030 				mci->mci_state = MCIS_OPENING;
1031 				mci_cache(mci);
1032 				if (TrafficLogFile != NULL)
1033 					fprintf(TrafficLogFile, "%05d == CONNECT %s\n",
1034 						getpid(), hostbuf);
1035 				break;
1036 			}
1037 			else if (tTd(11, 1))
1038 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1039 					i, errno);
1040 
1041 			/* enter status of this host */
1042 			setstat(i);
1043 
1044 			/* should print some message here for -v mode */
1045 		}
1046 		if (mci == NULL)
1047 		{
1048 			syserr("deliver: no host name");
1049 			rcode = EX_OSERR;
1050 			goto give_up;
1051 		}
1052 		mci->mci_pid = 0;
1053 #else /* no DAEMON */
1054 		syserr("554 openmailer: no IPC");
1055 		if (tTd(11, 1))
1056 			printf("openmailer: NULL\n");
1057 		rcode = EX_UNAVAILABLE;
1058 		goto give_up;
1059 #endif /* DAEMON */
1060 	}
1061 	else
1062 	{
1063 		if (TrafficLogFile != NULL)
1064 		{
1065 			char **av;
1066 
1067 			fprintf(TrafficLogFile, "%05d === EXEC", getpid());
1068 			for (av = pv; *av != NULL; av++)
1069 				fprintf(TrafficLogFile, " %s", *av);
1070 			fprintf(TrafficLogFile, "\n");
1071 		}
1072 
1073 		/* create a pipe to shove the mail through */
1074 		if (pipe(mpvect) < 0)
1075 		{
1076 			syserr("%s... openmailer(%s): pipe (to mailer)",
1077 				e->e_to, m->m_name);
1078 			if (tTd(11, 1))
1079 				printf("openmailer: NULL\n");
1080 			rcode = EX_OSERR;
1081 			goto give_up;
1082 		}
1083 
1084 		/* if this mailer speaks smtp, create a return pipe */
1085 		if (clever && pipe(rpvect) < 0)
1086 		{
1087 			syserr("%s... openmailer(%s): pipe (from mailer)",
1088 				e->e_to, m->m_name);
1089 			(void) close(mpvect[0]);
1090 			(void) close(mpvect[1]);
1091 			if (tTd(11, 1))
1092 				printf("openmailer: NULL\n");
1093 			rcode = EX_OSERR;
1094 			goto give_up;
1095 		}
1096 
1097 		/*
1098 		**  Actually fork the mailer process.
1099 		**	DOFORK is clever about retrying.
1100 		**
1101 		**	Dispose of SIGCHLD signal catchers that may be laying
1102 		**	around so that endmail will get it.
1103 		*/
1104 
1105 		if (e->e_xfp != NULL)
1106 			(void) fflush(e->e_xfp);		/* for debugging */
1107 		(void) fflush(stdout);
1108 # ifdef SIGCHLD
1109 		(void) setsignal(SIGCHLD, SIG_DFL);
1110 # endif /* SIGCHLD */
1111 		DOFORK(FORK);
1112 		/* pid is set by DOFORK */
1113 		if (pid < 0)
1114 		{
1115 			/* failure */
1116 			syserr("%s... openmailer(%s): cannot fork",
1117 				e->e_to, m->m_name);
1118 			(void) close(mpvect[0]);
1119 			(void) close(mpvect[1]);
1120 			if (clever)
1121 			{
1122 				(void) close(rpvect[0]);
1123 				(void) close(rpvect[1]);
1124 			}
1125 			if (tTd(11, 1))
1126 				printf("openmailer: NULL\n");
1127 			rcode = EX_OSERR;
1128 			goto give_up;
1129 		}
1130 		else if (pid == 0)
1131 		{
1132 			int i;
1133 			int saveerrno;
1134 			char **ep;
1135 			char *env[MAXUSERENVIRON];
1136 			extern char **environ;
1137 			extern int DtableSize;
1138 
1139 			/* child -- set up input & exec mailer */
1140 			(void) setsignal(SIGINT, SIG_IGN);
1141 			(void) setsignal(SIGHUP, SIG_IGN);
1142 			(void) setsignal(SIGTERM, SIG_DFL);
1143 
1144 			/* reset user and group */
1145 			if (!bitnset(M_RESTR, m->m_flags))
1146 			{
1147 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1148 				{
1149 					(void) initgroups(DefUser, DefGid);
1150 					(void) setgid(DefGid);
1151 					(void) setuid(DefUid);
1152 				}
1153 				else
1154 				{
1155 					(void) initgroups(ctladdr->q_ruser?
1156 						ctladdr->q_ruser: ctladdr->q_user,
1157 						ctladdr->q_gid);
1158 					(void) setgid(ctladdr->q_gid);
1159 					(void) setuid(ctladdr->q_uid);
1160 				}
1161 			}
1162 
1163 			if (tTd(11, 2))
1164 				printf("openmailer: running as r/euid=%d/%d\n",
1165 					getuid(), geteuid());
1166 
1167 			/* move into some "safe" directory */
1168 			if (m->m_execdir != NULL)
1169 			{
1170 				char *p, *q;
1171 				char buf[MAXLINE];
1172 
1173 				for (p = m->m_execdir; p != NULL; p = q)
1174 				{
1175 					q = strchr(p, ':');
1176 					if (q != NULL)
1177 						*q = '\0';
1178 					expand(p, buf, &buf[sizeof buf] - 1, e);
1179 					if (q != NULL)
1180 						*q++ = ':';
1181 					if (tTd(11, 20))
1182 						printf("openmailer: trydir %s\n",
1183 							buf);
1184 					if (buf[0] != '\0' && chdir(buf) >= 0)
1185 						break;
1186 				}
1187 			}
1188 
1189 			/* arrange to filter std & diag output of command */
1190 			if (clever)
1191 			{
1192 				(void) close(rpvect[0]);
1193 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1194 				{
1195 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1196 						e->e_to, m->m_name, rpvect[1]);
1197 					_exit(EX_OSERR);
1198 				}
1199 				(void) close(rpvect[1]);
1200 			}
1201 			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON || HoldErrs)
1202 			{
1203 				/* put mailer output in transcript */
1204 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1205 				{
1206 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1207 						e->e_to, m->m_name,
1208 						fileno(e->e_xfp));
1209 					_exit(EX_OSERR);
1210 				}
1211 			}
1212 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1213 			{
1214 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1215 					e->e_to, m->m_name);
1216 				_exit(EX_OSERR);
1217 			}
1218 
1219 			/* arrange to get standard input */
1220 			(void) close(mpvect[1]);
1221 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1222 			{
1223 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1224 					e->e_to, m->m_name, mpvect[0]);
1225 				_exit(EX_OSERR);
1226 			}
1227 			(void) close(mpvect[0]);
1228 
1229 			/* arrange for all the files to be closed */
1230 			for (i = 3; i < DtableSize; i++)
1231 			{
1232 				register int j;
1233 
1234 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1235 					(void) fcntl(i, F_SETFD, j | 1);
1236 			}
1237 
1238 			/* set up the mailer environment */
1239 			i = 0;
1240 			env[i++] = "AGENT=sendmail";
1241 			for (ep = environ; *ep != NULL; ep++)
1242 			{
1243 				if (strncmp(*ep, "TZ=", 3) == 0)
1244 					env[i++] = *ep;
1245 			}
1246 			env[i++] = NULL;
1247 
1248 			/* try to execute the mailer */
1249 			execve(m->m_mailer, pv, env);
1250 			saveerrno = errno;
1251 			syserr("Cannot exec %s", m->m_mailer);
1252 			if (m == LocalMailer || transienterror(saveerrno))
1253 				_exit(EX_OSERR);
1254 			_exit(EX_UNAVAILABLE);
1255 		}
1256 
1257 		/*
1258 		**  Set up return value.
1259 		*/
1260 
1261 		mci = (MCI *) xalloc(sizeof *mci);
1262 		bzero((char *) mci, sizeof *mci);
1263 		mci->mci_mailer = m;
1264 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1265 		mci->mci_pid = pid;
1266 		(void) close(mpvect[0]);
1267 		mci->mci_out = fdopen(mpvect[1], "w");
1268 		if (mci->mci_out == NULL)
1269 		{
1270 			syserr("deliver: cannot create mailer output channel, fd=%d",
1271 				mpvect[1]);
1272 			(void) close(mpvect[1]);
1273 			if (clever)
1274 			{
1275 				(void) close(rpvect[0]);
1276 				(void) close(rpvect[1]);
1277 			}
1278 			rcode = EX_OSERR;
1279 			goto give_up;
1280 		}
1281 		if (clever)
1282 		{
1283 			(void) close(rpvect[1]);
1284 			mci->mci_in = fdopen(rpvect[0], "r");
1285 			if (mci->mci_in == NULL)
1286 			{
1287 				syserr("deliver: cannot create mailer input channel, fd=%d",
1288 					mpvect[1]);
1289 				(void) close(rpvect[0]);
1290 				fclose(mci->mci_out);
1291 				mci->mci_out = NULL;
1292 				rcode = EX_OSERR;
1293 				goto give_up;
1294 			}
1295 		}
1296 		else
1297 		{
1298 			mci->mci_flags |= MCIF_TEMP;
1299 			mci->mci_in = NULL;
1300 		}
1301 	}
1302 
1303 	/*
1304 	**  If we are in SMTP opening state, send initial protocol.
1305 	*/
1306 
1307 	if (clever && mci->mci_state != MCIS_CLOSED)
1308 	{
1309 		smtpinit(m, mci, e);
1310 	}
1311 	if (tTd(11, 1))
1312 	{
1313 		printf("openmailer: ");
1314 		mci_dump(mci, FALSE);
1315 	}
1316 
1317 	if (mci->mci_state != MCIS_OPEN)
1318 	{
1319 		/* couldn't open the mailer */
1320 		rcode = mci->mci_exitstat;
1321 		errno = mci->mci_errno;
1322 #ifdef NAMED_BIND
1323 		h_errno = mci->mci_herrno;
1324 #endif
1325 		if (rcode == EX_OK)
1326 		{
1327 			/* shouldn't happen */
1328 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1329 				rcode, mci->mci_state, firstsig);
1330 			rcode = EX_SOFTWARE;
1331 		}
1332 		else if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
1333 		{
1334 			/* try next MX site */
1335 			goto tryhost;
1336 		}
1337 	}
1338 	else if (!clever)
1339 	{
1340 		/*
1341 		**  Format and send message.
1342 		*/
1343 
1344 		putfromline(mci->mci_out, m, e);
1345 		(*e->e_puthdr)(mci->mci_out, m, e);
1346 		putline("\n", mci->mci_out, m);
1347 		(*e->e_putbody)(mci->mci_out, m, e, NULL);
1348 
1349 		/* get the exit status */
1350 		rcode = endmailer(mci, e, pv);
1351 	}
1352 	else
1353 #ifdef SMTP
1354 	{
1355 		/*
1356 		**  Send the MAIL FROM: protocol
1357 		*/
1358 
1359 		rcode = smtpmailfrom(m, mci, e);
1360 		if (rcode == EX_OK)
1361 		{
1362 			register char *t = tobuf;
1363 			register int i;
1364 
1365 			/* send the recipient list */
1366 			tobuf[0] = '\0';
1367 			for (to = tochain; to != NULL; to = to->q_tchain)
1368 			{
1369 				e->e_to = to->q_paddr;
1370 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1371 				{
1372 					markfailure(e, to, i);
1373 					giveresponse(i, m, mci, ctladdr, e);
1374 				}
1375 				else
1376 				{
1377 					*t++ = ',';
1378 					for (p = to->q_paddr; *p; *t++ = *p++)
1379 						continue;
1380 					*t = '\0';
1381 				}
1382 			}
1383 
1384 			/* now send the data */
1385 			if (tobuf[0] == '\0')
1386 			{
1387 				rcode = EX_OK;
1388 				e->e_to = NULL;
1389 				if (bitset(MCIF_CACHED, mci->mci_flags))
1390 					smtprset(m, mci, e);
1391 			}
1392 			else
1393 			{
1394 				e->e_to = tobuf + 1;
1395 				rcode = smtpdata(m, mci, e);
1396 			}
1397 
1398 			/* now close the connection */
1399 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1400 				smtpquit(m, mci, e);
1401 		}
1402 		if (rcode != EX_OK && curhost != NULL && *curhost != '\0')
1403 		{
1404 			/* try next MX site */
1405 			goto tryhost;
1406 		}
1407 	}
1408 #else /* not SMTP */
1409 	{
1410 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1411 		rcode = EX_CONFIG;
1412 		goto give_up;
1413 	}
1414 #endif /* SMTP */
1415 #ifdef NAMED_BIND
1416 	if (ConfigLevel < 2)
1417 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1418 #endif
1419 
1420 	/* arrange a return receipt if requested */
1421 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1422 	    bitnset(M_LOCALMAILER, m->m_flags))
1423 	{
1424 		e->e_flags |= EF_SENDRECEIPT;
1425 		/* do we want to send back more info? */
1426 	}
1427 
1428 	/*
1429 	**  Do final status disposal.
1430 	**	We check for something in tobuf for the SMTP case.
1431 	**	If we got a temporary failure, arrange to queue the
1432 	**		addressees.
1433 	*/
1434 
1435   give_up:
1436 	if (tobuf[0] != '\0')
1437 		giveresponse(rcode, m, mci, ctladdr, e);
1438 	for (to = tochain; to != NULL; to = to->q_tchain)
1439 	{
1440 		if (rcode != EX_OK)
1441 			markfailure(e, to, rcode);
1442 		else
1443 		{
1444 			to->q_flags |= QSENT;
1445 			e->e_nsent++;
1446 			if (e->e_receiptto != NULL &&
1447 			    bitnset(M_LOCALMAILER, m->m_flags))
1448 			{
1449 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1450 					to->q_paddr);
1451 			}
1452 		}
1453 	}
1454 
1455 	/*
1456 	**  Restore state and return.
1457 	*/
1458 
1459 #ifdef XDEBUG
1460 	{
1461 		char wbuf[MAXLINE];
1462 
1463 		/* make absolutely certain 0, 1, and 2 are in use */
1464 		sprintf(wbuf, "%s... end of deliver(%s)",
1465 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1466 			m->m_name);
1467 		checkfd012(wbuf);
1468 	}
1469 #endif
1470 
1471 	errno = 0;
1472 	define('g', (char *) NULL, e);
1473 	return (rcode);
1474 }
1475 /*
1476 **  MARKFAILURE -- mark a failure on a specific address.
1477 **
1478 **	Parameters:
1479 **		e -- the envelope we are sending.
1480 **		q -- the address to mark.
1481 **		rcode -- the code signifying the particular failure.
1482 **
1483 **	Returns:
1484 **		none.
1485 **
1486 **	Side Effects:
1487 **		marks the address (and possibly the envelope) with the
1488 **			failure so that an error will be returned or
1489 **			the message will be queued, as appropriate.
1490 */
1491 
1492 markfailure(e, q, rcode)
1493 	register ENVELOPE *e;
1494 	register ADDRESS *q;
1495 	int rcode;
1496 {
1497 	char buf[MAXLINE];
1498 
1499 	switch (rcode)
1500 	{
1501 	  case EX_OK:
1502 		break;
1503 
1504 	  case EX_TEMPFAIL:
1505 	  case EX_IOERR:
1506 	  case EX_OSERR:
1507 		q->q_flags |= QQUEUEUP;
1508 		break;
1509 
1510 	  default:
1511 		q->q_flags |= QBADADDR;
1512 		break;
1513 	}
1514 }
1515 /*
1516 **  ENDMAILER -- Wait for mailer to terminate.
1517 **
1518 **	We should never get fatal errors (e.g., segmentation
1519 **	violation), so we report those specially.  For other
1520 **	errors, we choose a status message (into statmsg),
1521 **	and if it represents an error, we print it.
1522 **
1523 **	Parameters:
1524 **		pid -- pid of mailer.
1525 **		e -- the current envelope.
1526 **		pv -- the parameter vector that invoked the mailer
1527 **			(for error messages).
1528 **
1529 **	Returns:
1530 **		exit code of mailer.
1531 **
1532 **	Side Effects:
1533 **		none.
1534 */
1535 
1536 endmailer(mci, e, pv)
1537 	register MCI *mci;
1538 	register ENVELOPE *e;
1539 	char **pv;
1540 {
1541 	int st;
1542 
1543 	/* close any connections */
1544 	if (mci->mci_in != NULL)
1545 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1546 	if (mci->mci_out != NULL)
1547 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1548 	mci->mci_in = mci->mci_out = NULL;
1549 	mci->mci_state = MCIS_CLOSED;
1550 
1551 	/* in the IPC case there is nothing to wait for */
1552 	if (mci->mci_pid == 0)
1553 		return (EX_OK);
1554 
1555 	/* wait for the mailer process to die and collect status */
1556 	st = waitfor(mci->mci_pid);
1557 	if (st == -1)
1558 	{
1559 		syserr("endmailer %s: wait", pv[0]);
1560 		return (EX_SOFTWARE);
1561 	}
1562 
1563 	if (WIFEXITED(st))
1564 	{
1565 		/* normal death -- return status */
1566 		return (WEXITSTATUS(st));
1567 	}
1568 
1569 	/* it died a horrid death */
1570 	syserr("451 mailer %s died with signal %o",
1571 		mci->mci_mailer->m_name, st);
1572 
1573 	/* log the arguments */
1574 	if (pv != NULL && e->e_xfp != NULL)
1575 	{
1576 		register char **av;
1577 
1578 		fprintf(e->e_xfp, "Arguments:");
1579 		for (av = pv; *av != NULL; av++)
1580 			fprintf(e->e_xfp, " %s", *av);
1581 		fprintf(e->e_xfp, "\n");
1582 	}
1583 
1584 	ExitStat = EX_TEMPFAIL;
1585 	return (EX_TEMPFAIL);
1586 }
1587 /*
1588 **  GIVERESPONSE -- Interpret an error response from a mailer
1589 **
1590 **	Parameters:
1591 **		stat -- the status code from the mailer (high byte
1592 **			only; core dumps must have been taken care of
1593 **			already).
1594 **		m -- the mailer info for this mailer.
1595 **		mci -- the mailer connection info -- can be NULL if the
1596 **			response is given before the connection is made.
1597 **		ctladdr -- the controlling address for the recipient
1598 **			address(es).
1599 **		e -- the current envelope.
1600 **
1601 **	Returns:
1602 **		none.
1603 **
1604 **	Side Effects:
1605 **		Errors may be incremented.
1606 **		ExitStat may be set.
1607 */
1608 
1609 giveresponse(stat, m, mci, ctladdr, e)
1610 	int stat;
1611 	register MAILER *m;
1612 	register MCI *mci;
1613 	ADDRESS *ctladdr;
1614 	ENVELOPE *e;
1615 {
1616 	register const char *statmsg;
1617 	extern char *SysExMsg[];
1618 	register int i;
1619 	extern int N_SysEx;
1620 	char buf[MAXLINE];
1621 
1622 	/*
1623 	**  Compute status message from code.
1624 	*/
1625 
1626 	i = stat - EX__BASE;
1627 	if (stat == 0)
1628 	{
1629 		statmsg = "250 Sent";
1630 		if (e->e_statmsg != NULL)
1631 		{
1632 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1633 			statmsg = buf;
1634 		}
1635 	}
1636 	else if (i < 0 || i > N_SysEx)
1637 	{
1638 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1639 		stat = EX_UNAVAILABLE;
1640 		statmsg = buf;
1641 	}
1642 	else if (stat == EX_TEMPFAIL)
1643 	{
1644 		(void) strcpy(buf, SysExMsg[i] + 1);
1645 #ifdef NAMED_BIND
1646 		if (h_errno == TRY_AGAIN)
1647 			statmsg = errstring(h_errno+E_DNSBASE);
1648 		else
1649 #endif
1650 		{
1651 			if (errno != 0)
1652 				statmsg = errstring(errno);
1653 			else
1654 			{
1655 #ifdef SMTP
1656 				statmsg = SmtpError;
1657 #else /* SMTP */
1658 				statmsg = NULL;
1659 #endif /* SMTP */
1660 			}
1661 		}
1662 		if (statmsg != NULL && statmsg[0] != '\0')
1663 		{
1664 			(void) strcat(buf, ": ");
1665 			(void) strcat(buf, statmsg);
1666 		}
1667 		statmsg = buf;
1668 	}
1669 #ifdef NAMED_BIND
1670 	else if (stat == EX_NOHOST && h_errno != 0)
1671 	{
1672 		statmsg = errstring(h_errno + E_DNSBASE);
1673 		(void) sprintf(buf, "%s (%s)", SysExMsg[i], statmsg);
1674 		statmsg = buf;
1675 	}
1676 #endif
1677 	else
1678 	{
1679 		statmsg = SysExMsg[i];
1680 		if (*statmsg++ == ':')
1681 		{
1682 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1683 			statmsg = buf;
1684 		}
1685 	}
1686 
1687 	/*
1688 	**  Print the message as appropriate
1689 	*/
1690 
1691 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1692 	{
1693 		extern char MsgBuf[];
1694 
1695 		message(&statmsg[4], errstring(errno));
1696 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1697 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1698 	}
1699 	else
1700 	{
1701 		Errors++;
1702 		usrerr(statmsg, errstring(errno));
1703 	}
1704 
1705 	/*
1706 	**  Final cleanup.
1707 	**	Log a record of the transaction.  Compute the new
1708 	**	ExitStat -- if we already had an error, stick with
1709 	**	that.
1710 	*/
1711 
1712 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1713 		logdelivery(m, mci, &statmsg[4], ctladdr, e);
1714 
1715 	if (stat != EX_TEMPFAIL)
1716 		setstat(stat);
1717 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1718 	{
1719 		if (e->e_message != NULL)
1720 			free(e->e_message);
1721 		e->e_message = newstr(&statmsg[4]);
1722 	}
1723 	errno = 0;
1724 #ifdef NAMED_BIND
1725 	h_errno = 0;
1726 #endif
1727 }
1728 /*
1729 **  LOGDELIVERY -- log the delivery in the system log
1730 **
1731 **	Care is taken to avoid logging lines that are too long, because
1732 **	some versions of syslog have an unfortunate proclivity for core
1733 **	dumping.  This is a hack, to be sure, that is at best empirical.
1734 **
1735 **	Parameters:
1736 **		m -- the mailer info.  Can be NULL for initial queue.
1737 **		mci -- the mailer connection info -- can be NULL if the
1738 **			log is occuring when no connection is active.
1739 **		stat -- the message to print for the status.
1740 **		ctladdr -- the controlling address for the to list.
1741 **		e -- the current envelope.
1742 **
1743 **	Returns:
1744 **		none
1745 **
1746 **	Side Effects:
1747 **		none
1748 */
1749 
1750 logdelivery(m, mci, stat, ctladdr, e)
1751 	MAILER *m;
1752 	register MCI *mci;
1753 	char *stat;
1754 	ADDRESS *ctladdr;
1755 	register ENVELOPE *e;
1756 {
1757 # ifdef LOG
1758 	register char *bp;
1759 	register char *p;
1760 	int l;
1761 	char buf[512];
1762 
1763 #  if (SYSLOG_BUFSIZE) >= 256
1764 	bp = buf;
1765 	if (ctladdr != NULL)
1766 	{
1767 		strcpy(bp, ", ctladdr=");
1768 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
1769 		bp += strlen(bp);
1770 		if (bitset(QGOODUID, ctladdr->q_flags))
1771 		{
1772 			(void) sprintf(bp, " (%d/%d)",
1773 					ctladdr->q_uid, ctladdr->q_gid);
1774 			bp += strlen(bp);
1775 		}
1776 	}
1777 
1778 	(void) sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1779 	bp += strlen(bp);
1780 
1781 	if (m != NULL)
1782 	{
1783 		(void) strcpy(bp, ", mailer=");
1784 		(void) strcat(bp, m->m_name);
1785 		bp += strlen(bp);
1786 	}
1787 
1788 	if (mci != NULL && mci->mci_host != NULL)
1789 	{
1790 # ifdef DAEMON
1791 		extern SOCKADDR CurHostAddr;
1792 # endif
1793 
1794 		(void) strcpy(bp, ", relay=");
1795 		(void) strcat(bp, mci->mci_host);
1796 
1797 # ifdef DAEMON
1798 		(void) strcat(bp, " (");
1799 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1800 		(void) strcat(bp, ")");
1801 # endif
1802 	}
1803 	else
1804 	{
1805 		char *p = macvalue('h', e);
1806 
1807 		if (p != NULL && p[0] != '\0')
1808 		{
1809 			(void) strcpy(bp, ", relay=");
1810 			(void) strcat(bp, p);
1811 		}
1812 	}
1813 	bp += strlen(bp);
1814 
1815 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
1816 #if (STATLEN) < 63
1817 # undef STATLEN
1818 # define STATLEN	63
1819 #endif
1820 #if (STATLEN) > 203
1821 # undef STATLEN
1822 # define STATLEN	203
1823 #endif
1824 
1825 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
1826 	{
1827 		/* desperation move -- truncate data */
1828 		bp = buf + sizeof buf - ((STATLEN) + 17);
1829 		strcpy(bp, "...");
1830 		bp += 3;
1831 	}
1832 
1833 	(void) strcpy(bp, ", stat=");
1834 	bp += strlen(bp);
1835 
1836 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
1837 
1838 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
1839 	p = e->e_to;
1840 	while (strlen(p) >= l)
1841 	{
1842 		register char *q = strchr(p + l, ',');
1843 
1844 		if (q == NULL)
1845 			break;
1846 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
1847 			e->e_id, ++q - p, p, buf);
1848 		p = q;
1849 	}
1850 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
1851 
1852 #  else		/* we have a very short log buffer size */
1853 
1854 	l = SYSLOG_BUFSIZE - 80;
1855 	p = e->e_to;
1856 	while (strlen(p) >= l)
1857 	{
1858 		register char *q = strchr(p + l, ',');
1859 
1860 		if (q == NULL)
1861 			break;
1862 		syslog(LOG_INFO, "%s: to=%.*s [more]",
1863 			e->e_id, ++q - p, p);
1864 		p = q;
1865 	}
1866 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
1867 
1868 	if (ctladdr != NULL)
1869 	{
1870 		bp = buf;
1871 		strcpy(buf, "ctladdr=");
1872 		bp += strlen(buf);
1873 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
1874 		bp += strlen(buf);
1875 		if (bitset(QGOODUID, ctladdr->q_flags))
1876 		{
1877 			(void) sprintf(bp, " (%d/%d)",
1878 					ctladdr->q_uid, ctladdr->q_gid);
1879 			bp += strlen(bp);
1880 		}
1881 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1882 	}
1883 	bp = buf;
1884 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1885 	bp += strlen(bp);
1886 
1887 	if (m != NULL)
1888 	{
1889 		sprintf(bp, ", mailer=%s", m->m_name);
1890 		bp += strlen(bp);
1891 	}
1892 
1893 	if (mci != NULL && mci->mci_host != NULL)
1894 	{
1895 # ifdef DAEMON
1896 		extern SOCKADDR CurHostAddr;
1897 # endif
1898 
1899 		sprintf(bp, ", relay=%s", mci->mci_host);
1900 
1901 # ifdef DAEMON
1902 		(void) strcat(bp, " (");
1903 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1904 		(void) strcat(bp, ")");
1905 # endif
1906 	}
1907 	else
1908 	{
1909 		char *p = macvalue('h', e);
1910 
1911 		if (p != NULL && p[0] != '\0')
1912 			sprintf(bp, ", relay=%s", p);
1913 	}
1914 	syslog(LOG_INFO, "%s: %s", e->e_id, buf);
1915 
1916 	syslog(LOG_INFO, "%s: stat=%s", e->e_id, shortenstring(stat, 63));
1917 #  endif /* short log buffer */
1918 # endif /* LOG */
1919 }
1920 /*
1921 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1922 **
1923 **	This can be made an arbitrary message separator by changing $l
1924 **
1925 **	One of the ugliest hacks seen by human eyes is contained herein:
1926 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1927 **	does a well-meaning programmer such as myself have to deal with
1928 **	this kind of antique garbage????
1929 **
1930 **	Parameters:
1931 **		fp -- the file to output to.
1932 **		m -- the mailer describing this entry.
1933 **
1934 **	Returns:
1935 **		none
1936 **
1937 **	Side Effects:
1938 **		outputs some text to fp.
1939 */
1940 
1941 putfromline(fp, m, e)
1942 	register FILE *fp;
1943 	register MAILER *m;
1944 	ENVELOPE *e;
1945 {
1946 	char *template = "\201l\n";
1947 	char buf[MAXLINE];
1948 
1949 	if (bitnset(M_NHDR, m->m_flags))
1950 		return;
1951 
1952 # ifdef UGLYUUCP
1953 	if (bitnset(M_UGLYUUCP, m->m_flags))
1954 	{
1955 		char *bang;
1956 		char xbuf[MAXLINE];
1957 
1958 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1959 		bang = strchr(buf, '!');
1960 		if (bang == NULL)
1961 		{
1962 			errno = 0;
1963 			syserr("554 No ! in UUCP From address! (%s given)", buf);
1964 		}
1965 		else
1966 		{
1967 			*bang++ = '\0';
1968 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1969 			template = xbuf;
1970 		}
1971 	}
1972 # endif /* UGLYUUCP */
1973 	expand(template, buf, &buf[sizeof buf - 1], e);
1974 	putline(buf, fp, m);
1975 }
1976 /*
1977 **  PUTBODY -- put the body of a message.
1978 **
1979 **	Parameters:
1980 **		fp -- file to output onto.
1981 **		m -- a mailer descriptor to control output format.
1982 **		e -- the envelope to put out.
1983 **		separator -- if non-NULL, a message separator that must
1984 **			not be permitted in the resulting message.
1985 **
1986 **	Returns:
1987 **		none.
1988 **
1989 **	Side Effects:
1990 **		The message is written onto fp.
1991 */
1992 
1993 putbody(fp, m, e, separator)
1994 	FILE *fp;
1995 	MAILER *m;
1996 	register ENVELOPE *e;
1997 	char *separator;
1998 {
1999 	char buf[MAXLINE];
2000 
2001 	/*
2002 	**  Output the body of the message
2003 	*/
2004 
2005 	if (e->e_dfp == NULL)
2006 	{
2007 		if (e->e_df != NULL)
2008 		{
2009 			e->e_dfp = fopen(e->e_df, "r");
2010 			if (e->e_dfp == NULL)
2011 				syserr("putbody: Cannot open %s for %s from %s",
2012 				e->e_df, e->e_to, e->e_from.q_paddr);
2013 		}
2014 		else
2015 			putline("<<< No Message Collected >>>", fp, m);
2016 	}
2017 	if (e->e_dfp != NULL)
2018 	{
2019 		rewind(e->e_dfp);
2020 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
2021 		{
2022 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
2023 			    strncmp(buf, "From ", 5) == 0)
2024 				(void) putc('>', fp);
2025 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
2026 			{
2027 				/* possible separator */
2028 				int sl = strlen(separator);
2029 
2030 				if (strncmp(&buf[2], separator, sl) == 0)
2031 					(void) putc(' ', fp);
2032 			}
2033 			putline(buf, fp, m);
2034 		}
2035 
2036 		if (ferror(e->e_dfp))
2037 		{
2038 			syserr("putbody: %s: read error", e->e_df);
2039 			ExitStat = EX_IOERR;
2040 		}
2041 	}
2042 
2043 	/* some mailers want extra blank line at end of message */
2044 	if (bitnset(M_BLANKEND, m->m_flags) && buf[0] != '\0' && buf[0] != '\n')
2045 		putline("", fp, m);
2046 
2047 	(void) fflush(fp);
2048 	if (ferror(fp) && errno != EPIPE)
2049 	{
2050 		syserr("putbody: write error");
2051 		ExitStat = EX_IOERR;
2052 	}
2053 	errno = 0;
2054 }
2055 /*
2056 **  MAILFILE -- Send a message to a file.
2057 **
2058 **	If the file has the setuid/setgid bits set, but NO execute
2059 **	bits, sendmail will try to become the owner of that file
2060 **	rather than the real user.  Obviously, this only works if
2061 **	sendmail runs as root.
2062 **
2063 **	This could be done as a subordinate mailer, except that it
2064 **	is used implicitly to save messages in ~/dead.letter.  We
2065 **	view this as being sufficiently important as to include it
2066 **	here.  For example, if the system is dying, we shouldn't have
2067 **	to create another process plus some pipes to save the message.
2068 **
2069 **	Parameters:
2070 **		filename -- the name of the file to send to.
2071 **		ctladdr -- the controlling address header -- includes
2072 **			the userid/groupid to be when sending.
2073 **
2074 **	Returns:
2075 **		The exit code associated with the operation.
2076 **
2077 **	Side Effects:
2078 **		none.
2079 */
2080 
2081 mailfile(filename, ctladdr, e)
2082 	char *filename;
2083 	ADDRESS *ctladdr;
2084 	register ENVELOPE *e;
2085 {
2086 	register FILE *f;
2087 	register int pid;
2088 	int mode;
2089 
2090 	if (tTd(11, 1))
2091 	{
2092 		printf("mailfile %s\n  ctladdr=", filename);
2093 		printaddr(ctladdr, FALSE);
2094 	}
2095 
2096 	if (e->e_xfp != NULL)
2097 		fflush(e->e_xfp);
2098 
2099 	/*
2100 	**  Fork so we can change permissions here.
2101 	**	Note that we MUST use fork, not vfork, because of
2102 	**	the complications of calling subroutines, etc.
2103 	*/
2104 
2105 	DOFORK(fork);
2106 
2107 	if (pid < 0)
2108 		return (EX_OSERR);
2109 	else if (pid == 0)
2110 	{
2111 		/* child -- actually write to file */
2112 		struct stat stb;
2113 
2114 		(void) setsignal(SIGINT, SIG_DFL);
2115 		(void) setsignal(SIGHUP, SIG_DFL);
2116 		(void) setsignal(SIGTERM, SIG_DFL);
2117 		(void) umask(OldUmask);
2118 
2119 		if (stat(filename, &stb) < 0)
2120 			stb.st_mode = FileMode;
2121 		mode = stb.st_mode;
2122 
2123 		/* limit the errors to those actually caused in the child */
2124 		errno = 0;
2125 		ExitStat = EX_OK;
2126 
2127 		if (bitset(0111, stb.st_mode))
2128 			exit(EX_CANTCREAT);
2129 		if (ctladdr != NULL)
2130 		{
2131 			/* ignore setuid and setgid bits */
2132 			mode &= ~(S_ISGID|S_ISUID);
2133 		}
2134 
2135 		/* we have to open the dfile BEFORE setuid */
2136 		if (e->e_dfp == NULL && e->e_df != NULL)
2137 		{
2138 			e->e_dfp = fopen(e->e_df, "r");
2139 			if (e->e_dfp == NULL)
2140 			{
2141 				syserr("mailfile: Cannot open %s for %s from %s",
2142 					e->e_df, e->e_to, e->e_from.q_paddr);
2143 			}
2144 		}
2145 
2146 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
2147 		{
2148 			if (ctladdr == NULL || ctladdr->q_uid == 0)
2149 			{
2150 				(void) initgroups(DefUser, DefGid);
2151 			}
2152 			else
2153 			{
2154 				(void) initgroups(ctladdr->q_ruser ?
2155 					ctladdr->q_ruser : ctladdr->q_user,
2156 					ctladdr->q_gid);
2157 			}
2158 		}
2159 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
2160 		{
2161 			if (ctladdr == NULL || ctladdr->q_uid == 0)
2162 				(void) setuid(DefUid);
2163 			else
2164 				(void) setuid(ctladdr->q_uid);
2165 		}
2166 		FileName = filename;
2167 		LineNumber = 0;
2168 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
2169 		if (f == NULL)
2170 		{
2171 			message("554 cannot open: %s", errstring(errno));
2172 			exit(EX_CANTCREAT);
2173 		}
2174 
2175 		putfromline(f, FileMailer, e);
2176 		(*e->e_puthdr)(f, FileMailer, e);
2177 		putline("\n", f, FileMailer);
2178 		(*e->e_putbody)(f, FileMailer, e, NULL);
2179 		putline("\n", f, FileMailer);
2180 		if (ferror(f))
2181 		{
2182 			message("451 I/O error: %s", errstring(errno));
2183 			setstat(EX_IOERR);
2184 		}
2185 		(void) xfclose(f, "mailfile", filename);
2186 		(void) fflush(stdout);
2187 
2188 		/* reset ISUID & ISGID bits for paranoid systems */
2189 		(void) chmod(filename, (int) stb.st_mode);
2190 		exit(ExitStat);
2191 		/*NOTREACHED*/
2192 	}
2193 	else
2194 	{
2195 		/* parent -- wait for exit status */
2196 		int st;
2197 
2198 		st = waitfor(pid);
2199 		if (WIFEXITED(st))
2200 			return (WEXITSTATUS(st));
2201 		else
2202 		{
2203 			syserr("child died on signal %d", st);
2204 			return (EX_UNAVAILABLE);
2205 		}
2206 		/*NOTREACHED*/
2207 	}
2208 }
2209 /*
2210 **  HOSTSIGNATURE -- return the "signature" for a host.
2211 **
2212 **	The signature describes how we are going to send this -- it
2213 **	can be just the hostname (for non-Internet hosts) or can be
2214 **	an ordered list of MX hosts.
2215 **
2216 **	Parameters:
2217 **		m -- the mailer describing this host.
2218 **		host -- the host name.
2219 **		e -- the current envelope.
2220 **
2221 **	Returns:
2222 **		The signature for this host.
2223 **
2224 **	Side Effects:
2225 **		Can tweak the symbol table.
2226 */
2227 
2228 char *
2229 hostsignature(m, host, e)
2230 	register MAILER *m;
2231 	char *host;
2232 	ENVELOPE *e;
2233 {
2234 	register char *p;
2235 	register STAB *s;
2236 	int i;
2237 	int len;
2238 #ifdef NAMED_BIND
2239 	int nmx;
2240 	auto int rcode;
2241 	char *hp;
2242 	char *endp;
2243 	int oldoptions;
2244 	char *mxhosts[MAXMXHOSTS + 1];
2245 #endif
2246 
2247 	/*
2248 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2249 	*/
2250 
2251 	p = m->m_mailer;
2252 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2253 	{
2254 		/* just an ordinary mailer */
2255 		return host;
2256 	}
2257 
2258 	/*
2259 	**  Look it up in the symbol table.
2260 	*/
2261 
2262 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2263 	if (s->s_hostsig != NULL)
2264 		return s->s_hostsig;
2265 
2266 	/*
2267 	**  Not already there -- create a signature.
2268 	*/
2269 
2270 #ifdef NAMED_BIND
2271 	if (ConfigLevel < 2)
2272 	{
2273 		oldoptions = _res.options;
2274 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2275 	}
2276 
2277 	for (hp = host; hp != NULL; hp = endp)
2278 	{
2279 		endp = strchr(hp, ':');
2280 		if (endp != NULL)
2281 			*endp = '\0';
2282 
2283 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2284 
2285 		if (nmx <= 0)
2286 		{
2287 			register MCI *mci;
2288 
2289 			/* update the connection info for this host */
2290 			mci = mci_get(hp, m);
2291 			mci->mci_exitstat = rcode;
2292 			mci->mci_errno = errno;
2293 #ifdef NAMED_BIND
2294 			mci->mci_herrno = h_errno;
2295 #endif
2296 
2297 			/* and return the original host name as the signature */
2298 			nmx = 1;
2299 			mxhosts[0] = hp;
2300 		}
2301 
2302 		len = 0;
2303 		for (i = 0; i < nmx; i++)
2304 		{
2305 			len += strlen(mxhosts[i]) + 1;
2306 		}
2307 		if (s->s_hostsig != NULL)
2308 			len += strlen(s->s_hostsig) + 1;
2309 		p = xalloc(len);
2310 		if (s->s_hostsig != NULL)
2311 		{
2312 			(void) strcpy(p, s->s_hostsig);
2313 			free(s->s_hostsig);
2314 			s->s_hostsig = p;
2315 			p += strlen(p);
2316 			*p++ = ':';
2317 		}
2318 		else
2319 			s->s_hostsig = p;
2320 		for (i = 0; i < nmx; i++)
2321 		{
2322 			if (i != 0)
2323 				*p++ = ':';
2324 			strcpy(p, mxhosts[i]);
2325 			p += strlen(p);
2326 		}
2327 		if (endp != NULL)
2328 			*endp++ = ':';
2329 	}
2330 	makelower(s->s_hostsig);
2331 	if (ConfigLevel < 2)
2332 		_res.options = oldoptions;
2333 #else
2334 	/* not using BIND -- the signature is just the host name */
2335 	s->s_hostsig = host;
2336 #endif
2337 	if (tTd(17, 1))
2338 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2339 	return s->s_hostsig;
2340 }
2341