1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms are permitted
7  * provided that the above copyright notice and this paragraph are
8  * duplicated in all such forms and that any documentation,
9  * advertising materials, and other materials related to such
10  * distribution and use acknowledge that the software was developed
11  * by the University of California, Berkeley.  The name of the
12  * University may not be used to endorse or promote products derived
13  * from this software without specific prior written permission.
14  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
16  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
17  */
18 
19 #ifndef lint
20 static char sccsid[] = "@(#)deliver.c	5.32 (Berkeley) 04/19/90";
21 #endif /* not lint */
22 
23 #include "sendmail.h"
24 #include <sys/signal.h>
25 #include <sys/stat.h>
26 #include <netdb.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #ifdef NAMED_BIND
30 #include <arpa/nameser.h>
31 #include <resolv.h>
32 #endif
33 
34 /*
35 **  DELIVER -- Deliver a message to a list of addresses.
36 **
37 **	This routine delivers to everyone on the same host as the
38 **	user on the head of the list.  It is clever about mailers
39 **	that don't handle multiple users.  It is NOT guaranteed
40 **	that it will deliver to all these addresses however -- so
41 **	deliver should be called once for each address on the
42 **	list.
43 **
44 **	Parameters:
45 **		e -- the envelope to deliver.
46 **		firstto -- head of the address list to deliver to.
47 **
48 **	Returns:
49 **		zero -- successfully delivered.
50 **		else -- some failure, see ExitStat for more info.
51 **
52 **	Side Effects:
53 **		The standard input is passed off to someone.
54 */
55 
56 deliver(e, firstto)
57 	register ENVELOPE *e;
58 	ADDRESS *firstto;
59 {
60 	char *host;			/* host being sent to */
61 	char *user;			/* user being sent to */
62 	char **pvp;
63 	register char **mvp;
64 	register char *p;
65 	register MAILER *m;		/* mailer for this recipient */
66 	ADDRESS *ctladdr;
67 	register ADDRESS *to = firstto;
68 	bool clever = FALSE;		/* running user smtp to this mailer */
69 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
70 	int rcode;		/* response code */
71 	char *pv[MAXPV+1];
72 	char tobuf[MAXLINE-50];		/* text line of to people */
73 	char buf[MAXNAME];
74 	char tfrombuf[MAXNAME];		/* translated from person */
75 	extern bool checkcompat();
76 	extern ADDRESS *getctladdr();
77 	extern char *remotename();
78 
79 	errno = 0;
80 	if (bitset(QDONTSEND, to->q_flags))
81 		return (0);
82 
83 #ifdef NAMED_BIND
84 	/* unless interactive, try twice, over a minute */
85 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP) {
86 		_res.retrans = 30;
87 		_res.retry = 2;
88 	}
89 #endif
90 
91 	m = to->q_mailer;
92 	host = to->q_host;
93 
94 	if (tTd(10, 1))
95 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
96 			m->m_mno, host, to->q_user);
97 
98 	/*
99 	**  If this mailer is expensive, and if we don't want to make
100 	**  connections now, just mark these addresses and return.
101 	**	This is useful if we want to batch connections to
102 	**	reduce load.  This will cause the messages to be
103 	**	queued up, and a daemon will come along to send the
104 	**	messages later.
105 	**		This should be on a per-mailer basis.
106 	*/
107 
108 	if (NoConnect && !QueueRun && bitnset(M_EXPENSIVE, m->m_flags) &&
109 	    !Verbose)
110 	{
111 		for (; to != NULL; to = to->q_next)
112 		{
113 			if (bitset(QDONTSEND, to->q_flags) || to->q_mailer != m)
114 				continue;
115 			to->q_flags |= QQUEUEUP|QDONTSEND;
116 			e->e_to = to->q_paddr;
117 			message(Arpa_Info, "queued");
118 			if (LogLevel > 4)
119 				logdelivery("queued");
120 		}
121 		e->e_to = NULL;
122 		return (0);
123 	}
124 
125 	/*
126 	**  Do initial argv setup.
127 	**	Insert the mailer name.  Notice that $x expansion is
128 	**	NOT done on the mailer name.  Then, if the mailer has
129 	**	a picky -f flag, we insert it as appropriate.  This
130 	**	code does not check for 'pv' overflow; this places a
131 	**	manifest lower limit of 4 for MAXPV.
132 	**		The from address rewrite is expected to make
133 	**		the address relative to the other end.
134 	*/
135 
136 	/* rewrite from address, using rewriting rules */
137 	expand("\001f", buf, &buf[sizeof buf - 1], e);
138 	(void) strcpy(tfrombuf, remotename(buf, m, TRUE, TRUE));
139 
140 	define('g', tfrombuf, e);		/* translated sender address */
141 	define('h', host, e);			/* to host */
142 	Errors = 0;
143 	pvp = pv;
144 	*pvp++ = m->m_argv[0];
145 
146 	/* insert -f or -r flag as appropriate */
147 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
148 	{
149 		if (bitnset(M_FOPT, m->m_flags))
150 			*pvp++ = "-f";
151 		else
152 			*pvp++ = "-r";
153 		expand("\001g", buf, &buf[sizeof buf - 1], e);
154 		*pvp++ = newstr(buf);
155 	}
156 
157 	/*
158 	**  Append the other fixed parts of the argv.  These run
159 	**  up to the first entry containing "$u".  There can only
160 	**  be one of these, and there are only a few more slots
161 	**  in the pv after it.
162 	*/
163 
164 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
165 	{
166 		while ((p = index(p, '\001')) != NULL)
167 			if (*++p == 'u')
168 				break;
169 		if (p != NULL)
170 			break;
171 
172 		/* this entry is safe -- go ahead and process it */
173 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
174 		*pvp++ = newstr(buf);
175 		if (pvp >= &pv[MAXPV - 3])
176 		{
177 			syserr("Too many parameters to %s before $u", pv[0]);
178 			return (-1);
179 		}
180 	}
181 
182 	/*
183 	**  If we have no substitution for the user name in the argument
184 	**  list, we know that we must supply the names otherwise -- and
185 	**  SMTP is the answer!!
186 	*/
187 
188 	if (*mvp == NULL)
189 	{
190 		/* running SMTP */
191 # ifdef SMTP
192 		clever = TRUE;
193 		*pvp = NULL;
194 # else SMTP
195 		/* oops!  we don't implement SMTP */
196 		syserr("SMTP style mailer");
197 		return (EX_SOFTWARE);
198 # endif SMTP
199 	}
200 
201 	/*
202 	**  At this point *mvp points to the argument with $u.  We
203 	**  run through our address list and append all the addresses
204 	**  we can.  If we run out of space, do not fret!  We can
205 	**  always send another copy later.
206 	*/
207 
208 	tobuf[0] = '\0';
209 	e->e_to = tobuf;
210 	ctladdr = NULL;
211 	for (; to != NULL; to = to->q_next)
212 	{
213 		/* avoid sending multiple recipients to dumb mailers */
214 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
215 			break;
216 
217 		/* if already sent or not for this host, don't send */
218 		if (bitset(QDONTSEND, to->q_flags) ||
219 		    strcmp(to->q_host, host) != 0 ||
220 		    to->q_mailer != firstto->q_mailer)
221 			continue;
222 
223 		/* avoid overflowing tobuf */
224 		if (sizeof tobuf - (strlen(to->q_paddr) + strlen(tobuf) + 2) < 0)
225 			break;
226 
227 		if (tTd(10, 1))
228 		{
229 			printf("\nsend to ");
230 			printaddr(to, FALSE);
231 		}
232 
233 		/* compute effective uid/gid when sending */
234 		if (to->q_mailer == ProgMailer)
235 			ctladdr = getctladdr(to);
236 
237 		user = to->q_user;
238 		e->e_to = to->q_paddr;
239 		to->q_flags |= QDONTSEND;
240 
241 		/*
242 		**  Check to see that these people are allowed to
243 		**  talk to each other.
244 		*/
245 
246 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
247 		{
248 			NoReturn = TRUE;
249 			usrerr("Message is too large; %ld bytes max", m->m_maxsize);
250 			giveresponse(EX_UNAVAILABLE, m, e);
251 			continue;
252 		}
253 		if (!checkcompat(to))
254 		{
255 			giveresponse(EX_UNAVAILABLE, m, e);
256 			continue;
257 		}
258 
259 		/*
260 		**  Strip quote bits from names if the mailer is dumb
261 		**	about them.
262 		*/
263 
264 		if (bitnset(M_STRIPQ, m->m_flags))
265 		{
266 			stripquotes(user, TRUE);
267 			stripquotes(host, TRUE);
268 		}
269 		else
270 		{
271 			stripquotes(user, FALSE);
272 			stripquotes(host, FALSE);
273 		}
274 
275 		/* hack attack -- delivermail compatibility */
276 		if (m == ProgMailer && *user == '|')
277 			user++;
278 
279 		/*
280 		**  If an error message has already been given, don't
281 		**	bother to send to this address.
282 		**
283 		**	>>>>>>>>>> This clause assumes that the local mailer
284 		**	>> NOTE >> cannot do any further aliasing; that
285 		**	>>>>>>>>>> function is subsumed by sendmail.
286 		*/
287 
288 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
289 			continue;
290 
291 		/* save statistics.... */
292 		markstats(e, to);
293 
294 		/*
295 		**  See if this user name is "special".
296 		**	If the user name has a slash in it, assume that this
297 		**	is a file -- send it off without further ado.  Note
298 		**	that this type of addresses is not processed along
299 		**	with the others, so we fudge on the To person.
300 		*/
301 
302 		if (m == LocalMailer)
303 		{
304 			if (user[0] == '/')
305 			{
306 				rcode = mailfile(user, getctladdr(to));
307 				giveresponse(rcode, m, e);
308 				continue;
309 			}
310 		}
311 
312 		/*
313 		**  Address is verified -- add this user to mailer
314 		**  argv, and add it to the print list of recipients.
315 		*/
316 
317 		/* link together the chain of recipients */
318 		to->q_tchain = tochain;
319 		tochain = to;
320 
321 		/* create list of users for error messages */
322 		(void) strcat(tobuf, ",");
323 		(void) strcat(tobuf, to->q_paddr);
324 		define('u', user, e);		/* to user */
325 		define('z', to->q_home, e);	/* user's home */
326 
327 		/*
328 		**  Expand out this user into argument list.
329 		*/
330 
331 		if (!clever)
332 		{
333 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
334 			*pvp++ = newstr(buf);
335 			if (pvp >= &pv[MAXPV - 2])
336 			{
337 				/* allow some space for trailing parms */
338 				break;
339 			}
340 		}
341 	}
342 
343 	/* see if any addresses still exist */
344 	if (tobuf[0] == '\0')
345 	{
346 		define('g', (char *) NULL, e);
347 		return (0);
348 	}
349 
350 	/* print out messages as full list */
351 	e->e_to = tobuf + 1;
352 
353 	/*
354 	**  Fill out any parameters after the $u parameter.
355 	*/
356 
357 	while (!clever && *++mvp != NULL)
358 	{
359 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
360 		*pvp++ = newstr(buf);
361 		if (pvp >= &pv[MAXPV])
362 			syserr("deliver: pv overflow after $u for %s", pv[0]);
363 	}
364 	*pvp++ = NULL;
365 
366 	/*
367 	**  Call the mailer.
368 	**	The argument vector gets built, pipes
369 	**	are created as necessary, and we fork & exec as
370 	**	appropriate.
371 	**	If we are running SMTP, we just need to clean up.
372 	*/
373 
374 #ifdef NAMED_BIND
375 	_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);		/* XXX */
376 #endif
377 #ifdef SMTP
378 	if (clever)
379 	{
380 		rcode = EX_OK;
381 #ifdef NAMED_BIND
382 		if (host[0] && host[0] != '[')
383 		{
384 			expand("\001w", buf, &buf[sizeof(buf) - 1], e);
385 			Nmx = getmxrr(host, MxHosts, buf, &rcode);
386 		}
387 		else
388 #endif
389 		{
390 			Nmx = 1;
391 			MxHosts[0] = host;
392 		}
393 		if (Nmx >= 0)
394 		{
395 			message(Arpa_Info, "Connecting to %s (%s)...",
396 			    MxHosts[0], m->m_name);
397 			if ((rcode = smtpinit(m, pv)) == EX_OK) {
398 				register char *t = tobuf;
399 				register int i;
400 
401 				/* send the recipient list */
402 				tobuf[0] = '\0';
403 				for (to = tochain; to; to = to->q_tchain) {
404 					e->e_to = to->q_paddr;
405 					if ((i = smtprcpt(to, m)) != EX_OK) {
406 						markfailure(e, to, i);
407 						giveresponse(i, m, e);
408 					}
409 					else {
410 						*t++ = ',';
411 						for (p = to->q_paddr; *p; *t++ = *p++);
412 					}
413 				}
414 
415 				/* now send the data */
416 				if (tobuf[0] == '\0')
417 					e->e_to = NULL;
418 				else {
419 					e->e_to = tobuf + 1;
420 					rcode = smtpdata(m, e);
421 				}
422 
423 				/* now close the connection */
424 				smtpquit(m);
425 			}
426 		}
427 	}
428 	else
429 #endif /* SMTP */
430 	{
431 		message(Arpa_Info, "Connecting to %s (%s)...", host, m->m_name);
432 		rcode = sendoff(e, m, pv, ctladdr);
433 	}
434 #ifdef NAMED_BIND
435 	_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
436 #endif
437 
438 	/*
439 	**  Do final status disposal.
440 	**	We check for something in tobuf for the SMTP case.
441 	**	If we got a temporary failure, arrange to queue the
442 	**		addressees.
443 	*/
444 
445 	if (tobuf[0] != '\0')
446 		giveresponse(rcode, m, e);
447 	if (rcode != EX_OK)
448 		for (to = tochain; to != NULL; to = to->q_tchain)
449 			markfailure(e, to, rcode);
450 
451 	errno = 0;
452 	define('g', (char *) NULL, e);
453 	return (rcode);
454 }
455 /*
456 **  MARKFAILURE -- mark a failure on a specific address.
457 **
458 **	Parameters:
459 **		e -- the envelope we are sending.
460 **		q -- the address to mark.
461 **		rcode -- the code signifying the particular failure.
462 **
463 **	Returns:
464 **		none.
465 **
466 **	Side Effects:
467 **		marks the address (and possibly the envelope) with the
468 **			failure so that an error will be returned or
469 **			the message will be queued, as appropriate.
470 */
471 
472 markfailure(e, q, rcode)
473 	register ENVELOPE *e;
474 	register ADDRESS *q;
475 	int rcode;
476 {
477 	if (rcode == EX_OK)
478 		return;
479 	else if (rcode != EX_TEMPFAIL)
480 		q->q_flags |= QBADADDR;
481 	else if (curtime() > e->e_ctime + TimeOut)
482 	{
483 		extern char *pintvl();
484 		char buf[MAXLINE];
485 
486 		if (!bitset(EF_TIMEOUT, e->e_flags))
487 		{
488 			(void) sprintf(buf, "Cannot send message for %s",
489 				pintvl(TimeOut, FALSE));
490 			if (e->e_message != NULL)
491 				free(e->e_message);
492 			e->e_message = newstr(buf);
493 			message(Arpa_Info, buf);
494 		}
495 		q->q_flags |= QBADADDR;
496 		e->e_flags |= EF_TIMEOUT;
497 	}
498 	else
499 		q->q_flags |= QQUEUEUP;
500 }
501 /*
502 **  DOFORK -- do a fork, retrying a couple of times on failure.
503 **
504 **	This MUST be a macro, since after a vfork we are running
505 **	two processes on the same stack!!!
506 **
507 **	Parameters:
508 **		none.
509 **
510 **	Returns:
511 **		From a macro???  You've got to be kidding!
512 **
513 **	Side Effects:
514 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
515 **			pid of child in parent, zero in child.
516 **			-1 on unrecoverable error.
517 **
518 **	Notes:
519 **		I'm awfully sorry this looks so awful.  That's
520 **		vfork for you.....
521 */
522 
523 # define NFORKTRIES	5
524 # ifdef VMUNIX
525 # define XFORK	vfork
526 # else VMUNIX
527 # define XFORK	fork
528 # endif VMUNIX
529 
530 # define DOFORK(fORKfN) \
531 {\
532 	register int i;\
533 \
534 	for (i = NFORKTRIES; --i >= 0; )\
535 	{\
536 		pid = fORKfN();\
537 		if (pid >= 0)\
538 			break;\
539 		if (i > 0)\
540 			sleep((unsigned) NFORKTRIES - i);\
541 	}\
542 }
543 /*
544 **  DOFORK -- simple fork interface to DOFORK.
545 **
546 **	Parameters:
547 **		none.
548 **
549 **	Returns:
550 **		pid of child in parent.
551 **		zero in child.
552 **		-1 on error.
553 **
554 **	Side Effects:
555 **		returns twice, once in parent and once in child.
556 */
557 
558 dofork()
559 {
560 	register int pid;
561 
562 	DOFORK(fork);
563 	return (pid);
564 }
565 /*
566 **  SENDOFF -- send off call to mailer & collect response.
567 **
568 **	Parameters:
569 **		e -- the envelope to mail.
570 **		m -- mailer descriptor.
571 **		pvp -- parameter vector to send to it.
572 **		ctladdr -- an address pointer controlling the
573 **			user/groupid etc. of the mailer.
574 **
575 **	Returns:
576 **		exit status of mailer.
577 **
578 **	Side Effects:
579 **		none.
580 */
581 static
582 sendoff(e, m, pvp, ctladdr)
583 	register ENVELOPE *e;
584 	MAILER *m;
585 	char **pvp;
586 	ADDRESS *ctladdr;
587 {
588 	auto FILE *mfile;
589 	auto FILE *rfile;
590 	register int i;
591 	int pid;
592 
593 	/*
594 	**  Create connection to mailer.
595 	*/
596 
597 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
598 	if (pid < 0)
599 		return (-1);
600 
601 	/*
602 	**  Format and send message.
603 	*/
604 
605 	putfromline(mfile, m);
606 	(*e->e_puthdr)(mfile, m, e);
607 	putline("\n", mfile, m);
608 	(*e->e_putbody)(mfile, m, e);
609 	(void) fclose(mfile);
610 
611 	i = endmailer(pid, pvp[0]);
612 
613 	/* arrange a return receipt if requested */
614 	if (e->e_receiptto != NULL && bitnset(M_LOCAL, m->m_flags))
615 	{
616 		e->e_flags |= EF_SENDRECEIPT;
617 		/* do we want to send back more info? */
618 	}
619 
620 	return (i);
621 }
622 /*
623 **  ENDMAILER -- Wait for mailer to terminate.
624 **
625 **	We should never get fatal errors (e.g., segmentation
626 **	violation), so we report those specially.  For other
627 **	errors, we choose a status message (into statmsg),
628 **	and if it represents an error, we print it.
629 **
630 **	Parameters:
631 **		pid -- pid of mailer.
632 **		name -- name of mailer (for error messages).
633 **
634 **	Returns:
635 **		exit code of mailer.
636 **
637 **	Side Effects:
638 **		none.
639 */
640 
641 endmailer(pid, name)
642 	int pid;
643 	char *name;
644 {
645 	int st;
646 
647 	/* in the IPC case there is nothing to wait for */
648 	if (pid == 0)
649 		return (EX_OK);
650 
651 	/* wait for the mailer process to die and collect status */
652 	st = waitfor(pid);
653 	if (st == -1)
654 	{
655 		syserr("endmailer %s: wait", name);
656 		return (EX_SOFTWARE);
657 	}
658 
659 	/* see if it died a horrid death */
660 	if ((st & 0377) != 0)
661 	{
662 		syserr("mailer %s died with signal %o", name, st);
663 		ExitStat = EX_TEMPFAIL;
664 		return (EX_TEMPFAIL);
665 	}
666 
667 	/* normal death -- return status */
668 	st = (st >> 8) & 0377;
669 	return (st);
670 }
671 /*
672 **  OPENMAILER -- open connection to mailer.
673 **
674 **	Parameters:
675 **		m -- mailer descriptor.
676 **		pvp -- parameter vector to pass to mailer.
677 **		ctladdr -- controlling address for user.
678 **		clever -- create a full duplex connection.
679 **		pmfile -- pointer to mfile (to mailer) connection.
680 **		prfile -- pointer to rfile (from mailer) connection.
681 **
682 **	Returns:
683 **		pid of mailer ( > 0 ).
684 **		-1 on error.
685 **		zero on an IPC connection.
686 **
687 **	Side Effects:
688 **		creates a mailer in a subprocess.
689 */
690 
691 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
692 	MAILER *m;
693 	char **pvp;
694 	ADDRESS *ctladdr;
695 	bool clever;
696 	FILE **pmfile;
697 	FILE **prfile;
698 {
699 	int pid;
700 	int mpvect[2];
701 	int rpvect[2];
702 	FILE *mfile = NULL;
703 	FILE *rfile = NULL;
704 	extern FILE *fdopen();
705 
706 	if (tTd(11, 1))
707 	{
708 		printf("openmailer:");
709 		printav(pvp);
710 	}
711 	errno = 0;
712 
713 	CurHostName = m->m_mailer;
714 
715 	/*
716 	**  Deal with the special case of mail handled through an IPC
717 	**  connection.
718 	**	In this case we don't actually fork.  We must be
719 	**	running SMTP for this to work.  We will return a
720 	**	zero pid to indicate that we are running IPC.
721 	**  We also handle a debug version that just talks to stdin/out.
722 	*/
723 
724 	/* check for Local Person Communication -- not for mortals!!! */
725 	if (strcmp(m->m_mailer, "[LPC]") == 0)
726 	{
727 		*pmfile = stdout;
728 		*prfile = stdin;
729 		return (0);
730 	}
731 
732 	if (strcmp(m->m_mailer, "[IPC]") == 0)
733 	{
734 #ifdef HOSTINFO
735 		register STAB *st;
736 		extern STAB *stab();
737 #endif HOSTINFO
738 #ifdef DAEMON
739 		register int i, j;
740 		register u_short port;
741 
742 		CurHostName = pvp[1];
743 		if (!clever)
744 			syserr("non-clever IPC");
745 		if (pvp[2] != NULL)
746 			port = atoi(pvp[2]);
747 		else
748 			port = 0;
749 		for (j = 0; j < Nmx; j++)
750 		{
751 			CurHostName = MxHosts[j];
752 #ifdef HOSTINFO
753 		/* see if we have already determined that this host is fried */
754 			st = stab(MxHosts[j], ST_HOST, ST_FIND);
755 			if (st == NULL || st->s_host.ho_exitstat == EX_OK) {
756 				if (j > 1)
757 					message(Arpa_Info,
758 					    "Connecting to %s (%s)...",
759 					    MxHosts[j], m->m_name);
760 				i = makeconnection(MxHosts[j], port, pmfile, prfile);
761 			}
762 			else
763 			{
764 				i = st->s_host.ho_exitstat;
765 				errno = st->s_host.ho_errno;
766 			}
767 #else HOSTINFO
768 			i = makeconnection(MxHosts[j], port, pmfile, prfile);
769 #endif HOSTINFO
770 			if (i != EX_OK)
771 			{
772 #ifdef HOSTINFO
773 				/* enter status of this host */
774 				if (st == NULL)
775 					st = stab(MxHosts[j], ST_HOST, ST_ENTER);
776 				st->s_host.ho_exitstat = i;
777 				st->s_host.ho_errno = errno;
778 #endif HOSTINFO
779 				ExitStat = i;
780 				continue;
781 			}
782 			else
783 				return (0);
784 		}
785 		return (-1);
786 #else DAEMON
787 		syserr("openmailer: no IPC");
788 		return (-1);
789 #endif DAEMON
790 	}
791 
792 	/* create a pipe to shove the mail through */
793 	if (pipe(mpvect) < 0)
794 	{
795 		syserr("openmailer: pipe (to mailer)");
796 		return (-1);
797 	}
798 
799 #ifdef SMTP
800 	/* if this mailer speaks smtp, create a return pipe */
801 	if (clever && pipe(rpvect) < 0)
802 	{
803 		syserr("openmailer: pipe (from mailer)");
804 		(void) close(mpvect[0]);
805 		(void) close(mpvect[1]);
806 		return (-1);
807 	}
808 #endif SMTP
809 
810 	/*
811 	**  Actually fork the mailer process.
812 	**	DOFORK is clever about retrying.
813 	**
814 	**	Dispose of SIGCHLD signal catchers that may be laying
815 	**	around so that endmail will get it.
816 	*/
817 
818 	if (CurEnv->e_xfp != NULL)
819 		(void) fflush(CurEnv->e_xfp);		/* for debugging */
820 	(void) fflush(stdout);
821 # ifdef SIGCHLD
822 	(void) signal(SIGCHLD, SIG_DFL);
823 # endif SIGCHLD
824 	DOFORK(XFORK);
825 	/* pid is set by DOFORK */
826 	if (pid < 0)
827 	{
828 		/* failure */
829 		syserr("openmailer: cannot fork");
830 		(void) close(mpvect[0]);
831 		(void) close(mpvect[1]);
832 #ifdef SMTP
833 		if (clever)
834 		{
835 			(void) close(rpvect[0]);
836 			(void) close(rpvect[1]);
837 		}
838 #endif SMTP
839 		return (-1);
840 	}
841 	else if (pid == 0)
842 	{
843 		int i;
844 		extern int DtableSize;
845 
846 		/* child -- set up input & exec mailer */
847 		/* make diagnostic output be standard output */
848 		(void) signal(SIGINT, SIG_IGN);
849 		(void) signal(SIGHUP, SIG_IGN);
850 		(void) signal(SIGTERM, SIG_DFL);
851 
852 		/* arrange to filter standard & diag output of command */
853 		if (clever)
854 		{
855 			(void) close(rpvect[0]);
856 			(void) close(1);
857 			(void) dup(rpvect[1]);
858 			(void) close(rpvect[1]);
859 		}
860 		else if (OpMode == MD_SMTP || HoldErrs)
861 		{
862 			/* put mailer output in transcript */
863 			(void) close(1);
864 			(void) dup(fileno(CurEnv->e_xfp));
865 		}
866 		(void) close(2);
867 		(void) dup(1);
868 
869 		/* arrange to get standard input */
870 		(void) close(mpvect[1]);
871 		(void) close(0);
872 		if (dup(mpvect[0]) < 0)
873 		{
874 			syserr("Cannot dup to zero!");
875 			_exit(EX_OSERR);
876 		}
877 		(void) close(mpvect[0]);
878 		if (!bitnset(M_RESTR, m->m_flags))
879 		{
880 			if (ctladdr == NULL || ctladdr->q_uid == 0)
881 			{
882 				(void) setgid(DefGid);
883 				(void) initgroups(DefUser, DefGid);
884 				(void) setuid(DefUid);
885 			}
886 			else
887 			{
888 				(void) setgid(ctladdr->q_gid);
889 				(void) initgroups(ctladdr->q_ruser?
890 					ctladdr->q_ruser: ctladdr->q_user,
891 					ctladdr->q_gid);
892 				(void) setuid(ctladdr->q_uid);
893 			}
894 		}
895 
896 		/* arrange for all the files to be closed */
897 		for (i = 3; i < DtableSize; i++) {
898 			register int j;
899 			if ((j = fcntl(i, F_GETFD, 0)) != -1)
900 				(void)fcntl(i, F_SETFD, j|1);
901 		}
902 
903 		/* try to execute the mailer */
904 		execve(m->m_mailer, pvp, UserEnviron);
905 		syserr("Cannot exec %s", m->m_mailer);
906 		if (m == LocalMailer || errno == EIO || errno == EAGAIN ||
907 		    errno == ENOMEM || errno == EPROCLIM)
908 			_exit(EX_TEMPFAIL);
909 		else
910 			_exit(EX_UNAVAILABLE);
911 	}
912 
913 	/*
914 	**  Set up return value.
915 	*/
916 
917 	(void) close(mpvect[0]);
918 	mfile = fdopen(mpvect[1], "w");
919 	if (clever)
920 	{
921 		(void) close(rpvect[1]);
922 		rfile = fdopen(rpvect[0], "r");
923 	}
924 
925 	*pmfile = mfile;
926 	*prfile = rfile;
927 
928 	return (pid);
929 }
930 /*
931 **  GIVERESPONSE -- Interpret an error response from a mailer
932 **
933 **	Parameters:
934 **		stat -- the status code from the mailer (high byte
935 **			only; core dumps must have been taken care of
936 **			already).
937 **		m -- the mailer descriptor for this mailer.
938 **
939 **	Returns:
940 **		none.
941 **
942 **	Side Effects:
943 **		Errors may be incremented.
944 **		ExitStat may be set.
945 */
946 
947 giveresponse(stat, m, e)
948 	int stat;
949 	register MAILER *m;
950 	ENVELOPE *e;
951 {
952 	register char *statmsg;
953 	extern char *SysExMsg[];
954 	register int i;
955 	extern int N_SysEx;
956 #ifdef NAMED_BIND
957 	extern int h_errno;
958 #endif
959 	char buf[MAXLINE];
960 
961 #ifdef lint
962 	if (m == NULL)
963 		return;
964 #endif lint
965 
966 	/*
967 	**  Compute status message from code.
968 	*/
969 
970 	i = stat - EX__BASE;
971 	if (stat == 0)
972 		statmsg = "250 Sent";
973 	else if (i < 0 || i > N_SysEx)
974 	{
975 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
976 		stat = EX_UNAVAILABLE;
977 		statmsg = buf;
978 	}
979 	else if (stat == EX_TEMPFAIL)
980 	{
981 		(void) strcpy(buf, SysExMsg[i]);
982 #ifdef NAMED_BIND
983 		if (h_errno == TRY_AGAIN)
984 		{
985 			extern char *errstring();
986 
987 			statmsg = errstring(h_errno+MAX_ERRNO);
988 		}
989 		else
990 #endif
991 		{
992 			if (errno != 0)
993 			{
994 				extern char *errstring();
995 
996 				statmsg = errstring(errno);
997 			}
998 			else
999 			{
1000 #ifdef SMTP
1001 				extern char SmtpError[];
1002 
1003 				statmsg = SmtpError;
1004 #else SMTP
1005 				statmsg = NULL;
1006 #endif SMTP
1007 			}
1008 		}
1009 		if (statmsg != NULL && statmsg[0] != '\0')
1010 		{
1011 			(void) strcat(buf, ": ");
1012 			(void) strcat(buf, statmsg);
1013 		}
1014 		statmsg = buf;
1015 	}
1016 	else
1017 	{
1018 		statmsg = SysExMsg[i];
1019 	}
1020 
1021 	/*
1022 	**  Print the message as appropriate
1023 	*/
1024 
1025 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1026 		message(Arpa_Info, &statmsg[4]);
1027 	else
1028 	{
1029 		Errors++;
1030 		usrerr(statmsg);
1031 	}
1032 
1033 	/*
1034 	**  Final cleanup.
1035 	**	Log a record of the transaction.  Compute the new
1036 	**	ExitStat -- if we already had an error, stick with
1037 	**	that.
1038 	*/
1039 
1040 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
1041 		logdelivery(&statmsg[4]);
1042 
1043 	if (stat != EX_TEMPFAIL)
1044 		setstat(stat);
1045 	if (stat != EX_OK)
1046 	{
1047 		if (e->e_message != NULL)
1048 			free(e->e_message);
1049 		e->e_message = newstr(&statmsg[4]);
1050 	}
1051 	errno = 0;
1052 #ifdef NAMED_BIND
1053 	h_errno = 0;
1054 #endif
1055 }
1056 /*
1057 **  LOGDELIVERY -- log the delivery in the system log
1058 **
1059 **	Parameters:
1060 **		stat -- the message to print for the status
1061 **
1062 **	Returns:
1063 **		none
1064 **
1065 **	Side Effects:
1066 **		none
1067 */
1068 
1069 logdelivery(stat)
1070 	char *stat;
1071 {
1072 	extern char *pintvl();
1073 
1074 # ifdef LOG
1075 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", CurEnv->e_id,
1076 	       CurEnv->e_to, pintvl(curtime() - CurEnv->e_ctime, TRUE), stat);
1077 # endif LOG
1078 }
1079 /*
1080 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1081 **
1082 **	This can be made an arbitrary message separator by changing $l
1083 **
1084 **	One of the ugliest hacks seen by human eyes is contained herein:
1085 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1086 **	does a well-meaning programmer such as myself have to deal with
1087 **	this kind of antique garbage????
1088 **
1089 **	Parameters:
1090 **		fp -- the file to output to.
1091 **		m -- the mailer describing this entry.
1092 **
1093 **	Returns:
1094 **		none
1095 **
1096 **	Side Effects:
1097 **		outputs some text to fp.
1098 */
1099 
1100 putfromline(fp, m)
1101 	register FILE *fp;
1102 	register MAILER *m;
1103 {
1104 	char *template = "\001l\n";
1105 	char buf[MAXLINE];
1106 
1107 	if (bitnset(M_NHDR, m->m_flags))
1108 		return;
1109 
1110 # ifdef UGLYUUCP
1111 	if (bitnset(M_UGLYUUCP, m->m_flags))
1112 	{
1113 		char *bang;
1114 		char xbuf[MAXLINE];
1115 
1116 		expand("\001g", buf, &buf[sizeof buf - 1], CurEnv);
1117 		bang = index(buf, '!');
1118 		if (bang == NULL)
1119 			syserr("No ! in UUCP! (%s)", buf);
1120 		else
1121 		{
1122 			*bang++ = '\0';
1123 			(void) sprintf(xbuf, "From %s  \001d remote from %s\n", bang, buf);
1124 			template = xbuf;
1125 		}
1126 	}
1127 # endif UGLYUUCP
1128 	expand(template, buf, &buf[sizeof buf - 1], CurEnv);
1129 	putline(buf, fp, m);
1130 }
1131 /*
1132 **  PUTBODY -- put the body of a message.
1133 **
1134 **	Parameters:
1135 **		fp -- file to output onto.
1136 **		m -- a mailer descriptor to control output format.
1137 **		e -- the envelope to put out.
1138 **
1139 **	Returns:
1140 **		none.
1141 **
1142 **	Side Effects:
1143 **		The message is written onto fp.
1144 */
1145 
1146 putbody(fp, m, e)
1147 	FILE *fp;
1148 	MAILER *m;
1149 	register ENVELOPE *e;
1150 {
1151 	char buf[MAXLINE];
1152 
1153 	/*
1154 	**  Output the body of the message
1155 	*/
1156 
1157 	if (e->e_dfp == NULL)
1158 	{
1159 		if (e->e_df != NULL)
1160 		{
1161 			e->e_dfp = fopen(e->e_df, "r");
1162 			if (e->e_dfp == NULL)
1163 				syserr("putbody: Cannot open %s for %s from %s",
1164 				e->e_df, e->e_to, e->e_from);
1165 		}
1166 		else
1167 			putline("<<< No Message Collected >>>", fp, m);
1168 	}
1169 	if (e->e_dfp != NULL)
1170 	{
1171 		rewind(e->e_dfp);
1172 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1173 		{
1174 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1175 			    strncmp(buf, "From", 4) == 0)
1176 				(void) putc('>', fp);
1177 			putline(buf, fp, m);
1178 		}
1179 
1180 		if (ferror(e->e_dfp))
1181 		{
1182 			syserr("putbody: read error");
1183 			ExitStat = EX_IOERR;
1184 		}
1185 	}
1186 
1187 	(void) fflush(fp);
1188 	if (ferror(fp) && errno != EPIPE)
1189 	{
1190 		syserr("putbody: write error");
1191 		ExitStat = EX_IOERR;
1192 	}
1193 	errno = 0;
1194 }
1195 /*
1196 **  MAILFILE -- Send a message to a file.
1197 **
1198 **	If the file has the setuid/setgid bits set, but NO execute
1199 **	bits, sendmail will try to become the owner of that file
1200 **	rather than the real user.  Obviously, this only works if
1201 **	sendmail runs as root.
1202 **
1203 **	This could be done as a subordinate mailer, except that it
1204 **	is used implicitly to save messages in ~/dead.letter.  We
1205 **	view this as being sufficiently important as to include it
1206 **	here.  For example, if the system is dying, we shouldn't have
1207 **	to create another process plus some pipes to save the message.
1208 **
1209 **	Parameters:
1210 **		filename -- the name of the file to send to.
1211 **		ctladdr -- the controlling address header -- includes
1212 **			the userid/groupid to be when sending.
1213 **
1214 **	Returns:
1215 **		The exit code associated with the operation.
1216 **
1217 **	Side Effects:
1218 **		none.
1219 */
1220 
1221 mailfile(filename, ctladdr)
1222 	char *filename;
1223 	ADDRESS *ctladdr;
1224 {
1225 	register FILE *f;
1226 	register int pid;
1227 	ENVELOPE *e = CurEnv;
1228 
1229 	/*
1230 	**  Fork so we can change permissions here.
1231 	**	Note that we MUST use fork, not vfork, because of
1232 	**	the complications of calling subroutines, etc.
1233 	*/
1234 
1235 	DOFORK(fork);
1236 
1237 	if (pid < 0)
1238 		return (EX_OSERR);
1239 	else if (pid == 0)
1240 	{
1241 		/* child -- actually write to file */
1242 		struct stat stb;
1243 
1244 		(void) signal(SIGINT, SIG_DFL);
1245 		(void) signal(SIGHUP, SIG_DFL);
1246 		(void) signal(SIGTERM, SIG_DFL);
1247 		(void) umask(OldUmask);
1248 		if (stat(filename, &stb) < 0)
1249 		{
1250 			errno = 0;
1251 			stb.st_mode = 0666;
1252 		}
1253 		if (bitset(0111, stb.st_mode))
1254 			exit(EX_CANTCREAT);
1255 		if (ctladdr == NULL)
1256 			ctladdr = &e->e_from;
1257 		/* we have to open the dfile BEFORE setuid */
1258 		if (e->e_dfp == NULL &&  e->e_df != NULL)
1259 		{
1260 			e->e_dfp = fopen(e->e_df, "r");
1261 			if (e->e_dfp == NULL) {
1262 				syserr("mailfile: Cannot open %s for %s from %s",
1263 				e->e_df, e->e_to, e->e_from);
1264 			}
1265 		}
1266 
1267 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1268 		{
1269 			if (ctladdr->q_uid == 0) {
1270 				(void) setgid(DefGid);
1271 				(void) initgroups(DefUser, DefGid);
1272 			} else {
1273 				(void) setgid(ctladdr->q_gid);
1274 				(void) initgroups(ctladdr->q_ruser?
1275 					ctladdr->q_ruser: ctladdr->q_user,
1276 					ctladdr->q_gid);
1277 			}
1278 		}
1279 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1280 		{
1281 			if (ctladdr->q_uid == 0)
1282 				(void) setuid(DefUid);
1283 			else
1284 				(void) setuid(ctladdr->q_uid);
1285 		}
1286 		f = dfopen(filename, "a");
1287 		if (f == NULL)
1288 			exit(EX_CANTCREAT);
1289 
1290 		putfromline(f, ProgMailer);
1291 		(*CurEnv->e_puthdr)(f, ProgMailer, CurEnv);
1292 		putline("\n", f, ProgMailer);
1293 		(*CurEnv->e_putbody)(f, ProgMailer, CurEnv);
1294 		putline("\n", f, ProgMailer);
1295 		(void) fclose(f);
1296 		(void) fflush(stdout);
1297 
1298 		/* reset ISUID & ISGID bits for paranoid systems */
1299 		(void) chmod(filename, (int) stb.st_mode);
1300 		exit(EX_OK);
1301 		/*NOTREACHED*/
1302 	}
1303 	else
1304 	{
1305 		/* parent -- wait for exit status */
1306 		int st;
1307 
1308 		st = waitfor(pid);
1309 		if ((st & 0377) != 0)
1310 			return (EX_UNAVAILABLE);
1311 		else
1312 			return ((st >> 8) & 0377);
1313 		/*NOTREACHED*/
1314 	}
1315 }
1316 /*
1317 **  SENDALL -- actually send all the messages.
1318 **
1319 **	Parameters:
1320 **		e -- the envelope to send.
1321 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
1322 **			the current SendMode.
1323 **
1324 **	Returns:
1325 **		none.
1326 **
1327 **	Side Effects:
1328 **		Scans the send lists and sends everything it finds.
1329 **		Delivers any appropriate error messages.
1330 **		If we are running in a non-interactive mode, takes the
1331 **			appropriate action.
1332 */
1333 
1334 sendall(e, mode)
1335 	ENVELOPE *e;
1336 	char mode;
1337 {
1338 	register ADDRESS *q;
1339 	bool oldverbose;
1340 	int pid;
1341 	FILE *lockfp = NULL, *queueup();
1342 
1343 	/* determine actual delivery mode */
1344 	if (mode == SM_DEFAULT)
1345 	{
1346 		extern bool shouldqueue();
1347 
1348 		if (shouldqueue(e->e_msgpriority))
1349 			mode = SM_QUEUE;
1350 		else
1351 			mode = SendMode;
1352 	}
1353 
1354 	if (tTd(13, 1))
1355 	{
1356 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1357 		printaddr(e->e_sendqueue, TRUE);
1358 	}
1359 
1360 	/*
1361 	**  Do any preprocessing necessary for the mode we are running.
1362 	**	Check to make sure the hop count is reasonable.
1363 	**	Delete sends to the sender in mailing lists.
1364 	*/
1365 
1366 	CurEnv = e;
1367 
1368 	if (e->e_hopcount > MAXHOP)
1369 	{
1370 		errno = 0;
1371 		syserr("sendall: too many hops %d (%d max): from %s, to %s",
1372 			e->e_hopcount, MAXHOP, e->e_from, e->e_to);
1373 		return;
1374 	}
1375 
1376 	if (!MeToo)
1377 	{
1378 		extern ADDRESS *recipient();
1379 
1380 		e->e_from.q_flags |= QDONTSEND;
1381 		(void) recipient(&e->e_from, &e->e_sendqueue);
1382 	}
1383 
1384 # ifdef QUEUE
1385 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1386 	     (mode != SM_VERIFY && SuperSafe)) &&
1387 	    !bitset(EF_INQUEUE, e->e_flags))
1388 		lockfp = queueup(e, TRUE, mode == SM_QUEUE);
1389 #endif QUEUE
1390 
1391 	oldverbose = Verbose;
1392 	switch (mode)
1393 	{
1394 	  case SM_VERIFY:
1395 		Verbose = TRUE;
1396 		break;
1397 
1398 	  case SM_QUEUE:
1399 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1400 		return;
1401 
1402 	  case SM_FORK:
1403 		if (e->e_xfp != NULL)
1404 			(void) fflush(e->e_xfp);
1405 		pid = fork();
1406 		if (pid < 0)
1407 		{
1408 			mode = SM_DELIVER;
1409 			break;
1410 		}
1411 		else if (pid > 0)
1412 		{
1413 			/* be sure we leave the temp files to our child */
1414 			e->e_id = e->e_df = NULL;
1415 			if (lockfp != NULL)
1416 				(void) fclose(lockfp);
1417 			return;
1418 		}
1419 
1420 		/* double fork to avoid zombies */
1421 		if (fork() > 0)
1422 			exit(EX_OK);
1423 
1424 		/* be sure we are immune from the terminal */
1425 		disconnect(FALSE);
1426 
1427 		break;
1428 	}
1429 
1430 	/*
1431 	**  Run through the list and send everything.
1432 	*/
1433 
1434 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1435 	{
1436 		if (mode == SM_VERIFY)
1437 		{
1438 			e->e_to = q->q_paddr;
1439 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1440 				message(Arpa_Info, "deliverable");
1441 		}
1442 		else
1443 			(void) deliver(e, q);
1444 	}
1445 	Verbose = oldverbose;
1446 
1447 	/*
1448 	**  Now run through and check for errors.
1449 	*/
1450 
1451 	if (mode == SM_VERIFY) {
1452 		if (lockfp != NULL)
1453 			(void) fclose(lockfp);
1454 		return;
1455 	}
1456 
1457 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1458 	{
1459 		register ADDRESS *qq;
1460 
1461 		if (tTd(13, 3))
1462 		{
1463 			printf("Checking ");
1464 			printaddr(q, FALSE);
1465 		}
1466 
1467 		/* only send errors if the message failed */
1468 		if (!bitset(QBADADDR, q->q_flags))
1469 			continue;
1470 
1471 		/* we have an address that failed -- find the parent */
1472 		for (qq = q; qq != NULL; qq = qq->q_alias)
1473 		{
1474 			char obuf[MAXNAME + 6];
1475 			extern char *aliaslookup();
1476 
1477 			/* we can only have owners for local addresses */
1478 			if (!bitnset(M_LOCAL, qq->q_mailer->m_flags))
1479 				continue;
1480 
1481 			/* see if the owner list exists */
1482 			(void) strcpy(obuf, "owner-");
1483 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1484 				(void) strcat(obuf, "owner");
1485 			else
1486 				(void) strcat(obuf, qq->q_user);
1487 			if (aliaslookup(obuf) == NULL)
1488 				continue;
1489 
1490 			if (tTd(13, 4))
1491 				printf("Errors to %s\n", obuf);
1492 
1493 			/* owner list exists -- add it to the error queue */
1494 			sendtolist(obuf, (ADDRESS *) NULL, &e->e_errorqueue);
1495 			ErrorMode = EM_MAIL;
1496 			break;
1497 		}
1498 
1499 		/* if we did not find an owner, send to the sender */
1500 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1501 			sendtolist(e->e_from.q_paddr, qq, &e->e_errorqueue);
1502 	}
1503 
1504 	/* this removes the lock on the file */
1505 	if (lockfp != NULL)
1506 		(void) fclose(lockfp);
1507 
1508 	if (mode == SM_FORK)
1509 		finis();
1510 }
1511