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