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