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