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.119 (Berkeley) 12/10/94";
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, 0);
1452 		(*e->e_putbody)(mci, e, NULL, 0);
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 = "550";
1631 		break;
1632 
1633 	  case EX_DATAERR:
1634 		stat = "501";
1635 		break;
1636 
1637 	  case EX_NOINPUT:
1638 	  case EX_NOUSER:
1639 	  case EX_NOHOST:
1640 	  case EX_CANTCREAT:
1641 	  case EX_NOPERM:
1642 		stat = "550";
1643 		break;
1644 
1645 	  case EX_UNAVAILABLE:
1646 	  case EX_SOFTWARE:
1647 	  case EX_OSFILE:
1648 	  case EX_PROTOCOL:
1649 	  case EX_CONFIG:
1650 		stat = "554";
1651 		break;
1652 
1653 	  case EX_OSERR:
1654 	  case EX_IOERR:
1655 		stat = "451";
1656 		break;
1657 
1658 	  case EX_TEMPFAIL:
1659 		stat = "426";
1660 		break;
1661 	}
1662 	if (stat != NULL && q->q_status == NULL)
1663 		q->q_status = stat;
1664 
1665 	q->q_statdate = curtime();
1666 	if (CurHostName != NULL && CurHostName[0] != '\0')
1667 		q->q_statmta = newstr(CurHostName);
1668 	if (rcode != EX_OK && q->q_rstatus == NULL)
1669 	{
1670 		char buf[30];
1671 
1672 		(void) sprintf(buf, "%d", rcode);
1673 		q->q_rstatus = newstr(buf);
1674 	}
1675 }
1676 /*
1677 **  ENDMAILER -- Wait for mailer to terminate.
1678 **
1679 **	We should never get fatal errors (e.g., segmentation
1680 **	violation), so we report those specially.  For other
1681 **	errors, we choose a status message (into statmsg),
1682 **	and if it represents an error, we print it.
1683 **
1684 **	Parameters:
1685 **		pid -- pid of mailer.
1686 **		e -- the current envelope.
1687 **		pv -- the parameter vector that invoked the mailer
1688 **			(for error messages).
1689 **
1690 **	Returns:
1691 **		exit code of mailer.
1692 **
1693 **	Side Effects:
1694 **		none.
1695 */
1696 
1697 endmailer(mci, e, pv)
1698 	register MCI *mci;
1699 	register ENVELOPE *e;
1700 	char **pv;
1701 {
1702 	int st;
1703 
1704 	/* close any connections */
1705 	if (mci->mci_in != NULL)
1706 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1707 	if (mci->mci_out != NULL)
1708 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1709 	mci->mci_in = mci->mci_out = NULL;
1710 	mci->mci_state = MCIS_CLOSED;
1711 
1712 	/* in the IPC case there is nothing to wait for */
1713 	if (mci->mci_pid == 0)
1714 		return (EX_OK);
1715 
1716 	/* wait for the mailer process to die and collect status */
1717 	st = waitfor(mci->mci_pid);
1718 	if (st == -1)
1719 	{
1720 		syserr("endmailer %s: wait", pv[0]);
1721 		return (EX_SOFTWARE);
1722 	}
1723 
1724 	if (WIFEXITED(st))
1725 	{
1726 		/* normal death -- return status */
1727 		return (WEXITSTATUS(st));
1728 	}
1729 
1730 	/* it died a horrid death */
1731 	syserr("451 mailer %s died with signal %o",
1732 		mci->mci_mailer->m_name, st);
1733 
1734 	/* log the arguments */
1735 	if (pv != NULL && e->e_xfp != NULL)
1736 	{
1737 		register char **av;
1738 
1739 		fprintf(e->e_xfp, "Arguments:");
1740 		for (av = pv; *av != NULL; av++)
1741 			fprintf(e->e_xfp, " %s", *av);
1742 		fprintf(e->e_xfp, "\n");
1743 	}
1744 
1745 	ExitStat = EX_TEMPFAIL;
1746 	return (EX_TEMPFAIL);
1747 }
1748 /*
1749 **  GIVERESPONSE -- Interpret an error response from a mailer
1750 **
1751 **	Parameters:
1752 **		stat -- the status code from the mailer (high byte
1753 **			only; core dumps must have been taken care of
1754 **			already).
1755 **		m -- the mailer info for this mailer.
1756 **		mci -- the mailer connection info -- can be NULL if the
1757 **			response is given before the connection is made.
1758 **		ctladdr -- the controlling address for the recipient
1759 **			address(es).
1760 **		xstart -- the transaction start time, for computing
1761 **			transaction delays.
1762 **		e -- the current envelope.
1763 **
1764 **	Returns:
1765 **		none.
1766 **
1767 **	Side Effects:
1768 **		Errors may be incremented.
1769 **		ExitStat may be set.
1770 */
1771 
1772 giveresponse(stat, m, mci, ctladdr, xstart, e)
1773 	int stat;
1774 	register MAILER *m;
1775 	register MCI *mci;
1776 	ADDRESS *ctladdr;
1777 	time_t xstart;
1778 	ENVELOPE *e;
1779 {
1780 	register const char *statmsg;
1781 	extern char *SysExMsg[];
1782 	register int i;
1783 	extern int N_SysEx;
1784 	char buf[MAXLINE];
1785 
1786 	/*
1787 	**  Compute status message from code.
1788 	*/
1789 
1790 	i = stat - EX__BASE;
1791 	if (stat == 0)
1792 	{
1793 		statmsg = "250 Sent";
1794 		if (e->e_statmsg != NULL)
1795 		{
1796 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1797 			statmsg = buf;
1798 		}
1799 	}
1800 	else if (i < 0 || i > N_SysEx)
1801 	{
1802 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1803 		stat = EX_UNAVAILABLE;
1804 		statmsg = buf;
1805 	}
1806 	else if (stat == EX_TEMPFAIL)
1807 	{
1808 		(void) strcpy(buf, SysExMsg[i] + 1);
1809 #if NAMED_BIND
1810 		if (h_errno == TRY_AGAIN)
1811 			statmsg = errstring(h_errno+E_DNSBASE);
1812 		else
1813 #endif
1814 		{
1815 			if (errno != 0)
1816 				statmsg = errstring(errno);
1817 			else
1818 			{
1819 #ifdef SMTP
1820 				statmsg = SmtpError;
1821 #else /* SMTP */
1822 				statmsg = NULL;
1823 #endif /* SMTP */
1824 			}
1825 		}
1826 		if (statmsg != NULL && statmsg[0] != '\0')
1827 		{
1828 			(void) strcat(buf, ": ");
1829 			(void) strcat(buf, statmsg);
1830 		}
1831 		statmsg = buf;
1832 	}
1833 #if NAMED_BIND
1834 	else if (stat == EX_NOHOST && h_errno != 0)
1835 	{
1836 		statmsg = errstring(h_errno + E_DNSBASE);
1837 		(void) sprintf(buf, "%s (%s)", SysExMsg[i] + 1, statmsg);
1838 		statmsg = buf;
1839 	}
1840 #endif
1841 	else
1842 	{
1843 		statmsg = SysExMsg[i];
1844 		if (*statmsg++ == ':')
1845 		{
1846 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1847 			statmsg = buf;
1848 		}
1849 	}
1850 
1851 	/*
1852 	**  Print the message as appropriate
1853 	*/
1854 
1855 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1856 	{
1857 		extern char MsgBuf[];
1858 
1859 		message("%s", &statmsg[4]);
1860 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1861 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1862 	}
1863 	else
1864 	{
1865 		char mbuf[8];
1866 
1867 		Errors++;
1868 		sprintf(mbuf, "%.3s %%s", statmsg);
1869 		usrerr(mbuf, &statmsg[4]);
1870 	}
1871 
1872 	/*
1873 	**  Final cleanup.
1874 	**	Log a record of the transaction.  Compute the new
1875 	**	ExitStat -- if we already had an error, stick with
1876 	**	that.
1877 	*/
1878 
1879 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1880 		logdelivery(m, mci, &statmsg[4], ctladdr, xstart, e);
1881 
1882 	if (tTd(11, 2))
1883 		printf("giveresponse: stat=%d, e->e_message=%s\n",
1884 			stat, e->e_message == NULL ? "<NULL>" : e->e_message);
1885 
1886 	if (stat != EX_TEMPFAIL)
1887 		setstat(stat);
1888 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1889 	{
1890 		if (e->e_message != NULL)
1891 			free(e->e_message);
1892 		e->e_message = newstr(&statmsg[4]);
1893 	}
1894 	errno = 0;
1895 #if NAMED_BIND
1896 	h_errno = 0;
1897 #endif
1898 }
1899 /*
1900 **  LOGDELIVERY -- log the delivery in the system log
1901 **
1902 **	Care is taken to avoid logging lines that are too long, because
1903 **	some versions of syslog have an unfortunate proclivity for core
1904 **	dumping.  This is a hack, to be sure, that is at best empirical.
1905 **
1906 **	Parameters:
1907 **		m -- the mailer info.  Can be NULL for initial queue.
1908 **		mci -- the mailer connection info -- can be NULL if the
1909 **			log is occuring when no connection is active.
1910 **		stat -- the message to print for the status.
1911 **		ctladdr -- the controlling address for the to list.
1912 **		xstart -- the transaction start time, used for
1913 **			computing transaction delay.
1914 **		e -- the current envelope.
1915 **
1916 **	Returns:
1917 **		none
1918 **
1919 **	Side Effects:
1920 **		none
1921 */
1922 
1923 logdelivery(m, mci, stat, ctladdr, xstart, e)
1924 	MAILER *m;
1925 	register MCI *mci;
1926 	char *stat;
1927 	ADDRESS *ctladdr;
1928 	time_t xstart;
1929 	register ENVELOPE *e;
1930 {
1931 # ifdef LOG
1932 	register char *bp;
1933 	register char *p;
1934 	int l;
1935 	char buf[512];
1936 
1937 #  if (SYSLOG_BUFSIZE) >= 256
1938 	bp = buf;
1939 	if (ctladdr != NULL)
1940 	{
1941 		strcpy(bp, ", ctladdr=");
1942 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
1943 		bp += strlen(bp);
1944 		if (bitset(QGOODUID, ctladdr->q_flags))
1945 		{
1946 			(void) sprintf(bp, " (%d/%d)",
1947 					ctladdr->q_uid, ctladdr->q_gid);
1948 			bp += strlen(bp);
1949 		}
1950 	}
1951 
1952 	sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1953 	bp += strlen(bp);
1954 
1955 	if (xstart != (time_t) 0)
1956 	{
1957 		sprintf(bp, ", xdelay=%s", pintvl(curtime() - xstart, TRUE));
1958 		bp += strlen(bp);
1959 	}
1960 
1961 	if (m != NULL)
1962 	{
1963 		(void) strcpy(bp, ", mailer=");
1964 		(void) strcat(bp, m->m_name);
1965 		bp += strlen(bp);
1966 	}
1967 
1968 	if (mci != NULL && mci->mci_host != NULL)
1969 	{
1970 # ifdef DAEMON
1971 		extern SOCKADDR CurHostAddr;
1972 # endif
1973 
1974 		(void) strcpy(bp, ", relay=");
1975 		(void) strcat(bp, mci->mci_host);
1976 
1977 # ifdef DAEMON
1978 		(void) strcat(bp, " [");
1979 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
1980 		(void) strcat(bp, "]");
1981 # endif
1982 	}
1983 	else if (strcmp(stat, "queued") != 0)
1984 	{
1985 		char *p = macvalue('h', e);
1986 
1987 		if (p != NULL && p[0] != '\0')
1988 		{
1989 			(void) strcpy(bp, ", relay=");
1990 			(void) strcat(bp, p);
1991 		}
1992 	}
1993 	bp += strlen(bp);
1994 
1995 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
1996 #if (STATLEN) < 63
1997 # undef STATLEN
1998 # define STATLEN	63
1999 #endif
2000 #if (STATLEN) > 203
2001 # undef STATLEN
2002 # define STATLEN	203
2003 #endif
2004 
2005 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
2006 	{
2007 		/* desperation move -- truncate data */
2008 		bp = buf + sizeof buf - ((STATLEN) + 17);
2009 		strcpy(bp, "...");
2010 		bp += 3;
2011 	}
2012 
2013 	(void) strcpy(bp, ", stat=");
2014 	bp += strlen(bp);
2015 
2016 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
2017 
2018 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
2019 	p = e->e_to;
2020 	while (strlen(p) >= l)
2021 	{
2022 		register char *q = strchr(p + l, ',');
2023 
2024 		if (q == NULL)
2025 			break;
2026 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
2027 			e->e_id, ++q - p, p, buf);
2028 		p = q;
2029 	}
2030 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
2031 
2032 #  else		/* we have a very short log buffer size */
2033 
2034 	l = SYSLOG_BUFSIZE - 85;
2035 	p = e->e_to;
2036 	while (strlen(p) >= l)
2037 	{
2038 		register char *q = strchr(p + l, ',');
2039 
2040 		if (q == NULL)
2041 			break;
2042 		syslog(LOG_INFO, "%s: to=%.*s [more]",
2043 			e->e_id, ++q - p, p);
2044 		p = q;
2045 	}
2046 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
2047 
2048 	if (ctladdr != NULL)
2049 	{
2050 		bp = buf;
2051 		strcpy(buf, "ctladdr=");
2052 		bp += strlen(buf);
2053 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
2054 		bp += strlen(buf);
2055 		if (bitset(QGOODUID, ctladdr->q_flags))
2056 		{
2057 			(void) sprintf(bp, " (%d/%d)",
2058 					ctladdr->q_uid, ctladdr->q_gid);
2059 			bp += strlen(bp);
2060 		}
2061 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2062 	}
2063 	bp = buf;
2064 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
2065 	bp += strlen(bp);
2066 	if (xstart != (time_t) 0)
2067 	{
2068 		sprintf(bp, ", xdelay=%s", pintvl(curtime() - xstart, TRUE));
2069 		bp += strlen(bp);
2070 	}
2071 
2072 	if (m != NULL)
2073 	{
2074 		sprintf(bp, ", mailer=%s", m->m_name);
2075 		bp += strlen(bp);
2076 	}
2077 	syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2078 
2079 	buf[0] = '\0';
2080 	if (mci != NULL && mci->mci_host != NULL)
2081 	{
2082 # ifdef DAEMON
2083 		extern SOCKADDR CurHostAddr;
2084 # endif
2085 
2086 		sprintf(buf, "relay=%s", mci->mci_host);
2087 
2088 # ifdef DAEMON
2089 		(void) strcat(buf, " [");
2090 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
2091 		(void) strcat(buf, "]");
2092 # endif
2093 	}
2094 	else if (strcmp(stat, "queued") != 0)
2095 	{
2096 		char *p = macvalue('h', e);
2097 
2098 		if (p != NULL && p[0] != '\0')
2099 			sprintf(buf, "relay=%s", p);
2100 	}
2101 	if (buf[0] != '\0')
2102 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2103 
2104 	syslog(LOG_INFO, "%s: stat=%s", e->e_id, shortenstring(stat, 63));
2105 #  endif /* short log buffer */
2106 # endif /* LOG */
2107 }
2108 /*
2109 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
2110 **
2111 **	This can be made an arbitrary message separator by changing $l
2112 **
2113 **	One of the ugliest hacks seen by human eyes is contained herein:
2114 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
2115 **	does a well-meaning programmer such as myself have to deal with
2116 **	this kind of antique garbage????
2117 **
2118 **	Parameters:
2119 **		mci -- the connection information.
2120 **		e -- the envelope.
2121 **
2122 **	Returns:
2123 **		none
2124 **
2125 **	Side Effects:
2126 **		outputs some text to fp.
2127 */
2128 
2129 putfromline(mci, e)
2130 	register MCI *mci;
2131 	ENVELOPE *e;
2132 {
2133 	char *template = "\201l\n";
2134 	char buf[MAXLINE];
2135 
2136 	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
2137 		return;
2138 
2139 # ifdef UGLYUUCP
2140 	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
2141 	{
2142 		char *bang;
2143 		char xbuf[MAXLINE];
2144 
2145 		expand("\201g", buf, &buf[sizeof buf - 1], e);
2146 		bang = strchr(buf, '!');
2147 		if (bang == NULL)
2148 		{
2149 			errno = 0;
2150 			syserr("554 No ! in UUCP From address! (%s given)", buf);
2151 		}
2152 		else
2153 		{
2154 			*bang++ = '\0';
2155 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
2156 			template = xbuf;
2157 		}
2158 	}
2159 # endif /* UGLYUUCP */
2160 	expand(template, buf, &buf[sizeof buf - 1], e);
2161 	putline(buf, mci);
2162 }
2163 /*
2164 **  PUTBODY -- put the body of a message.
2165 **
2166 **	Parameters:
2167 **		mci -- the connection information.
2168 **		e -- the envelope to put out.
2169 **		separator -- if non-NULL, a message separator that must
2170 **			not be permitted in the resulting message.
2171 **		flags -- to modify the behaviour.
2172 **
2173 **	Returns:
2174 **		none.
2175 **
2176 **	Side Effects:
2177 **		The message is written onto fp.
2178 */
2179 
2180 /* values for output state variable */
2181 #define OS_HEAD		0	/* at beginning of line */
2182 #define OS_CR		1	/* read a carriage return */
2183 #define OS_INLINE	2	/* putting rest of line */
2184 
2185 putbody(mci, e, separator, flags)
2186 	register MCI *mci;
2187 	register ENVELOPE *e;
2188 	char *separator;
2189 	int flags;
2190 {
2191 	char buf[MAXLINE];
2192 
2193 	/*
2194 	**  Output the body of the message
2195 	*/
2196 
2197 	if (e->e_dfp == NULL && e->e_df != NULL)
2198 	{
2199 		e->e_dfp = fopen(e->e_df, "r");
2200 		if (e->e_dfp == NULL)
2201 			syserr("putbody: Cannot open %s for %s from %s",
2202 			e->e_df, e->e_to, e->e_from.q_paddr);
2203 	}
2204 	if (e->e_dfp == NULL)
2205 	{
2206 		if (bitset(MCIF_INHEADER, mci->mci_flags))
2207 		{
2208 			putline("", mci);
2209 			mci->mci_flags &= ~MCIF_INHEADER;
2210 		}
2211 		putline("<<< No Message Collected >>>", mci);
2212 		goto endofmessage;
2213 	}
2214 	if (e->e_dfino == (ino_t) 0)
2215 	{
2216 		struct stat stbuf;
2217 
2218 		if (fstat(fileno(e->e_dfp), &stbuf) < 0)
2219 			e->e_dfino = -1;
2220 		else
2221 		{
2222 			e->e_dfdev = stbuf.st_dev;
2223 			e->e_dfino = stbuf.st_ino;
2224 		}
2225 	}
2226 	rewind(e->e_dfp);
2227 
2228 	if (bitset(MCIF_CVT8TO7, mci->mci_flags))
2229 	{
2230 		/*
2231 		**  Do 8 to 7 bit MIME conversion.
2232 		*/
2233 
2234 		/* make sure it looks like a MIME message */
2235 		if (hvalue("MIME-Version", e->e_header) == NULL)
2236 			putline("MIME-Version: 1.0", mci);
2237 
2238 		if (hvalue("Content-Type", e->e_header) == NULL)
2239 		{
2240 			sprintf(buf, "Content-Type: text/plain; charset=%s",
2241 				defcharset(e));
2242 			putline(buf, mci);
2243 		}
2244 
2245 		/* now do the hard work */
2246 		mime8to7(mci, e->e_header, e, NULL);
2247 	}
2248 	else
2249 	{
2250 		int ostate;
2251 		register char *bp;
2252 		register char *pbp;
2253 		register int c;
2254 		int padc;
2255 		char *buflim;
2256 		int pos;
2257 		char peekbuf[10];
2258 
2259 		/* we can pass it through unmodified */
2260 		if (bitset(MCIF_INHEADER, mci->mci_flags))
2261 		{
2262 			putline("", mci);
2263 			mci->mci_flags &= ~MCIF_INHEADER;
2264 		}
2265 
2266 		/* determine end of buffer; allow for short mailer lines */
2267 		buflim = &buf[sizeof buf - 1];
2268 		if (mci->mci_mailer->m_linelimit > 0 &&
2269 		    mci->mci_mailer->m_linelimit < sizeof buf - 1)
2270 			buflim = &buf[mci->mci_mailer->m_linelimit - 1];
2271 
2272 		/* copy temp file to output with mapping */
2273 		ostate = OS_HEAD;
2274 		bp = buf;
2275 		pbp = peekbuf;
2276 		while (!ferror(mci->mci_out))
2277 		{
2278 			register char *xp;
2279 
2280 			if (pbp > peekbuf)
2281 				c = *--pbp;
2282 			else if ((c = fgetc(e->e_dfp)) == EOF)
2283 				break;
2284 			if (bitset(MCIF_7BIT, mci->mci_flags))
2285 				c &= 0x7f;
2286 			switch (ostate)
2287 			{
2288 			  case OS_HEAD:
2289 				if (c != '\r' && c != '\n' && bp < buflim)
2290 				{
2291 					*bp++ = c;
2292 					break;
2293 				}
2294 
2295 				/* check beginning of line for special cases */
2296 				*bp = '\0';
2297 				pos = 0;
2298 				padc = EOF;
2299 				if (buf[0] == 'F' &&
2300 				    bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
2301 				    strncmp(buf, "From ", 5) == 0)
2302 				{
2303 					padc = '>';
2304 				}
2305 				if (buf[0] == '-' && buf[1] == '-' &&
2306 				    separator != NULL)
2307 				{
2308 					/* possible separator */
2309 					int sl = strlen(separator);
2310 
2311 					if (strncmp(&buf[2], separator, sl) == 0)
2312 						padc = ' ';
2313 				}
2314 				if (buf[0] == '.' &&
2315 				    bitnset(M_XDOT, mci->mci_mailer->m_flags))
2316 				{
2317 					padc = '.';
2318 				}
2319 
2320 				/* now copy out saved line */
2321 				if (TrafficLogFile != NULL)
2322 				{
2323 					fprintf(TrafficLogFile, "%05d >>> ", getpid());
2324 					if (padc != EOF)
2325 						fputc(padc, TrafficLogFile);
2326 					for (xp = buf; xp < bp; xp++)
2327 						fputc(*xp, TrafficLogFile);
2328 					if (c == '\n')
2329 						fputs(mci->mci_mailer->m_eol,
2330 						      TrafficLogFile);
2331 				}
2332 				if (padc != EOF)
2333 				{
2334 					fputc(padc, mci->mci_out);
2335 					pos++;
2336 				}
2337 				for (xp = buf; xp < bp; xp++)
2338 					fputc(*xp, mci->mci_out);
2339 				if (c == '\n')
2340 				{
2341 					fputs(mci->mci_mailer->m_eol,
2342 					      mci->mci_out);
2343 					pos = 0;
2344 				}
2345 				else
2346 				{
2347 					pos += bp - buf;
2348 					if (c != '\r')
2349 						*pbp++ = c;
2350 				}
2351 				bp = buf;
2352 
2353 				/* determine next state */
2354 				if (c == '\n')
2355 					ostate = OS_HEAD;
2356 				else if (c == '\r')
2357 					ostate = OS_CR;
2358 				else
2359 					ostate = OS_INLINE;
2360 				continue;
2361 
2362 			  case OS_CR:
2363 				if (c == '\n')
2364 				{
2365 					/* got CRLF */
2366 					fputs(mci->mci_mailer->m_eol, mci->mci_out);
2367 					if (TrafficLogFile != NULL)
2368 					{
2369 						fputs(mci->mci_mailer->m_eol,
2370 						      TrafficLogFile);
2371 					}
2372 					ostate = OS_HEAD;
2373 					continue;
2374 				}
2375 
2376 				/* had a naked carriage return */
2377 				*pbp++ = c;
2378 				c = '\r';
2379 				goto putch;
2380 
2381 			  case OS_INLINE:
2382 				if (c == '\r')
2383 				{
2384 					ostate = OS_CR;
2385 					continue;
2386 				}
2387 putch:
2388 				if (mci->mci_mailer->m_linelimit > 0 &&
2389 				    pos > mci->mci_mailer->m_linelimit &&
2390 				    c != '\n')
2391 				{
2392 					putc('!', mci->mci_out);
2393 					fputs(mci->mci_mailer->m_eol, mci->mci_out);
2394 					if (TrafficLogFile != NULL)
2395 					{
2396 						fprintf(TrafficLogFile, "!%s",
2397 							mci->mci_mailer->m_eol);
2398 					}
2399 					ostate = OS_HEAD;
2400 					*pbp++ = c;
2401 					continue;
2402 				}
2403 				if (TrafficLogFile != NULL)
2404 					fputc(c, TrafficLogFile);
2405 				putc(c, mci->mci_out);
2406 				pos++;
2407 				ostate = c == '\n' ? OS_HEAD : OS_INLINE;
2408 				break;
2409 			}
2410 		}
2411 	}
2412 
2413 	if (ferror(e->e_dfp))
2414 	{
2415 		syserr("putbody: %s: read error", e->e_df);
2416 		ExitStat = EX_IOERR;
2417 	}
2418 
2419 endofmessage:
2420 	/* some mailers want extra blank line at end of message */
2421 	if (bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
2422 	    buf[0] != '\0' && buf[0] != '\n')
2423 		putline("", mci);
2424 
2425 	(void) fflush(mci->mci_out);
2426 	if (ferror(mci->mci_out) && errno != EPIPE)
2427 	{
2428 		syserr("putbody: write error");
2429 		ExitStat = EX_IOERR;
2430 	}
2431 	errno = 0;
2432 }
2433 /*
2434 **  MAILFILE -- Send a message to a file.
2435 **
2436 **	If the file has the setuid/setgid bits set, but NO execute
2437 **	bits, sendmail will try to become the owner of that file
2438 **	rather than the real user.  Obviously, this only works if
2439 **	sendmail runs as root.
2440 **
2441 **	This could be done as a subordinate mailer, except that it
2442 **	is used implicitly to save messages in ~/dead.letter.  We
2443 **	view this as being sufficiently important as to include it
2444 **	here.  For example, if the system is dying, we shouldn't have
2445 **	to create another process plus some pipes to save the message.
2446 **
2447 **	Parameters:
2448 **		filename -- the name of the file to send to.
2449 **		ctladdr -- the controlling address header -- includes
2450 **			the userid/groupid to be when sending.
2451 **
2452 **	Returns:
2453 **		The exit code associated with the operation.
2454 **
2455 **	Side Effects:
2456 **		none.
2457 */
2458 
2459 mailfile(filename, ctladdr, e)
2460 	char *filename;
2461 	ADDRESS *ctladdr;
2462 	register ENVELOPE *e;
2463 {
2464 	register FILE *f;
2465 	register int pid;
2466 	int mode;
2467 
2468 	if (tTd(11, 1))
2469 	{
2470 		printf("mailfile %s\n  ctladdr=", filename);
2471 		printaddr(ctladdr, FALSE);
2472 	}
2473 
2474 	if (e->e_xfp != NULL)
2475 		fflush(e->e_xfp);
2476 
2477 	/*
2478 	**  Fork so we can change permissions here.
2479 	**	Note that we MUST use fork, not vfork, because of
2480 	**	the complications of calling subroutines, etc.
2481 	*/
2482 
2483 	DOFORK(fork);
2484 
2485 	if (pid < 0)
2486 		return (EX_OSERR);
2487 	else if (pid == 0)
2488 	{
2489 		/* child -- actually write to file */
2490 		struct stat stb;
2491 		MCI mcibuf;
2492 
2493 		(void) setsignal(SIGINT, SIG_DFL);
2494 		(void) setsignal(SIGHUP, SIG_DFL);
2495 		(void) setsignal(SIGTERM, SIG_DFL);
2496 		(void) umask(OldUmask);
2497 
2498 		if (stat(filename, &stb) < 0)
2499 			stb.st_mode = FileMode;
2500 		mode = stb.st_mode;
2501 
2502 		/* limit the errors to those actually caused in the child */
2503 		errno = 0;
2504 		ExitStat = EX_OK;
2505 
2506 		if (bitset(0111, stb.st_mode))
2507 			exit(EX_CANTCREAT);
2508 		if (ctladdr != NULL)
2509 		{
2510 			/* ignore setuid and setgid bits */
2511 			mode &= ~(S_ISGID|S_ISUID);
2512 		}
2513 
2514 		/* we have to open the dfile BEFORE setuid */
2515 		if (e->e_dfp == NULL && e->e_df != NULL)
2516 		{
2517 			e->e_dfp = fopen(e->e_df, "r");
2518 			if (e->e_dfp == NULL)
2519 			{
2520 				syserr("mailfile: Cannot open %s for %s from %s",
2521 					e->e_df, e->e_to, e->e_from.q_paddr);
2522 			}
2523 		}
2524 
2525 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
2526 		{
2527 			if (ctladdr != NULL && ctladdr->q_uid != 0)
2528 				(void) initgroups(ctladdr->q_ruser ?
2529 					ctladdr->q_ruser : ctladdr->q_user,
2530 					ctladdr->q_gid);
2531 			else if (FileMailer != NULL && FileMailer->m_gid != 0)
2532 				(void) initgroups(DefUser, FileMailer->m_gid);
2533 			else
2534 				(void) initgroups(DefUser, DefGid);
2535 		}
2536 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
2537 		{
2538 			if (ctladdr != NULL && ctladdr->q_uid != 0)
2539 				(void) setuid(ctladdr->q_uid);
2540 			else if (FileMailer != NULL && FileMailer->m_uid != 0)
2541 				(void) setuid(FileMailer->m_uid);
2542 			else
2543 				(void) setuid(DefUid);
2544 		}
2545 		FileName = filename;
2546 		LineNumber = 0;
2547 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
2548 		if (f == NULL)
2549 		{
2550 			message("554 cannot open: %s", errstring(errno));
2551 			exit(EX_CANTCREAT);
2552 		}
2553 
2554 		bzero(&mcibuf, sizeof mcibuf);
2555 		mcibuf.mci_mailer = FileMailer;
2556 		mcibuf.mci_out = f;
2557 		if (bitnset(M_7BITS, FileMailer->m_flags))
2558 			mcibuf.mci_flags |= MCIF_7BIT;
2559 
2560 		putfromline(&mcibuf, e);
2561 		(*e->e_puthdr)(&mcibuf, e->e_header, e, 0);
2562 		(*e->e_putbody)(&mcibuf, e, NULL, 0);
2563 		putline("\n", &mcibuf);
2564 		if (ferror(f))
2565 		{
2566 			message("451 I/O error: %s", errstring(errno));
2567 			setstat(EX_IOERR);
2568 		}
2569 		(void) xfclose(f, "mailfile", filename);
2570 		(void) fflush(stdout);
2571 
2572 		/* reset ISUID & ISGID bits for paranoid systems */
2573 		(void) chmod(filename, (int) stb.st_mode);
2574 		exit(ExitStat);
2575 		/*NOTREACHED*/
2576 	}
2577 	else
2578 	{
2579 		/* parent -- wait for exit status */
2580 		int st;
2581 
2582 		st = waitfor(pid);
2583 		if (WIFEXITED(st))
2584 			return (WEXITSTATUS(st));
2585 		else
2586 		{
2587 			syserr("child died on signal %d", st);
2588 			return (EX_UNAVAILABLE);
2589 		}
2590 		/*NOTREACHED*/
2591 	}
2592 }
2593 /*
2594 **  HOSTSIGNATURE -- return the "signature" for a host.
2595 **
2596 **	The signature describes how we are going to send this -- it
2597 **	can be just the hostname (for non-Internet hosts) or can be
2598 **	an ordered list of MX hosts.
2599 **
2600 **	Parameters:
2601 **		m -- the mailer describing this host.
2602 **		host -- the host name.
2603 **		e -- the current envelope.
2604 **
2605 **	Returns:
2606 **		The signature for this host.
2607 **
2608 **	Side Effects:
2609 **		Can tweak the symbol table.
2610 */
2611 
2612 char *
2613 hostsignature(m, host, e)
2614 	register MAILER *m;
2615 	char *host;
2616 	ENVELOPE *e;
2617 {
2618 	register char *p;
2619 	register STAB *s;
2620 	int i;
2621 	int len;
2622 #if NAMED_BIND
2623 	int nmx;
2624 	auto int rcode;
2625 	char *hp;
2626 	char *endp;
2627 	int oldoptions;
2628 	char *mxhosts[MAXMXHOSTS + 1];
2629 #endif
2630 
2631 	/*
2632 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2633 	*/
2634 
2635 	p = m->m_mailer;
2636 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2637 	{
2638 		/* just an ordinary mailer */
2639 		return host;
2640 	}
2641 
2642 	/*
2643 	**  Look it up in the symbol table.
2644 	*/
2645 
2646 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2647 	if (s->s_hostsig != NULL)
2648 		return s->s_hostsig;
2649 
2650 	/*
2651 	**  Not already there -- create a signature.
2652 	*/
2653 
2654 #if NAMED_BIND
2655 	if (ConfigLevel < 2)
2656 	{
2657 		oldoptions = _res.options;
2658 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2659 	}
2660 
2661 	for (hp = host; hp != NULL; hp = endp)
2662 	{
2663 		endp = strchr(hp, ':');
2664 		if (endp != NULL)
2665 			*endp = '\0';
2666 
2667 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2668 
2669 		if (nmx <= 0)
2670 		{
2671 			register MCI *mci;
2672 
2673 			/* update the connection info for this host */
2674 			mci = mci_get(hp, m);
2675 			mci->mci_exitstat = rcode;
2676 			mci->mci_errno = errno;
2677 #if NAMED_BIND
2678 			mci->mci_herrno = h_errno;
2679 #endif
2680 
2681 			/* and return the original host name as the signature */
2682 			nmx = 1;
2683 			mxhosts[0] = hp;
2684 		}
2685 
2686 		len = 0;
2687 		for (i = 0; i < nmx; i++)
2688 		{
2689 			len += strlen(mxhosts[i]) + 1;
2690 		}
2691 		if (s->s_hostsig != NULL)
2692 			len += strlen(s->s_hostsig) + 1;
2693 		p = xalloc(len);
2694 		if (s->s_hostsig != NULL)
2695 		{
2696 			(void) strcpy(p, s->s_hostsig);
2697 			free(s->s_hostsig);
2698 			s->s_hostsig = p;
2699 			p += strlen(p);
2700 			*p++ = ':';
2701 		}
2702 		else
2703 			s->s_hostsig = p;
2704 		for (i = 0; i < nmx; i++)
2705 		{
2706 			if (i != 0)
2707 				*p++ = ':';
2708 			strcpy(p, mxhosts[i]);
2709 			p += strlen(p);
2710 		}
2711 		if (endp != NULL)
2712 			*endp++ = ':';
2713 	}
2714 	makelower(s->s_hostsig);
2715 	if (ConfigLevel < 2)
2716 		_res.options = oldoptions;
2717 #else
2718 	/* not using BIND -- the signature is just the host name */
2719 	s->s_hostsig = host;
2720 #endif
2721 	if (tTd(17, 1))
2722 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2723 	return s->s_hostsig;
2724 }
2725 /*
2726 **  SETSTATUS -- set the address status for return messages
2727 **
2728 **	Parameters:
2729 **		a -- the address to set.
2730 **		msg -- the text of the message, which must be in standard
2731 **			SMTP form (3 digits, a space, and a message).
2732 **
2733 **	Returns:
2734 **		none.
2735 */
2736 
2737 setstatus(a, msg)
2738 	register ADDRESS *a;
2739 	char *msg;
2740 {
2741 	char buf[MAXLINE];
2742 
2743 	if (a->q_rstatus != NULL)
2744 		free(a->q_rstatus);
2745 	if (strlen(msg) > 4)
2746 	{
2747 		register char *p, *q;
2748 		int parenlev = 0;
2749 
2750 		strncpy(buf, msg, 4);
2751 		p = &buf[4];
2752 		*p++ = '(';
2753 		for (q = &msg[4]; *q != '\0'; q++)
2754 		{
2755 			switch (*q)
2756 			{
2757 			  case '(':
2758 				parenlev++;
2759 				break;
2760 
2761 			  case ')':
2762 				if (parenlev > 0)
2763 					parenlev--;
2764 				else
2765 					*p++ = '\\';
2766 				break;
2767 			}
2768 			*p++ = *q;
2769 		}
2770 		while (parenlev-- >= 0)
2771 			*p++ = ')';
2772 		*p++ = '\0';
2773 		msg = buf;
2774 	}
2775 	a->q_rstatus = newstr(msg);
2776 }
2777