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