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