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