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