1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)deliver.c	6.78 (Berkeley) 05/21/93";
11 #endif /* not lint */
12 
13 #include "sendmail.h"
14 #include <signal.h>
15 #include <netdb.h>
16 #include <errno.h>
17 #ifdef NAMED_BIND
18 #include <arpa/nameser.h>
19 #include <resolv.h>
20 #endif
21 
22 /*
23 **  SENDALL -- actually send all the messages.
24 **
25 **	Parameters:
26 **		e -- the envelope to send.
27 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
28 **			the current e->e_sendmode.
29 **
30 **	Returns:
31 **		none.
32 **
33 **	Side Effects:
34 **		Scans the send lists and sends everything it finds.
35 **		Delivers any appropriate error messages.
36 **		If we are running in a non-interactive mode, takes the
37 **			appropriate action.
38 */
39 
40 sendall(e, mode)
41 	ENVELOPE *e;
42 	char mode;
43 {
44 	register ADDRESS *q;
45 	char *owner;
46 	int otherowners;
47 	register ENVELOPE *ee;
48 	ENVELOPE *splitenv = NULL;
49 	bool announcequeueup;
50 
51 	/* determine actual delivery mode */
52 	if (mode == SM_DEFAULT)
53 	{
54 		extern bool shouldqueue();
55 
56 		mode = e->e_sendmode;
57 		if (mode != SM_VERIFY &&
58 		    shouldqueue(e->e_msgpriority, e->e_ctime))
59 			mode = SM_QUEUE;
60 		announcequeueup = mode == SM_QUEUE;
61 	}
62 	else
63 		announcequeueup = FALSE;
64 
65 	if (tTd(13, 1))
66 	{
67 		printf("\nSENDALL: mode %c, e_from ", mode);
68 		printaddr(&e->e_from, FALSE);
69 		printf("sendqueue:\n");
70 		printaddr(e->e_sendqueue, TRUE);
71 	}
72 
73 	/*
74 	**  Do any preprocessing necessary for the mode we are running.
75 	**	Check to make sure the hop count is reasonable.
76 	**	Delete sends to the sender in mailing lists.
77 	*/
78 
79 	CurEnv = e;
80 
81 	if (e->e_hopcount > MaxHopCount)
82 	{
83 		errno = 0;
84 		syserr("554 too many hops %d (%d max): from %s, to %s",
85 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
86 			e->e_sendqueue->q_paddr);
87 		return;
88 	}
89 
90 	/*
91 	**  Do sender deletion.
92 	**
93 	**	If the sender has the QQUEUEUP flag set, skip this.
94 	**	This can happen if the name server is hosed when you
95 	**	are trying to send mail.  The result is that the sender
96 	**	is instantiated in the queue as a recipient.
97 	*/
98 
99 	if (!MeToo && !bitset(QQUEUEUP, e->e_from.q_flags))
100 	{
101 		extern ADDRESS *recipient();
102 
103 		if (tTd(13, 5))
104 		{
105 			printf("sendall: QDONTSEND ");
106 			printaddr(&e->e_from, FALSE);
107 		}
108 		e->e_from.q_flags |= QDONTSEND;
109 		(void) recipient(&e->e_from, &e->e_sendqueue, e);
110 	}
111 
112 	/*
113 	**  Handle alias owners.
114 	**
115 	**	We scan up the q_alias chain looking for owners.
116 	**	We discard owners that are the same as the return path.
117 	*/
118 
119 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
120 	{
121 		register struct address *a;
122 
123 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
124 			continue;
125 		if (a != NULL)
126 			q->q_owner = a->q_owner;
127 
128 		if (q->q_owner != NULL &&
129 		    !bitset(QDONTSEND, q->q_flags) &&
130 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
131 			q->q_owner = NULL;
132 	}
133 
134 	owner = "";
135 	otherowners = 1;
136 	while (owner != NULL && otherowners > 0)
137 	{
138 		owner = NULL;
139 		otherowners = 0;
140 
141 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
142 		{
143 			if (bitset(QDONTSEND, q->q_flags))
144 				continue;
145 
146 			if (q->q_owner != NULL)
147 			{
148 				if (owner == NULL)
149 					owner = q->q_owner;
150 				else if (owner != q->q_owner)
151 				{
152 					if (strcmp(owner, q->q_owner) == 0)
153 					{
154 						/* make future comparisons cheap */
155 						q->q_owner = owner;
156 					}
157 					else
158 					{
159 						otherowners++;
160 					}
161 					owner = q->q_owner;
162 				}
163 			}
164 			else
165 			{
166 				otherowners++;
167 			}
168 		}
169 
170 		if (owner != NULL && otherowners > 0)
171 		{
172 			extern HDR *copyheader();
173 			extern ADDRESS *copyqueue();
174 
175 			/*
176 			**  Split this envelope into two.
177 			*/
178 
179 			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
180 			*ee = *e;
181 			ee->e_id = NULL;
182 			(void) queuename(ee, '\0');
183 
184 			if (tTd(13, 1))
185 				printf("sendall: split %s into %s\n",
186 					e->e_id, ee->e_id);
187 
188 			ee->e_header = copyheader(e->e_header);
189 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
190 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
191 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS);
192 			setsender(owner, ee, NULL, TRUE);
193 			if (tTd(13, 5))
194 			{
195 				printf("sendall(split): QDONTSEND ");
196 				printaddr(&ee->e_from, FALSE);
197 			}
198 			ee->e_from.q_flags |= QDONTSEND;
199 			ee->e_dfp = NULL;
200 			ee->e_xfp = NULL;
201 			ee->e_lockfp = NULL;
202 			ee->e_df = NULL;
203 			ee->e_errormode = EM_MAIL;
204 			ee->e_sibling = splitenv;
205 			splitenv = ee;
206 
207 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
208 				if (q->q_owner == owner)
209 					q->q_flags |= QDONTSEND;
210 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
211 				if (q->q_owner != owner)
212 					q->q_flags |= QDONTSEND;
213 
214 			if (e->e_df != NULL && mode != SM_VERIFY)
215 			{
216 				ee->e_dfp = NULL;
217 				ee->e_df = newstr(queuename(ee, 'd'));
218 				if (link(e->e_df, ee->e_df) < 0)
219 				{
220 					syserr("sendall: link(%s, %s)",
221 						e->e_df, ee->e_df);
222 				}
223 			}
224 
225 			if (mode != SM_VERIFY)
226 				openxscript(ee);
227 #ifdef LOG
228 			if (LogLevel > 4)
229 				syslog(LOG_INFO, "%s: clone %s",
230 					ee->e_id, e->e_id);
231 #endif
232 		}
233 	}
234 
235 	if (owner != NULL)
236 	{
237 		setsender(owner, e, NULL, TRUE);
238 		if (tTd(13, 5))
239 		{
240 			printf("sendall(owner): QDONTSEND ");
241 			printaddr(&e->e_from, FALSE);
242 		}
243 		e->e_from.q_flags |= QDONTSEND;
244 		e->e_errormode = EM_MAIL;
245 	}
246 
247 # ifdef QUEUE
248 	if ((mode == SM_QUEUE || mode == SM_FORK ||
249 	     (mode != SM_VERIFY && SuperSafe)) &&
250 	    !bitset(EF_INQUEUE, e->e_flags))
251 	{
252 		/* be sure everything is instantiated in the queue */
253 		queueup(e, TRUE, announcequeueup);
254 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
255 			queueup(ee, TRUE, announcequeueup);
256 	}
257 #endif /* QUEUE */
258 
259 	if (splitenv != NULL)
260 	{
261 		if (tTd(13, 1))
262 		{
263 			printf("\nsendall: Split queue; remaining queue:\n");
264 			printaddr(e->e_sendqueue, TRUE);
265 		}
266 
267 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
268 		{
269 			CurEnv = ee;
270 			sendenvelope(ee, mode);
271 		}
272 
273 		CurEnv = e;
274 	}
275 	sendenvelope(e, mode);
276 
277 	for (; splitenv != NULL; splitenv = splitenv->e_sibling)
278 		dropenvelope(splitenv);
279 }
280 
281 sendenvelope(e, mode)
282 	register ENVELOPE *e;
283 	char mode;
284 {
285 	bool oldverbose;
286 	int pid;
287 	register ADDRESS *q;
288 #ifdef LOCKF
289 	struct flock lfd;
290 #endif
291 
292 	oldverbose = Verbose;
293 	switch (mode)
294 	{
295 	  case SM_VERIFY:
296 		Verbose = TRUE;
297 		break;
298 
299 	  case SM_QUEUE:
300   queueonly:
301 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
302 		return;
303 
304 	  case SM_FORK:
305 		if (e->e_xfp != NULL)
306 			(void) fflush(e->e_xfp);
307 
308 # ifdef LOCKF
309 		/*
310 		**  Since lockf has the interesting semantic that the
311 		**  lock is lost when we fork, we have to risk losing
312 		**  the lock here by closing before the fork, and then
313 		**  trying to get it back in the child.
314 		*/
315 
316 		if (e->e_lockfp != NULL)
317 		{
318 			(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
319 			e->e_lockfp = NULL;
320 		}
321 # endif /* LOCKF */
322 
323 		pid = fork();
324 		if (pid < 0)
325 		{
326 			goto queueonly;
327 		}
328 		else if (pid > 0)
329 		{
330 			/* be sure we leave the temp files to our child */
331 			e->e_id = e->e_df = NULL;
332 # ifndef LOCKF
333 			if (e->e_lockfp != NULL)
334 			{
335 				(void) xfclose(e->e_lockfp, "sendenvelope", "lockfp");
336 				e->e_lockfp = NULL;
337 			}
338 # endif
339 
340 			/* close any random open files in the envelope */
341 			if (e->e_dfp != NULL)
342 			{
343 				(void) xfclose(e->e_dfp, "sendenvelope", "dfp");
344 				e->e_dfp = NULL;
345 			}
346 			if (e->e_xfp != NULL)
347 			{
348 				(void) xfclose(e->e_xfp, "sendenvelope", "xfp");
349 				e->e_xfp = NULL;
350 			}
351 			return;
352 		}
353 
354 		/* double fork to avoid zombies */
355 		if (fork() > 0)
356 			exit(EX_OK);
357 
358 		/* be sure we are immune from the terminal */
359 		disconnect(FALSE, e);
360 
361 # ifdef LOCKF
362 		/*
363 		**  Now try to get our lock back.
364 		*/
365 
366 		lfd.l_type = F_WRLCK;
367 		lfd.l_whence = lfd.l_start = lfd.l_len = 0;
368 		e->e_lockfp = fopen(queuename(e, 'q'), "r+");
369 		if (e->e_lockfp == NULL ||
370 		    fcntl(fileno(e->e_lockfp), F_SETLK, &lfd) < 0)
371 		{
372 			/* oops....  lost it */
373 			if (tTd(13, 1))
374 				printf("sendenvelope: %s lost lock: lockfp=%x, %s\n",
375 					e->e_id, e->e_lockfp, errstring(errno));
376 
377 # ifdef LOG
378 			if (LogLevel > 29)
379 				syslog(LOG_NOTICE, "%s: lost lock: %m",
380 					e->e_id);
381 # endif /* LOG */
382 			exit(EX_OK);
383 		}
384 # endif /* LOCKF */
385 
386 		/*
387 		**  Close any cached connections.
388 		**
389 		**	We don't send the QUIT protocol because the parent
390 		**	still knows about the connection.
391 		**
392 		**	This should only happen when delivering an error
393 		**	message.
394 		*/
395 
396 		mci_flush(FALSE, NULL);
397 
398 		break;
399 	}
400 
401 	/*
402 	**  Run through the list and send everything.
403 	*/
404 
405 	e->e_nsent = 0;
406 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
407 	{
408 		if (mode == SM_VERIFY)
409 		{
410 			e->e_to = q->q_paddr;
411 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
412 			{
413 				message("deliverable: mailer %s, host %s, user %s",
414 					q->q_mailer->m_name,
415 					q->q_host,
416 					q->q_user);
417 			}
418 		}
419 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
420 		{
421 # ifdef QUEUE
422 			/*
423 			**  Checkpoint the send list every few addresses
424 			*/
425 
426 			if (e->e_nsent >= CheckpointInterval)
427 			{
428 				queueup(e, TRUE, FALSE);
429 				e->e_nsent = 0;
430 			}
431 # endif /* QUEUE */
432 			(void) deliver(e, q);
433 		}
434 	}
435 	Verbose = oldverbose;
436 
437 	/*
438 	**  Now run through and check for errors.
439 	*/
440 
441 	if (mode == SM_VERIFY)
442 	{
443 		return;
444 	}
445 
446 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
447 	{
448 		if (tTd(13, 3))
449 		{
450 			printf("Checking ");
451 			printaddr(q, FALSE);
452 		}
453 
454 		/* only send errors if the message failed */
455 		if (!bitset(QBADADDR, q->q_flags) ||
456 		    bitset(QDONTSEND, q->q_flags))
457 			continue;
458 
459 		e->e_flags |= EF_FATALERRS;
460 
461 		if (q->q_owner == NULL && strcmp(e->e_from.q_paddr, "<>") != 0)
462 			(void) sendtolist(e->e_from.q_paddr, NULL,
463 					  &e->e_errorqueue, e);
464 	}
465 
466 	if (mode == SM_FORK)
467 		finis();
468 }
469 /*
470 **  DOFORK -- do a fork, retrying a couple of times on failure.
471 **
472 **	This MUST be a macro, since after a vfork we are running
473 **	two processes on the same stack!!!
474 **
475 **	Parameters:
476 **		none.
477 **
478 **	Returns:
479 **		From a macro???  You've got to be kidding!
480 **
481 **	Side Effects:
482 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
483 **			pid of child in parent, zero in child.
484 **			-1 on unrecoverable error.
485 **
486 **	Notes:
487 **		I'm awfully sorry this looks so awful.  That's
488 **		vfork for you.....
489 */
490 
491 # define NFORKTRIES	5
492 
493 # ifndef FORK
494 # define FORK	fork
495 # endif
496 
497 # define DOFORK(fORKfN) \
498 {\
499 	register int i;\
500 \
501 	for (i = NFORKTRIES; --i >= 0; )\
502 	{\
503 		pid = fORKfN();\
504 		if (pid >= 0)\
505 			break;\
506 		if (i > 0)\
507 			sleep((unsigned) NFORKTRIES - i);\
508 	}\
509 }
510 /*
511 **  DOFORK -- simple fork interface to DOFORK.
512 **
513 **	Parameters:
514 **		none.
515 **
516 **	Returns:
517 **		pid of child in parent.
518 **		zero in child.
519 **		-1 on error.
520 **
521 **	Side Effects:
522 **		returns twice, once in parent and once in child.
523 */
524 
525 dofork()
526 {
527 	register int pid;
528 
529 	DOFORK(fork);
530 	return (pid);
531 }
532 /*
533 **  DELIVER -- Deliver a message to a list of addresses.
534 **
535 **	This routine delivers to everyone on the same host as the
536 **	user on the head of the list.  It is clever about mailers
537 **	that don't handle multiple users.  It is NOT guaranteed
538 **	that it will deliver to all these addresses however -- so
539 **	deliver should be called once for each address on the
540 **	list.
541 **
542 **	Parameters:
543 **		e -- the envelope to deliver.
544 **		firstto -- head of the address list to deliver to.
545 **
546 **	Returns:
547 **		zero -- successfully delivered.
548 **		else -- some failure, see ExitStat for more info.
549 **
550 **	Side Effects:
551 **		The standard input is passed off to someone.
552 */
553 
554 deliver(e, firstto)
555 	register ENVELOPE *e;
556 	ADDRESS *firstto;
557 {
558 	char *host;			/* host being sent to */
559 	char *user;			/* user being sent to */
560 	char **pvp;
561 	register char **mvp;
562 	register char *p;
563 	register MAILER *m;		/* mailer for this recipient */
564 	ADDRESS *ctladdr;
565 	register MCI *mci;
566 	register ADDRESS *to = firstto;
567 	bool clever = FALSE;		/* running user smtp to this mailer */
568 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
569 	int rcode;			/* response code */
570 	char *firstsig;			/* signature of firstto */
571 	int pid;
572 	char *curhost;
573 	int mpvect[2];
574 	int rpvect[2];
575 	char *pv[MAXPV+1];
576 	char tobuf[TOBUFSIZE];		/* text line of to people */
577 	char buf[MAXNAME];
578 	char rpathbuf[MAXNAME];		/* translated return path */
579 	extern int checkcompat();
580 	extern ADDRESS *getctladdr();
581 	extern char *remotename();
582 	extern char *hostsignature();
583 	extern FILE *fdopen();
584 
585 	errno = 0;
586 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
587 		return (0);
588 
589 #ifdef NAMED_BIND
590 	/* unless interactive, try twice, over a minute */
591 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP) {
592 		_res.retrans = 30;
593 		_res.retry = 2;
594 	}
595 #endif
596 
597 	m = to->q_mailer;
598 	host = to->q_host;
599 	CurEnv = e;			/* just in case */
600 	e->e_statmsg = NULL;
601 
602 	if (tTd(10, 1))
603 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
604 			m->m_mno, host, to->q_user);
605 
606 	/*
607 	**  If this mailer is expensive, and if we don't want to make
608 	**  connections now, just mark these addresses and return.
609 	**	This is useful if we want to batch connections to
610 	**	reduce load.  This will cause the messages to be
611 	**	queued up, and a daemon will come along to send the
612 	**	messages later.
613 	**		This should be on a per-mailer basis.
614 	*/
615 
616 	if (NoConnect && !bitset(EF_QUEUERUN, e->e_flags) &&
617 	    bitnset(M_EXPENSIVE, m->m_flags) && !Verbose)
618 	{
619 		for (; to != NULL; to = to->q_next)
620 		{
621 			if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
622 			    to->q_mailer != m)
623 				continue;
624 			to->q_flags |= QQUEUEUP|QDONTSEND;
625 			e->e_to = to->q_paddr;
626 			message("queued");
627 			if (LogLevel > 8)
628 				logdelivery(m, NULL, "queued", e);
629 		}
630 		e->e_to = NULL;
631 		return (0);
632 	}
633 
634 	/*
635 	**  Do initial argv setup.
636 	**	Insert the mailer name.  Notice that $x expansion is
637 	**	NOT done on the mailer name.  Then, if the mailer has
638 	**	a picky -f flag, we insert it as appropriate.  This
639 	**	code does not check for 'pv' overflow; this places a
640 	**	manifest lower limit of 4 for MAXPV.
641 	**		The from address rewrite is expected to make
642 	**		the address relative to the other end.
643 	*/
644 
645 	/* rewrite from address, using rewriting rules */
646 	rcode = EX_OK;
647 	(void) strcpy(rpathbuf, remotename(e->e_from.q_paddr, m,
648 					   RF_SENDERADDR|RF_CANONICAL,
649 					   &rcode, e));
650 	define('g', rpathbuf, e);		/* translated return path */
651 	define('h', host, e);			/* to host */
652 	Errors = 0;
653 	pvp = pv;
654 	*pvp++ = m->m_argv[0];
655 
656 	/* insert -f or -r flag as appropriate */
657 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
658 	{
659 		if (bitnset(M_FOPT, m->m_flags))
660 			*pvp++ = "-f";
661 		else
662 			*pvp++ = "-r";
663 		*pvp++ = newstr(rpathbuf);
664 	}
665 
666 	/*
667 	**  Append the other fixed parts of the argv.  These run
668 	**  up to the first entry containing "$u".  There can only
669 	**  be one of these, and there are only a few more slots
670 	**  in the pv after it.
671 	*/
672 
673 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
674 	{
675 		/* can't use strchr here because of sign extension problems */
676 		while (*p != '\0')
677 		{
678 			if ((*p++ & 0377) == MACROEXPAND)
679 			{
680 				if (*p == 'u')
681 					break;
682 			}
683 		}
684 
685 		if (*p != '\0')
686 			break;
687 
688 		/* this entry is safe -- go ahead and process it */
689 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
690 		*pvp++ = newstr(buf);
691 		if (pvp >= &pv[MAXPV - 3])
692 		{
693 			syserr("554 Too many parameters to %s before $u", pv[0]);
694 			return (-1);
695 		}
696 	}
697 
698 	/*
699 	**  If we have no substitution for the user name in the argument
700 	**  list, we know that we must supply the names otherwise -- and
701 	**  SMTP is the answer!!
702 	*/
703 
704 	if (*mvp == NULL)
705 	{
706 		/* running SMTP */
707 # ifdef SMTP
708 		clever = TRUE;
709 		*pvp = NULL;
710 # else /* SMTP */
711 		/* oops!  we don't implement SMTP */
712 		syserr("554 SMTP style mailer");
713 		return (EX_SOFTWARE);
714 # endif /* SMTP */
715 	}
716 
717 	/*
718 	**  At this point *mvp points to the argument with $u.  We
719 	**  run through our address list and append all the addresses
720 	**  we can.  If we run out of space, do not fret!  We can
721 	**  always send another copy later.
722 	*/
723 
724 	tobuf[0] = '\0';
725 	e->e_to = tobuf;
726 	ctladdr = NULL;
727 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
728 	for (; to != NULL; to = to->q_next)
729 	{
730 		/* avoid sending multiple recipients to dumb mailers */
731 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
732 			break;
733 
734 		/* if already sent or not for this host, don't send */
735 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
736 		    to->q_mailer != firstto->q_mailer ||
737 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
738 			continue;
739 
740 		/* avoid overflowing tobuf */
741 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
742 			break;
743 
744 		if (tTd(10, 1))
745 		{
746 			printf("\nsend to ");
747 			printaddr(to, FALSE);
748 		}
749 
750 		/* compute effective uid/gid when sending */
751 		if (to->q_mailer == ProgMailer)
752 			ctladdr = getctladdr(to);
753 
754 		user = to->q_user;
755 		e->e_to = to->q_paddr;
756 		if (tTd(10, 5))
757 		{
758 			printf("deliver: QDONTSEND ");
759 			printaddr(to, FALSE);
760 		}
761 		to->q_flags |= QDONTSEND;
762 
763 		/*
764 		**  Check to see that these people are allowed to
765 		**  talk to each other.
766 		*/
767 
768 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
769 		{
770 			NoReturn = TRUE;
771 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
772 			giveresponse(EX_UNAVAILABLE, m, NULL, e);
773 			continue;
774 		}
775 		rcode = checkcompat(to, e);
776 		if (rcode != EX_OK)
777 		{
778 			giveresponse(rcode, m, NULL, e);
779 			continue;
780 		}
781 
782 		/*
783 		**  Strip quote bits from names if the mailer is dumb
784 		**	about them.
785 		*/
786 
787 		if (bitnset(M_STRIPQ, m->m_flags))
788 		{
789 			stripquotes(user);
790 			stripquotes(host);
791 		}
792 
793 		/* hack attack -- delivermail compatibility */
794 		if (m == ProgMailer && *user == '|')
795 			user++;
796 
797 		/*
798 		**  If an error message has already been given, don't
799 		**	bother to send to this address.
800 		**
801 		**	>>>>>>>>>> This clause assumes that the local mailer
802 		**	>> NOTE >> cannot do any further aliasing; that
803 		**	>>>>>>>>>> function is subsumed by sendmail.
804 		*/
805 
806 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
807 			continue;
808 
809 		/* save statistics.... */
810 		markstats(e, to);
811 
812 		/*
813 		**  See if this user name is "special".
814 		**	If the user name has a slash in it, assume that this
815 		**	is a file -- send it off without further ado.  Note
816 		**	that this type of addresses is not processed along
817 		**	with the others, so we fudge on the To person.
818 		*/
819 
820 		if (m == FileMailer)
821 		{
822 			rcode = mailfile(user, getctladdr(to), e);
823 			giveresponse(rcode, m, NULL, e);
824 			if (rcode == EX_OK)
825 				to->q_flags |= QSENT;
826 			continue;
827 		}
828 
829 		/*
830 		**  Address is verified -- add this user to mailer
831 		**  argv, and add it to the print list of recipients.
832 		*/
833 
834 		/* link together the chain of recipients */
835 		to->q_tchain = tochain;
836 		tochain = to;
837 
838 		/* create list of users for error messages */
839 		(void) strcat(tobuf, ",");
840 		(void) strcat(tobuf, to->q_paddr);
841 		define('u', user, e);		/* to user */
842 		define('z', to->q_home, e);	/* user's home */
843 
844 		/*
845 		**  Expand out this user into argument list.
846 		*/
847 
848 		if (!clever)
849 		{
850 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
851 			*pvp++ = newstr(buf);
852 			if (pvp >= &pv[MAXPV - 2])
853 			{
854 				/* allow some space for trailing parms */
855 				break;
856 			}
857 		}
858 	}
859 
860 	/* see if any addresses still exist */
861 	if (tobuf[0] == '\0')
862 	{
863 		define('g', (char *) NULL, e);
864 		return (0);
865 	}
866 
867 	/* print out messages as full list */
868 	e->e_to = tobuf + 1;
869 
870 	/*
871 	**  Fill out any parameters after the $u parameter.
872 	*/
873 
874 	while (!clever && *++mvp != NULL)
875 	{
876 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
877 		*pvp++ = newstr(buf);
878 		if (pvp >= &pv[MAXPV])
879 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
880 	}
881 	*pvp++ = NULL;
882 
883 	/*
884 	**  Call the mailer.
885 	**	The argument vector gets built, pipes
886 	**	are created as necessary, and we fork & exec as
887 	**	appropriate.
888 	**	If we are running SMTP, we just need to clean up.
889 	*/
890 
891 	if (ctladdr == NULL && m != ProgMailer)
892 		ctladdr = &e->e_from;
893 #ifdef NAMED_BIND
894 	if (ConfigLevel < 2)
895 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
896 #endif
897 
898 	if (tTd(11, 1))
899 	{
900 		printf("openmailer:");
901 		printav(pv);
902 	}
903 	errno = 0;
904 
905 	CurHostName = m->m_mailer;
906 
907 	/*
908 	**  Deal with the special case of mail handled through an IPC
909 	**  connection.
910 	**	In this case we don't actually fork.  We must be
911 	**	running SMTP for this to work.  We will return a
912 	**	zero pid to indicate that we are running IPC.
913 	**  We also handle a debug version that just talks to stdin/out.
914 	*/
915 
916 	curhost = NULL;
917 
918 	/* check for Local Person Communication -- not for mortals!!! */
919 	if (strcmp(m->m_mailer, "[LPC]") == 0)
920 	{
921 		mci = (MCI *) xalloc(sizeof *mci);
922 		bzero((char *) mci, sizeof *mci);
923 		mci->mci_in = stdin;
924 		mci->mci_out = stdout;
925 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
926 		mci->mci_mailer = m;
927 	}
928 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
929 		 strcmp(m->m_mailer, "[TCP]") == 0)
930 	{
931 #ifdef DAEMON
932 		register int i;
933 		register u_short port;
934 		extern MCI *mci_get();
935 		extern char *hostsignature();
936 
937 		CurHostName = pv[1];
938 		curhost = hostsignature(m, pv[1], e);
939 
940 		if (curhost == NULL || curhost[0] == '\0')
941 		{
942 			syserr("null signature");
943 			rcode = EX_OSERR;
944 			goto give_up;
945 		}
946 
947 		if (!clever)
948 		{
949 			syserr("554 non-clever IPC");
950 			rcode = EX_OSERR;
951 			goto give_up;
952 		}
953 		if (pv[2] != NULL)
954 			port = atoi(pv[2]);
955 		else
956 			port = 0;
957 tryhost:
958 		mci = NULL;
959 		while (*curhost != '\0')
960 		{
961 			register char *p;
962 			static char hostbuf[MAXNAME];
963 
964 			mci = NULL;
965 
966 			/* pull the next host from the signature */
967 			p = strchr(curhost, ':');
968 			if (p == NULL)
969 				p = &curhost[strlen(curhost)];
970 			strncpy(hostbuf, curhost, p - curhost);
971 			hostbuf[p - curhost] = '\0';
972 			if (*p != '\0')
973 				p++;
974 			curhost = p;
975 
976 			/* see if we already know that this host is fried */
977 			CurHostName = hostbuf;
978 			mci = mci_get(hostbuf, m);
979 			if (mci->mci_state != MCIS_CLOSED)
980 			{
981 				if (tTd(11, 1))
982 				{
983 					printf("openmailer: ");
984 					mci_dump(mci);
985 				}
986 				CurHostName = mci->mci_host;
987 				break;
988 			}
989 			mci->mci_mailer = m;
990 			if (mci->mci_exitstat != EX_OK)
991 				continue;
992 
993 			/* try the connection */
994 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
995 			message("Connecting to %s (%s)...",
996 				hostbuf, m->m_name);
997 			i = makeconnection(hostbuf, port, mci,
998 				bitnset(M_SECURE_PORT, m->m_flags));
999 			mci->mci_exitstat = i;
1000 			mci->mci_errno = errno;
1001 			if (i == EX_OK)
1002 			{
1003 				mci->mci_state = MCIS_OPENING;
1004 				mci_cache(mci);
1005 				break;
1006 			}
1007 			else if (tTd(11, 1))
1008 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1009 					i, errno);
1010 
1011 
1012 			/* enter status of this host */
1013 			setstat(i);
1014 		}
1015 		mci->mci_pid = 0;
1016 #else /* no DAEMON */
1017 		syserr("554 openmailer: no IPC");
1018 		if (tTd(11, 1))
1019 			printf("openmailer: NULL\n");
1020 		return NULL;
1021 #endif /* DAEMON */
1022 	}
1023 	else
1024 	{
1025 		int i;
1026 		struct stat stbuf;
1027 
1028 		/* make absolutely certain 0, 1, and 2 are in use */
1029 		for (i = 0; i < 3; i++)
1030 		{
1031 			if (fstat(i, &stbuf) < 0)
1032 			{
1033 				/* oops.... */
1034 				int fd;
1035 
1036 				syserr("%s... openmailer(%s): fd %d not open",
1037 					e->e_to, m->m_name, i);
1038 				fd = open("/dev/null", O_RDONLY, 0666);
1039 				if (fd != i)
1040 				{
1041 					(void) dup2(fd, i);
1042 					(void) close(fd);
1043 				}
1044 			}
1045 		}
1046 
1047 		/* create a pipe to shove the mail through */
1048 		if (pipe(mpvect) < 0)
1049 		{
1050 			syserr("%s... openmailer(%s): pipe (to mailer)",
1051 				e->e_to, m->m_name);
1052 			if (tTd(11, 1))
1053 				printf("openmailer: NULL\n");
1054 			rcode = EX_OSERR;
1055 			goto give_up;
1056 		}
1057 
1058 		/* if this mailer speaks smtp, create a return pipe */
1059 		if (clever && pipe(rpvect) < 0)
1060 		{
1061 			syserr("%s... openmailer(%s): pipe (from mailer)",
1062 				e->e_to, m->m_name);
1063 			(void) close(mpvect[0]);
1064 			(void) close(mpvect[1]);
1065 			if (tTd(11, 1))
1066 				printf("openmailer: NULL\n");
1067 			rcode = EX_OSERR;
1068 			goto give_up;
1069 		}
1070 
1071 		/*
1072 		**  Actually fork the mailer process.
1073 		**	DOFORK is clever about retrying.
1074 		**
1075 		**	Dispose of SIGCHLD signal catchers that may be laying
1076 		**	around so that endmail will get it.
1077 		*/
1078 
1079 		if (e->e_xfp != NULL)
1080 			(void) fflush(e->e_xfp);		/* for debugging */
1081 		(void) fflush(stdout);
1082 # ifdef SIGCHLD
1083 		(void) signal(SIGCHLD, SIG_DFL);
1084 # endif /* SIGCHLD */
1085 		DOFORK(FORK);
1086 		/* pid is set by DOFORK */
1087 		if (pid < 0)
1088 		{
1089 			/* failure */
1090 			syserr("%s... openmailer(%s): cannot fork",
1091 				e->e_to, m->m_name);
1092 			(void) close(mpvect[0]);
1093 			(void) close(mpvect[1]);
1094 			if (clever)
1095 			{
1096 				(void) close(rpvect[0]);
1097 				(void) close(rpvect[1]);
1098 			}
1099 			if (tTd(11, 1))
1100 				printf("openmailer: NULL\n");
1101 			rcode = EX_OSERR;
1102 			goto give_up;
1103 		}
1104 		else if (pid == 0)
1105 		{
1106 			int i;
1107 			int saveerrno;
1108 			char **ep;
1109 			char *env[MAXUSERENVIRON];
1110 			extern char **environ;
1111 			extern int DtableSize;
1112 
1113 			/* child -- set up input & exec mailer */
1114 			/* make diagnostic output be standard output */
1115 			(void) signal(SIGINT, SIG_IGN);
1116 			(void) signal(SIGHUP, SIG_IGN);
1117 			(void) signal(SIGTERM, SIG_DFL);
1118 
1119 			/* close any other cached connections */
1120 			mci_flush(FALSE, mci);
1121 
1122 			/* move into some "safe" directory */
1123 			if (m->m_execdir != NULL)
1124 			{
1125 				char *p, *q;
1126 				char buf[MAXLINE];
1127 
1128 				for (p = m->m_execdir; p != NULL; p = q)
1129 				{
1130 					q = strchr(p, ':');
1131 					if (q != NULL)
1132 						*q = '\0';
1133 					expand(p, buf, &buf[sizeof buf] - 1, e);
1134 					if (q != NULL)
1135 						*q++ = ':';
1136 					if (tTd(11, 20))
1137 						printf("openmailer: trydir %s\n",
1138 							buf);
1139 					if (buf[0] != '\0' && chdir(buf) >= 0)
1140 						break;
1141 				}
1142 			}
1143 
1144 			/* arrange to filter std & diag output of command */
1145 			if (clever)
1146 			{
1147 				(void) close(rpvect[0]);
1148 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1149 				{
1150 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1151 						e->e_to, m->m_name, rpvect[1]);
1152 					_exit(EX_OSERR);
1153 				}
1154 				(void) close(rpvect[1]);
1155 			}
1156 			else if (OpMode == MD_SMTP || HoldErrs)
1157 			{
1158 				/* put mailer output in transcript */
1159 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1160 				{
1161 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1162 						e->e_to, m->m_name,
1163 						fileno(e->e_xfp));
1164 					_exit(EX_OSERR);
1165 				}
1166 			}
1167 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1168 			{
1169 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1170 					e->e_to, m->m_name);
1171 				_exit(EX_OSERR);
1172 			}
1173 
1174 			/* arrange to get standard input */
1175 			(void) close(mpvect[1]);
1176 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1177 			{
1178 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1179 					e->e_to, m->m_name, mpvect[0]);
1180 				_exit(EX_OSERR);
1181 			}
1182 			(void) close(mpvect[0]);
1183 			if (!bitnset(M_RESTR, m->m_flags))
1184 			{
1185 				if (ctladdr == NULL || ctladdr->q_uid == 0)
1186 				{
1187 					(void) setgid(DefGid);
1188 					(void) initgroups(DefUser, DefGid);
1189 					(void) setuid(DefUid);
1190 				}
1191 				else
1192 				{
1193 					(void) setgid(ctladdr->q_gid);
1194 					(void) initgroups(ctladdr->q_ruser?
1195 						ctladdr->q_ruser: ctladdr->q_user,
1196 						ctladdr->q_gid);
1197 					(void) setuid(ctladdr->q_uid);
1198 				}
1199 			}
1200 
1201 			/* arrange for all the files to be closed */
1202 			for (i = 3; i < DtableSize; i++)
1203 			{
1204 				register int j;
1205 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1206 					(void)fcntl(i, F_SETFD, j|1);
1207 			}
1208 
1209 			/* set up the mailer environment */
1210 			i = 0;
1211 			env[i++] = "AGENT=sendmail";
1212 			for (ep = environ; *ep != NULL; ep++)
1213 			{
1214 				if (strncmp(*ep, "TZ=", 3) == 0)
1215 					env[i++] = *ep;
1216 			}
1217 			env[i++] = NULL;
1218 
1219 			/* try to execute the mailer */
1220 			execve(m->m_mailer, pv, env);
1221 			saveerrno = errno;
1222 			syserr("Cannot exec %s", m->m_mailer);
1223 			if (m == LocalMailer || transienterror(saveerrno))
1224 				_exit(EX_OSERR);
1225 			_exit(EX_UNAVAILABLE);
1226 		}
1227 
1228 		/*
1229 		**  Set up return value.
1230 		*/
1231 
1232 		mci = (MCI *) xalloc(sizeof *mci);
1233 		bzero((char *) mci, sizeof *mci);
1234 		mci->mci_mailer = m;
1235 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1236 		mci->mci_pid = pid;
1237 		(void) close(mpvect[0]);
1238 		mci->mci_out = fdopen(mpvect[1], "w");
1239 		if (clever)
1240 		{
1241 			(void) close(rpvect[1]);
1242 			mci->mci_in = fdopen(rpvect[0], "r");
1243 		}
1244 		else
1245 		{
1246 			mci->mci_flags |= MCIF_TEMP;
1247 			mci->mci_in = NULL;
1248 		}
1249 	}
1250 
1251 	/*
1252 	**  If we are in SMTP opening state, send initial protocol.
1253 	*/
1254 
1255 	if (clever && mci->mci_state != MCIS_CLOSED)
1256 	{
1257 		smtpinit(m, mci, e);
1258 	}
1259 	if (tTd(11, 1))
1260 	{
1261 		printf("openmailer: ");
1262 		mci_dump(mci);
1263 	}
1264 
1265 	if (mci->mci_state != MCIS_OPEN)
1266 	{
1267 		/* couldn't open the mailer */
1268 		rcode = mci->mci_exitstat;
1269 		errno = mci->mci_errno;
1270 		if (rcode == EX_OK)
1271 		{
1272 			/* shouldn't happen */
1273 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1274 				rcode, mci->mci_state, firstsig);
1275 			rcode = EX_SOFTWARE;
1276 		}
1277 		else if (rcode == EX_TEMPFAIL && *curhost != '\0')
1278 		{
1279 			/* try next MX site */
1280 			goto tryhost;
1281 		}
1282 	}
1283 	else if (!clever)
1284 	{
1285 		/*
1286 		**  Format and send message.
1287 		*/
1288 
1289 		putfromline(mci->mci_out, m, e);
1290 		(*e->e_puthdr)(mci->mci_out, m, e);
1291 		putline("\n", mci->mci_out, m);
1292 		(*e->e_putbody)(mci->mci_out, m, e, NULL);
1293 
1294 		/* get the exit status */
1295 		rcode = endmailer(mci, e, pv);
1296 	}
1297 	else
1298 #ifdef SMTP
1299 	{
1300 		/*
1301 		**  Send the MAIL FROM: protocol
1302 		*/
1303 
1304 		rcode = smtpmailfrom(m, mci, e);
1305 		if (rcode == EX_OK)
1306 		{
1307 			register char *t = tobuf;
1308 			register int i;
1309 
1310 			/* send the recipient list */
1311 			tobuf[0] = '\0';
1312 			for (to = tochain; to != NULL; to = to->q_tchain)
1313 			{
1314 				e->e_to = to->q_paddr;
1315 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1316 				{
1317 					markfailure(e, to, i);
1318 					giveresponse(i, m, mci, e);
1319 				}
1320 				else
1321 				{
1322 					*t++ = ',';
1323 					for (p = to->q_paddr; *p; *t++ = *p++)
1324 						continue;
1325 				}
1326 			}
1327 
1328 			/* now send the data */
1329 			if (tobuf[0] == '\0')
1330 			{
1331 				rcode = EX_OK;
1332 				e->e_to = NULL;
1333 				if (bitset(MCIF_CACHED, mci->mci_flags))
1334 					smtprset(m, mci, e);
1335 			}
1336 			else
1337 			{
1338 				e->e_to = tobuf + 1;
1339 				rcode = smtpdata(m, mci, e);
1340 			}
1341 
1342 			/* now close the connection */
1343 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1344 				smtpquit(m, mci, e);
1345 		}
1346 		if (rcode != EX_OK && *curhost != '\0')
1347 		{
1348 			/* try next MX site */
1349 			goto tryhost;
1350 		}
1351 	}
1352 #else /* not SMTP */
1353 	{
1354 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1355 		rcode = EX_CONFIG;
1356 		goto give_up;
1357 	}
1358 #endif /* SMTP */
1359 #ifdef NAMED_BIND
1360 	if (ConfigLevel < 2)
1361 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1362 #endif
1363 
1364 	/* arrange a return receipt if requested */
1365 	if (e->e_receiptto != NULL && bitnset(M_LOCALMAILER, m->m_flags))
1366 	{
1367 		e->e_flags |= EF_SENDRECEIPT;
1368 		/* do we want to send back more info? */
1369 	}
1370 
1371 	/*
1372 	**  Do final status disposal.
1373 	**	We check for something in tobuf for the SMTP case.
1374 	**	If we got a temporary failure, arrange to queue the
1375 	**		addressees.
1376 	*/
1377 
1378   give_up:
1379 	if (tobuf[0] != '\0')
1380 		giveresponse(rcode, m, mci, e);
1381 	for (to = tochain; to != NULL; to = to->q_tchain)
1382 	{
1383 		if (rcode != EX_OK)
1384 			markfailure(e, to, rcode);
1385 		else
1386 		{
1387 			to->q_flags |= QSENT;
1388 			e->e_nsent++;
1389 		}
1390 	}
1391 
1392 	/*
1393 	**  Restore state and return.
1394 	*/
1395 
1396 	errno = 0;
1397 	define('g', (char *) NULL, e);
1398 	return (rcode);
1399 }
1400 /*
1401 **  MARKFAILURE -- mark a failure on a specific address.
1402 **
1403 **	Parameters:
1404 **		e -- the envelope we are sending.
1405 **		q -- the address to mark.
1406 **		rcode -- the code signifying the particular failure.
1407 **
1408 **	Returns:
1409 **		none.
1410 **
1411 **	Side Effects:
1412 **		marks the address (and possibly the envelope) with the
1413 **			failure so that an error will be returned or
1414 **			the message will be queued, as appropriate.
1415 */
1416 
1417 markfailure(e, q, rcode)
1418 	register ENVELOPE *e;
1419 	register ADDRESS *q;
1420 	int rcode;
1421 {
1422 	char buf[MAXLINE];
1423 	extern char *pintvl();
1424 
1425 	if (rcode == EX_OK)
1426 		return;
1427 	else if (rcode != EX_TEMPFAIL && rcode != EX_IOERR && rcode != EX_OSERR)
1428 		q->q_flags |= QBADADDR;
1429 	else if (curtime() > e->e_ctime + TimeOuts.to_q_return)
1430 	{
1431 		if (!bitset(EF_TIMEOUT, e->e_flags))
1432 		{
1433 			(void) sprintf(buf, "Cannot send message for %s",
1434 				pintvl(TimeOuts.to_q_return, FALSE));
1435 			if (e->e_message != NULL)
1436 				free(e->e_message);
1437 			e->e_message = newstr(buf);
1438 			message(buf);
1439 		}
1440 		q->q_flags |= QBADADDR;
1441 		e->e_flags |= EF_TIMEOUT;
1442 		fprintf(e->e_xfp, "421 %s... Message timed out\n", q->q_paddr);
1443 	}
1444 	else
1445 	{
1446 		q->q_flags |= QQUEUEUP;
1447 		if (TimeOuts.to_q_warning > 0 &&
1448 		    curtime() > e->e_ctime + TimeOuts.to_q_warning)
1449 		{
1450 			if (!bitset(EF_WARNING, e->e_flags) &&
1451 			    e->e_class >= 0)
1452 			{
1453 				(void) sprintf(buf,
1454 					"warning: cannot send message for %s",
1455 					pintvl(TimeOuts.to_q_warning, FALSE));
1456 				if (e->e_message != NULL)
1457 					free(e->e_message);
1458 				e->e_message = newstr(buf);
1459 				message(buf);
1460 				e->e_flags |= EF_WARNING|EF_TIMEOUT;
1461 			}
1462 			fprintf(e->e_xfp,
1463 				"%s... Warning: message still undelivered after %s\n",
1464 				q->q_paddr, pintvl(TimeOuts.to_q_warning, FALSE));
1465 			fprintf(e->e_xfp, "Will keep trying until message is %s old\n",
1466 				pintvl(TimeOuts.to_q_return, FALSE));
1467 		}
1468 	}
1469 }
1470 /*
1471 **  ENDMAILER -- Wait for mailer to terminate.
1472 **
1473 **	We should never get fatal errors (e.g., segmentation
1474 **	violation), so we report those specially.  For other
1475 **	errors, we choose a status message (into statmsg),
1476 **	and if it represents an error, we print it.
1477 **
1478 **	Parameters:
1479 **		pid -- pid of mailer.
1480 **		e -- the current envelope.
1481 **		pv -- the parameter vector that invoked the mailer
1482 **			(for error messages).
1483 **
1484 **	Returns:
1485 **		exit code of mailer.
1486 **
1487 **	Side Effects:
1488 **		none.
1489 */
1490 
1491 endmailer(mci, e, pv)
1492 	register MCI *mci;
1493 	register ENVELOPE *e;
1494 	char **pv;
1495 {
1496 	int st;
1497 
1498 	/* close any connections */
1499 	if (mci->mci_in != NULL)
1500 		(void) xfclose(mci->mci_in, pv[0], "mci_in");
1501 	if (mci->mci_out != NULL)
1502 		(void) xfclose(mci->mci_out, pv[0], "mci_out");
1503 	mci->mci_in = mci->mci_out = NULL;
1504 	mci->mci_state = MCIS_CLOSED;
1505 
1506 	/* in the IPC case there is nothing to wait for */
1507 	if (mci->mci_pid == 0)
1508 		return (EX_OK);
1509 
1510 	/* wait for the mailer process to die and collect status */
1511 	st = waitfor(mci->mci_pid);
1512 	if (st == -1)
1513 	{
1514 		syserr("endmailer %s: wait", pv[0]);
1515 		return (EX_SOFTWARE);
1516 	}
1517 
1518 	/* see if it died a horrid death */
1519 	if ((st & 0377) != 0)
1520 	{
1521 		syserr("mailer %s died with signal %o", pv[0], st);
1522 
1523 		/* log the arguments */
1524 		if (e->e_xfp != NULL)
1525 		{
1526 			register char **av;
1527 
1528 			fprintf(e->e_xfp, "Arguments:");
1529 			for (av = pv; *av != NULL; av++)
1530 				fprintf(e->e_xfp, " %s", *av);
1531 			fprintf(e->e_xfp, "\n");
1532 		}
1533 
1534 		ExitStat = EX_TEMPFAIL;
1535 		return (EX_TEMPFAIL);
1536 	}
1537 
1538 	/* normal death -- return status */
1539 	st = (st >> 8) & 0377;
1540 	return (st);
1541 }
1542 /*
1543 **  GIVERESPONSE -- Interpret an error response from a mailer
1544 **
1545 **	Parameters:
1546 **		stat -- the status code from the mailer (high byte
1547 **			only; core dumps must have been taken care of
1548 **			already).
1549 **		m -- the mailer info for this mailer.
1550 **		mci -- the mailer connection info -- can be NULL if the
1551 **			response is given before the connection is made.
1552 **		e -- the current envelope.
1553 **
1554 **	Returns:
1555 **		none.
1556 **
1557 **	Side Effects:
1558 **		Errors may be incremented.
1559 **		ExitStat may be set.
1560 */
1561 
1562 giveresponse(stat, m, mci, e)
1563 	int stat;
1564 	register MAILER *m;
1565 	register MCI *mci;
1566 	ENVELOPE *e;
1567 {
1568 	register const char *statmsg;
1569 	extern char *SysExMsg[];
1570 	register int i;
1571 	extern int N_SysEx;
1572 #ifdef NAMED_BIND
1573 	extern int h_errno;
1574 #endif
1575 	char buf[MAXLINE];
1576 
1577 	/*
1578 	**  Compute status message from code.
1579 	*/
1580 
1581 	i = stat - EX__BASE;
1582 	if (stat == 0)
1583 	{
1584 		statmsg = "250 Sent";
1585 		if (e->e_statmsg != NULL)
1586 		{
1587 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1588 			statmsg = buf;
1589 		}
1590 	}
1591 	else if (i < 0 || i > N_SysEx)
1592 	{
1593 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1594 		stat = EX_UNAVAILABLE;
1595 		statmsg = buf;
1596 	}
1597 	else if (stat == EX_TEMPFAIL)
1598 	{
1599 		(void) strcpy(buf, SysExMsg[i] + 1);
1600 #ifdef NAMED_BIND
1601 		if (h_errno == TRY_AGAIN)
1602 			statmsg = errstring(h_errno+MAX_ERRNO);
1603 		else
1604 #endif
1605 		{
1606 			if (errno != 0)
1607 				statmsg = errstring(errno);
1608 			else
1609 			{
1610 #ifdef SMTP
1611 				extern char SmtpError[];
1612 
1613 				statmsg = SmtpError;
1614 #else /* SMTP */
1615 				statmsg = NULL;
1616 #endif /* SMTP */
1617 			}
1618 		}
1619 		if (statmsg != NULL && statmsg[0] != '\0')
1620 		{
1621 			(void) strcat(buf, ": ");
1622 			(void) strcat(buf, statmsg);
1623 		}
1624 		statmsg = buf;
1625 	}
1626 	else
1627 	{
1628 		statmsg = SysExMsg[i];
1629 		if (*statmsg++ == ':')
1630 		{
1631 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1632 			statmsg = buf;
1633 		}
1634 	}
1635 
1636 	/*
1637 	**  Print the message as appropriate
1638 	*/
1639 
1640 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1641 		message(&statmsg[4], errstring(errno));
1642 	else
1643 	{
1644 		Errors++;
1645 		usrerr(statmsg, errstring(errno));
1646 	}
1647 
1648 	/*
1649 	**  Final cleanup.
1650 	**	Log a record of the transaction.  Compute the new
1651 	**	ExitStat -- if we already had an error, stick with
1652 	**	that.
1653 	*/
1654 
1655 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1656 		logdelivery(m, mci, &statmsg[4], e);
1657 
1658 	if (stat != EX_TEMPFAIL)
1659 		setstat(stat);
1660 	if (stat != EX_OK)
1661 	{
1662 		if (e->e_message != NULL)
1663 			free(e->e_message);
1664 		e->e_message = newstr(&statmsg[4]);
1665 	}
1666 	errno = 0;
1667 #ifdef NAMED_BIND
1668 	h_errno = 0;
1669 #endif
1670 }
1671 /*
1672 **  LOGDELIVERY -- log the delivery in the system log
1673 **
1674 **	Parameters:
1675 **		m -- the mailer info.  Can be NULL for initial queue.
1676 **		mci -- the mailer connection info -- can be NULL if the
1677 **			log is occuring when no connection is active.
1678 **		stat -- the message to print for the status.
1679 **		e -- the current envelope.
1680 **
1681 **	Returns:
1682 **		none
1683 **
1684 **	Side Effects:
1685 **		none
1686 */
1687 
1688 logdelivery(m, mci, stat, e)
1689 	MAILER *m;
1690 	register MCI *mci;
1691 	char *stat;
1692 	register ENVELOPE *e;
1693 {
1694 # ifdef LOG
1695 	char *curhost;
1696 	char buf[512];
1697 	extern char *pintvl();
1698 	extern char *macvalue();
1699 
1700 	(void) sprintf(buf, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
1701 
1702 	if (m != NULL)
1703 	{
1704 		(void) strcat(buf, ", mailer=");
1705 		(void) strcat(buf, m->m_name);
1706 	}
1707 
1708 	if (mci != NULL && mci->mci_host != NULL)
1709 	{
1710 # ifdef DAEMON
1711 		extern SOCKADDR CurHostAddr;
1712 		extern char *anynet_ntoa();
1713 # endif
1714 
1715 		(void) strcat(buf, ", relay=");
1716 		(void) strcat(buf, mci->mci_host);
1717 
1718 # ifdef DAEMON
1719 		(void) strcat(buf, " (");
1720 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
1721 		(void) strcat(buf, ")");
1722 # endif
1723 	}
1724 	else
1725 	{
1726 		char *p = macvalue('h', e);
1727 
1728 		if (p != NULL && p[0] != '\0')
1729 		{
1730 			(void) strcat(buf, ", relay=");
1731 			(void) strcat(buf, p);
1732 		}
1733 	}
1734 
1735 	syslog(LOG_INFO, "%s: to=%s, %s, stat=%s",
1736 	       e->e_id, e->e_to, buf, stat);
1737 # endif /* LOG */
1738 }
1739 /*
1740 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1741 **
1742 **	This can be made an arbitrary message separator by changing $l
1743 **
1744 **	One of the ugliest hacks seen by human eyes is contained herein:
1745 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1746 **	does a well-meaning programmer such as myself have to deal with
1747 **	this kind of antique garbage????
1748 **
1749 **	Parameters:
1750 **		fp -- the file to output to.
1751 **		m -- the mailer describing this entry.
1752 **
1753 **	Returns:
1754 **		none
1755 **
1756 **	Side Effects:
1757 **		outputs some text to fp.
1758 */
1759 
1760 putfromline(fp, m, e)
1761 	register FILE *fp;
1762 	register MAILER *m;
1763 	ENVELOPE *e;
1764 {
1765 	char *template = "\201l\n";
1766 	char buf[MAXLINE];
1767 
1768 	if (bitnset(M_NHDR, m->m_flags))
1769 		return;
1770 
1771 # ifdef UGLYUUCP
1772 	if (bitnset(M_UGLYUUCP, m->m_flags))
1773 	{
1774 		char *bang;
1775 		char xbuf[MAXLINE];
1776 
1777 		expand("\201g", buf, &buf[sizeof buf - 1], e);
1778 		bang = strchr(buf, '!');
1779 		if (bang == NULL)
1780 			syserr("554 No ! in UUCP! (%s)", buf);
1781 		else
1782 		{
1783 			*bang++ = '\0';
1784 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
1785 			template = xbuf;
1786 		}
1787 	}
1788 # endif /* UGLYUUCP */
1789 	expand(template, buf, &buf[sizeof buf - 1], e);
1790 	putline(buf, fp, m);
1791 }
1792 /*
1793 **  PUTBODY -- put the body of a message.
1794 **
1795 **	Parameters:
1796 **		fp -- file to output onto.
1797 **		m -- a mailer descriptor to control output format.
1798 **		e -- the envelope to put out.
1799 **		separator -- if non-NULL, a message separator that must
1800 **			not be permitted in the resulting message.
1801 **
1802 **	Returns:
1803 **		none.
1804 **
1805 **	Side Effects:
1806 **		The message is written onto fp.
1807 */
1808 
1809 putbody(fp, m, e, separator)
1810 	FILE *fp;
1811 	MAILER *m;
1812 	register ENVELOPE *e;
1813 	char *separator;
1814 {
1815 	char buf[MAXLINE];
1816 
1817 	/*
1818 	**  Output the body of the message
1819 	*/
1820 
1821 	if (e->e_dfp == NULL)
1822 	{
1823 		if (e->e_df != NULL)
1824 		{
1825 			e->e_dfp = fopen(e->e_df, "r");
1826 			if (e->e_dfp == NULL)
1827 				syserr("putbody: Cannot open %s for %s from %s",
1828 				e->e_df, e->e_to, e->e_from);
1829 		}
1830 		else
1831 			putline("<<< No Message Collected >>>", fp, m);
1832 	}
1833 	if (e->e_dfp != NULL)
1834 	{
1835 		rewind(e->e_dfp);
1836 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1837 		{
1838 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1839 			    strncmp(buf, "From ", 5) == 0)
1840 				(void) putc('>', fp);
1841 			if (buf[0] == '-' && buf[1] == '-' && separator != NULL)
1842 			{
1843 				/* possible separator */
1844 				int sl = strlen(separator);
1845 
1846 				if (strncmp(&buf[2], separator, sl) == 0)
1847 					(void) putc(' ', fp);
1848 			}
1849 			putline(buf, fp, m);
1850 		}
1851 
1852 		if (ferror(e->e_dfp))
1853 		{
1854 			syserr("putbody: read error");
1855 			ExitStat = EX_IOERR;
1856 		}
1857 	}
1858 
1859 	/* some mailers want extra blank line at end of message */
1860 	if (bitnset(M_BLANKEND, m->m_flags) && buf[0] != '\0' && buf[0] != '\n')
1861 		putline("", fp, m);
1862 
1863 	(void) fflush(fp);
1864 	if (ferror(fp) && errno != EPIPE)
1865 	{
1866 		syserr("putbody: write error");
1867 		ExitStat = EX_IOERR;
1868 	}
1869 	errno = 0;
1870 }
1871 /*
1872 **  MAILFILE -- Send a message to a file.
1873 **
1874 **	If the file has the setuid/setgid bits set, but NO execute
1875 **	bits, sendmail will try to become the owner of that file
1876 **	rather than the real user.  Obviously, this only works if
1877 **	sendmail runs as root.
1878 **
1879 **	This could be done as a subordinate mailer, except that it
1880 **	is used implicitly to save messages in ~/dead.letter.  We
1881 **	view this as being sufficiently important as to include it
1882 **	here.  For example, if the system is dying, we shouldn't have
1883 **	to create another process plus some pipes to save the message.
1884 **
1885 **	Parameters:
1886 **		filename -- the name of the file to send to.
1887 **		ctladdr -- the controlling address header -- includes
1888 **			the userid/groupid to be when sending.
1889 **
1890 **	Returns:
1891 **		The exit code associated with the operation.
1892 **
1893 **	Side Effects:
1894 **		none.
1895 */
1896 
1897 mailfile(filename, ctladdr, e)
1898 	char *filename;
1899 	ADDRESS *ctladdr;
1900 	register ENVELOPE *e;
1901 {
1902 	register FILE *f;
1903 	register int pid;
1904 	int mode;
1905 
1906 	if (tTd(11, 1))
1907 	{
1908 		printf("mailfile %s\n  ctladdr=", filename);
1909 		printaddr(ctladdr, FALSE);
1910 	}
1911 
1912 	/*
1913 	**  Fork so we can change permissions here.
1914 	**	Note that we MUST use fork, not vfork, because of
1915 	**	the complications of calling subroutines, etc.
1916 	*/
1917 
1918 	DOFORK(fork);
1919 
1920 	if (pid < 0)
1921 		return (EX_OSERR);
1922 	else if (pid == 0)
1923 	{
1924 		/* child -- actually write to file */
1925 		struct stat stb;
1926 
1927 		(void) signal(SIGINT, SIG_DFL);
1928 		(void) signal(SIGHUP, SIG_DFL);
1929 		(void) signal(SIGTERM, SIG_DFL);
1930 		(void) umask(OldUmask);
1931 
1932 		if (stat(filename, &stb) < 0)
1933 			stb.st_mode = FileMode;
1934 		mode = stb.st_mode;
1935 
1936 		/* limit the errors to those actually caused in the child */
1937 		errno = 0;
1938 		ExitStat = EX_OK;
1939 
1940 		if (bitset(0111, stb.st_mode))
1941 			exit(EX_CANTCREAT);
1942 		if (ctladdr == NULL)
1943 			ctladdr = &e->e_from;
1944 		else
1945 		{
1946 			/* ignore setuid and setgid bits */
1947 			mode &= ~(S_ISGID|S_ISUID);
1948 		}
1949 
1950 		/* we have to open the dfile BEFORE setuid */
1951 		if (e->e_dfp == NULL && e->e_df != NULL)
1952 		{
1953 			e->e_dfp = fopen(e->e_df, "r");
1954 			if (e->e_dfp == NULL)
1955 			{
1956 				syserr("mailfile: Cannot open %s for %s from %s",
1957 					e->e_df, e->e_to, e->e_from);
1958 			}
1959 		}
1960 
1961 		if (!bitset(S_ISGID, mode) || setgid(stb.st_gid) < 0)
1962 		{
1963 			if (ctladdr->q_uid == 0)
1964 			{
1965 				(void) setgid(DefGid);
1966 				(void) initgroups(DefUser, DefGid);
1967 			}
1968 			else
1969 			{
1970 				(void) setgid(ctladdr->q_gid);
1971 				(void) initgroups(ctladdr->q_ruser ?
1972 					ctladdr->q_ruser : ctladdr->q_user,
1973 					ctladdr->q_gid);
1974 			}
1975 		}
1976 		if (!bitset(S_ISUID, mode) || setuid(stb.st_uid) < 0)
1977 		{
1978 			if (ctladdr->q_uid == 0)
1979 				(void) setuid(DefUid);
1980 			else
1981 				(void) setuid(ctladdr->q_uid);
1982 		}
1983 		FileName = filename;
1984 		LineNumber = 0;
1985 		f = dfopen(filename, O_WRONLY|O_CREAT|O_APPEND, FileMode);
1986 		if (f == NULL)
1987 		{
1988 			message("554 cannot open");
1989 			exit(EX_CANTCREAT);
1990 		}
1991 
1992 		putfromline(f, FileMailer, e);
1993 		(*e->e_puthdr)(f, FileMailer, e);
1994 		putline("\n", f, FileMailer);
1995 		(*e->e_putbody)(f, FileMailer, e, NULL);
1996 		putline("\n", f, FileMailer);
1997 		if (ferror(f))
1998 		{
1999 			message("451 I/O error");
2000 			setstat(EX_IOERR);
2001 		}
2002 		(void) xfclose(f, "mailfile", filename);
2003 		(void) fflush(stdout);
2004 
2005 		/* reset ISUID & ISGID bits for paranoid systems */
2006 		(void) chmod(filename, (int) stb.st_mode);
2007 		exit(ExitStat);
2008 		/*NOTREACHED*/
2009 	}
2010 	else
2011 	{
2012 		/* parent -- wait for exit status */
2013 		int st;
2014 
2015 		st = waitfor(pid);
2016 		if ((st & 0377) != 0)
2017 			return (EX_UNAVAILABLE);
2018 		else
2019 			return ((st >> 8) & 0377);
2020 		/*NOTREACHED*/
2021 	}
2022 }
2023 /*
2024 **  HOSTSIGNATURE -- return the "signature" for a host.
2025 **
2026 **	The signature describes how we are going to send this -- it
2027 **	can be just the hostname (for non-Internet hosts) or can be
2028 **	an ordered list of MX hosts.
2029 **
2030 **	Parameters:
2031 **		m -- the mailer describing this host.
2032 **		host -- the host name.
2033 **		e -- the current envelope.
2034 **
2035 **	Returns:
2036 **		The signature for this host.
2037 **
2038 **	Side Effects:
2039 **		Can tweak the symbol table.
2040 */
2041 
2042 char *
2043 hostsignature(m, host, e)
2044 	register MAILER *m;
2045 	char *host;
2046 	ENVELOPE *e;
2047 {
2048 	register char *p;
2049 	register STAB *s;
2050 	int i;
2051 	int len;
2052 #ifdef NAMED_BIND
2053 	int nmx;
2054 	auto int rcode;
2055 	char *hp;
2056 	char *endp;
2057 	int oldoptions;
2058 	char *mxhosts[MAXMXHOSTS + 1];
2059 #endif
2060 
2061 	/*
2062 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2063 	*/
2064 
2065 	p = m->m_mailer;
2066 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2067 	{
2068 		/* just an ordinary mailer */
2069 		return host;
2070 	}
2071 
2072 	/*
2073 	**  If it is a numeric address, just return it.
2074 	*/
2075 
2076 	if (host[0] == '[')
2077 		return host;
2078 
2079 	/*
2080 	**  Look it up in the symbol table.
2081 	*/
2082 
2083 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2084 	if (s->s_hostsig != NULL)
2085 		return s->s_hostsig;
2086 
2087 	/*
2088 	**  Not already there -- create a signature.
2089 	*/
2090 
2091 #ifdef NAMED_BIND
2092 	if (ConfigLevel < 2)
2093 	{
2094 		oldoptions = _res.options;
2095 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2096 	}
2097 
2098 	for (hp = host; hp != NULL; hp = endp)
2099 	{
2100 		endp = strchr(hp, ':');
2101 		if (endp != NULL)
2102 			*endp = '\0';
2103 
2104 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2105 
2106 		if (nmx <= 0)
2107 		{
2108 			register MCI *mci;
2109 			extern int errno;
2110 			extern MCI *mci_get();
2111 
2112 			/* update the connection info for this host */
2113 			mci = mci_get(hp, m);
2114 			mci->mci_exitstat = rcode;
2115 			mci->mci_errno = errno;
2116 
2117 			/* and return the original host name as the signature */
2118 			nmx = 1;
2119 			mxhosts[0] = hp;
2120 		}
2121 
2122 		len = 0;
2123 		for (i = 0; i < nmx; i++)
2124 		{
2125 			len += strlen(mxhosts[i]) + 1;
2126 		}
2127 		if (s->s_hostsig != NULL)
2128 			len += strlen(s->s_hostsig) + 1;
2129 		p = xalloc(len);
2130 		if (s->s_hostsig != NULL)
2131 		{
2132 			(void) strcpy(p, s->s_hostsig);
2133 			free(s->s_hostsig);
2134 			s->s_hostsig = p;
2135 			p += strlen(p);
2136 			*p++ = ':';
2137 		}
2138 		else
2139 			s->s_hostsig = p;
2140 		for (i = 0; i < nmx; i++)
2141 		{
2142 			if (i != 0)
2143 				*p++ = ':';
2144 			strcpy(p, mxhosts[i]);
2145 			p += strlen(p);
2146 		}
2147 		if (endp != NULL)
2148 			*endp++ = ':';
2149 	}
2150 	makelower(s->s_hostsig);
2151 	if (ConfigLevel < 2)
2152 		_res.options = oldoptions;
2153 #else
2154 	/* not using BIND -- the signature is just the host name */
2155 	s->s_hostsig = host;
2156 #endif
2157 	if (tTd(17, 1))
2158 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2159 	return s->s_hostsig;
2160 }
2161