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