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