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