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