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.27 (Berkeley) 02/15/89";
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 	if (ctladdr == NULL)
375 		ctladdr = &e->e_from;
376 #ifdef NAMED_BIND
377 	_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);		/* XXX */
378 #endif
379 #ifdef SMTP
380 	if (clever)
381 	{
382 		expand("\001w", buf, &buf[sizeof(buf) - 1], e);
383 		rcode = EX_OK;
384 #ifdef NAMED_BIND
385 		if (host[0] != '[')
386 		{
387 			Nmx = getmxrr(host, MxHosts, buf, &rcode);
388 		}
389 		else
390 #endif
391 		{
392 			Nmx = 1;
393 			MxHosts[0] = host;
394 		}
395 		if (Nmx >= 0)
396 		{
397 			message(Arpa_Info, "Connecting to %s (%s)...",
398 			    MxHosts[0], m->m_name);
399 			if ((rcode = smtpinit(m, pv)) == EX_OK) {
400 				register char *t = tobuf;
401 				register int i;
402 
403 				/* send the recipient list */
404 				tobuf[0] = '\0';
405 				for (to = tochain; to; to = to->q_tchain) {
406 					e->e_to = to->q_paddr;
407 					if ((i = smtprcpt(to, m)) != EX_OK) {
408 						markfailure(e, to, i);
409 						giveresponse(i, m, e);
410 					}
411 					else {
412 						*t++ = ',';
413 						for (p = to->q_paddr; *p; *t++ = *p++);
414 					}
415 				}
416 
417 				/* now send the data */
418 				if (tobuf[0] == '\0')
419 					e->e_to = NULL;
420 				else {
421 					e->e_to = tobuf + 1;
422 					rcode = smtpdata(m, e);
423 				}
424 
425 				/* now close the connection */
426 				smtpquit(m);
427 			}
428 		}
429 	}
430 	else
431 #endif /* SMTP */
432 	{
433 		message(Arpa_Info, "Connecting to %s (%s)...", host, m->m_name);
434 		rcode = sendoff(e, m, pv, ctladdr);
435 	}
436 #ifdef NAMED_BIND
437 	_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
438 #endif
439 
440 	/*
441 	**  Do final status disposal.
442 	**	We check for something in tobuf for the SMTP case.
443 	**	If we got a temporary failure, arrange to queue the
444 	**		addressees.
445 	*/
446 
447 	if (tobuf[0] != '\0')
448 		giveresponse(rcode, m, e);
449 	if (rcode != EX_OK)
450 		for (to = tochain; to != NULL; to = to->q_tchain)
451 			markfailure(e, to, rcode);
452 
453 	errno = 0;
454 	define('g', (char *) NULL, e);
455 	return (rcode);
456 }
457 /*
458 **  MARKFAILURE -- mark a failure on a specific address.
459 **
460 **	Parameters:
461 **		e -- the envelope we are sending.
462 **		q -- the address to mark.
463 **		rcode -- the code signifying the particular failure.
464 **
465 **	Returns:
466 **		none.
467 **
468 **	Side Effects:
469 **		marks the address (and possibly the envelope) with the
470 **			failure so that an error will be returned or
471 **			the message will be queued, as appropriate.
472 */
473 
474 markfailure(e, q, rcode)
475 	register ENVELOPE *e;
476 	register ADDRESS *q;
477 	int rcode;
478 {
479 	if (rcode == EX_OK)
480 		return;
481 	else if (rcode != EX_TEMPFAIL)
482 		q->q_flags |= QBADADDR;
483 	else if (curtime() > e->e_ctime + TimeOut)
484 	{
485 		extern char *pintvl();
486 		char buf[MAXLINE];
487 
488 		if (!bitset(EF_TIMEOUT, e->e_flags))
489 		{
490 			(void) sprintf(buf, "Cannot send message for %s",
491 				pintvl(TimeOut, FALSE));
492 			if (e->e_message != NULL)
493 				free(e->e_message);
494 			e->e_message = newstr(buf);
495 			message(Arpa_Info, buf);
496 		}
497 		q->q_flags |= QBADADDR;
498 		e->e_flags |= EF_TIMEOUT;
499 	}
500 	else
501 		q->q_flags |= QQUEUEUP;
502 }
503 /*
504 **  DOFORK -- do a fork, retrying a couple of times on failure.
505 **
506 **	This MUST be a macro, since after a vfork we are running
507 **	two processes on the same stack!!!
508 **
509 **	Parameters:
510 **		none.
511 **
512 **	Returns:
513 **		From a macro???  You've got to be kidding!
514 **
515 **	Side Effects:
516 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
517 **			pid of child in parent, zero in child.
518 **			-1 on unrecoverable error.
519 **
520 **	Notes:
521 **		I'm awfully sorry this looks so awful.  That's
522 **		vfork for you.....
523 */
524 
525 # define NFORKTRIES	5
526 # ifdef VMUNIX
527 # define XFORK	vfork
528 # else VMUNIX
529 # define XFORK	fork
530 # endif VMUNIX
531 
532 # define DOFORK(fORKfN) \
533 {\
534 	register int i;\
535 \
536 	for (i = NFORKTRIES; --i >= 0; )\
537 	{\
538 		pid = fORKfN();\
539 		if (pid >= 0)\
540 			break;\
541 		if (i > 0)\
542 			sleep((unsigned) NFORKTRIES - i);\
543 	}\
544 }
545 /*
546 **  DOFORK -- simple fork interface to DOFORK.
547 **
548 **	Parameters:
549 **		none.
550 **
551 **	Returns:
552 **		pid of child in parent.
553 **		zero in child.
554 **		-1 on error.
555 **
556 **	Side Effects:
557 **		returns twice, once in parent and once in child.
558 */
559 
560 dofork()
561 {
562 	register int pid;
563 
564 	DOFORK(fork);
565 	return (pid);
566 }
567 /*
568 **  SENDOFF -- send off call to mailer & collect response.
569 **
570 **	Parameters:
571 **		e -- the envelope to mail.
572 **		m -- mailer descriptor.
573 **		pvp -- parameter vector to send to it.
574 **		ctladdr -- an address pointer controlling the
575 **			user/groupid etc. of the mailer.
576 **
577 **	Returns:
578 **		exit status of mailer.
579 **
580 **	Side Effects:
581 **		none.
582 */
583 static
584 sendoff(e, m, pvp, ctladdr)
585 	register ENVELOPE *e;
586 	MAILER *m;
587 	char **pvp;
588 	ADDRESS *ctladdr;
589 {
590 	auto FILE *mfile;
591 	auto FILE *rfile;
592 	register int i;
593 	int pid;
594 
595 	/*
596 	**  Create connection to mailer.
597 	*/
598 
599 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
600 	if (pid < 0)
601 		return (-1);
602 
603 	/*
604 	**  Format and send message.
605 	*/
606 
607 	putfromline(mfile, m);
608 	(*e->e_puthdr)(mfile, m, e);
609 	putline("\n", mfile, m);
610 	(*e->e_putbody)(mfile, m, e);
611 	(void) fclose(mfile);
612 
613 	i = endmailer(pid, pvp[0]);
614 
615 	/* arrange a return receipt if requested */
616 	if (e->e_receiptto != NULL && bitnset(M_LOCAL, m->m_flags))
617 	{
618 		e->e_flags |= EF_SENDRECEIPT;
619 		/* do we want to send back more info? */
620 	}
621 
622 	return (i);
623 }
624 /*
625 **  ENDMAILER -- Wait for mailer to terminate.
626 **
627 **	We should never get fatal errors (e.g., segmentation
628 **	violation), so we report those specially.  For other
629 **	errors, we choose a status message (into statmsg),
630 **	and if it represents an error, we print it.
631 **
632 **	Parameters:
633 **		pid -- pid of mailer.
634 **		name -- name of mailer (for error messages).
635 **
636 **	Returns:
637 **		exit code of mailer.
638 **
639 **	Side Effects:
640 **		none.
641 */
642 
643 endmailer(pid, name)
644 	int pid;
645 	char *name;
646 {
647 	int st;
648 
649 	/* in the IPC case there is nothing to wait for */
650 	if (pid == 0)
651 		return (EX_OK);
652 
653 	/* wait for the mailer process to die and collect status */
654 	st = waitfor(pid);
655 	if (st == -1)
656 	{
657 		syserr("endmailer %s: wait", name);
658 		return (EX_SOFTWARE);
659 	}
660 
661 	/* see if it died a horrid death */
662 	if ((st & 0377) != 0)
663 	{
664 		syserr("mailer %s died with signal %o", name, st);
665 		ExitStat = EX_TEMPFAIL;
666 		return (EX_TEMPFAIL);
667 	}
668 
669 	/* normal death -- return status */
670 	st = (st >> 8) & 0377;
671 	return (st);
672 }
673 /*
674 **  OPENMAILER -- open connection to mailer.
675 **
676 **	Parameters:
677 **		m -- mailer descriptor.
678 **		pvp -- parameter vector to pass to mailer.
679 **		ctladdr -- controlling address for user.
680 **		clever -- create a full duplex connection.
681 **		pmfile -- pointer to mfile (to mailer) connection.
682 **		prfile -- pointer to rfile (from mailer) connection.
683 **
684 **	Returns:
685 **		pid of mailer ( > 0 ).
686 **		-1 on error.
687 **		zero on an IPC connection.
688 **
689 **	Side Effects:
690 **		creates a mailer in a subprocess.
691 */
692 
693 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
694 	MAILER *m;
695 	char **pvp;
696 	ADDRESS *ctladdr;
697 	bool clever;
698 	FILE **pmfile;
699 	FILE **prfile;
700 {
701 	int pid;
702 	int mpvect[2];
703 	int rpvect[2];
704 	FILE *mfile;
705 	FILE *rfile;
706 	extern FILE *fdopen();
707 
708 	if (tTd(11, 1))
709 	{
710 		printf("openmailer:");
711 		printav(pvp);
712 	}
713 	errno = 0;
714 
715 	CurHostName = m->m_mailer;
716 
717 	/*
718 	**  Deal with the special case of mail handled through an IPC
719 	**  connection.
720 	**	In this case we don't actually fork.  We must be
721 	**	running SMTP for this to work.  We will return a
722 	**	zero pid to indicate that we are running IPC.
723 	**  We also handle a debug version that just talks to stdin/out.
724 	*/
725 
726 	/* check for Local Person Communication -- not for mortals!!! */
727 	if (strcmp(m->m_mailer, "[LPC]") == 0)
728 	{
729 		*pmfile = stdout;
730 		*prfile = stdin;
731 		return (0);
732 	}
733 
734 	if (strcmp(m->m_mailer, "[IPC]") == 0)
735 	{
736 #ifdef HOSTINFO
737 		register STAB *st;
738 		extern STAB *stab();
739 #endif HOSTINFO
740 #ifdef DAEMON
741 		register int i, j;
742 		register u_short port;
743 
744 		CurHostName = pvp[1];
745 		if (!clever)
746 			syserr("non-clever IPC");
747 		if (pvp[2] != NULL)
748 			port = atoi(pvp[2]);
749 		else
750 			port = 0;
751 		for (j = 0; j < Nmx; j++)
752 		{
753 			CurHostName = MxHosts[j];
754 #ifdef HOSTINFO
755 		/* see if we have already determined that this host is fried */
756 			st = stab(MxHosts[j], ST_HOST, ST_FIND);
757 			if (st == NULL || st->s_host.ho_exitstat == EX_OK) {
758 				if (j > 1)
759 					message(Arpa_Info,
760 					    "Connecting to %s (%s)...",
761 					    MxHosts[j], m->m_name);
762 				i = makeconnection(MxHosts[j], port, pmfile, prfile);
763 			}
764 			else
765 			{
766 				i = st->s_host.ho_exitstat;
767 				errno = st->s_host.ho_errno;
768 			}
769 #else HOSTINFO
770 			i = makeconnection(MxHosts[j], port, pmfile, prfile);
771 #endif HOSTINFO
772 			if (i != EX_OK)
773 			{
774 #ifdef HOSTINFO
775 				/* enter status of this host */
776 				if (st == NULL)
777 					st = stab(MxHosts[j], ST_HOST, ST_ENTER);
778 				st->s_host.ho_exitstat = i;
779 				st->s_host.ho_errno = errno;
780 #endif HOSTINFO
781 				ExitStat = i;
782 				continue;
783 			}
784 			else
785 				return (0);
786 		}
787 		return (-1);
788 #else DAEMON
789 		syserr("openmailer: no IPC");
790 		return (-1);
791 #endif DAEMON
792 	}
793 
794 	/* create a pipe to shove the mail through */
795 	if (pipe(mpvect) < 0)
796 	{
797 		syserr("openmailer: pipe (to mailer)");
798 		return (-1);
799 	}
800 
801 #ifdef SMTP
802 	/* if this mailer speaks smtp, create a return pipe */
803 	if (clever && pipe(rpvect) < 0)
804 	{
805 		syserr("openmailer: pipe (from mailer)");
806 		(void) close(mpvect[0]);
807 		(void) close(mpvect[1]);
808 		return (-1);
809 	}
810 #endif SMTP
811 
812 	/*
813 	**  Actually fork the mailer process.
814 	**	DOFORK is clever about retrying.
815 	**
816 	**	Dispose of SIGCHLD signal catchers that may be laying
817 	**	around so that endmail will get it.
818 	*/
819 
820 	if (CurEnv->e_xfp != NULL)
821 		(void) fflush(CurEnv->e_xfp);		/* for debugging */
822 	(void) fflush(stdout);
823 # ifdef SIGCHLD
824 	(void) signal(SIGCHLD, SIG_DFL);
825 # endif SIGCHLD
826 	DOFORK(XFORK);
827 	/* pid is set by DOFORK */
828 	if (pid < 0)
829 	{
830 		/* failure */
831 		syserr("openmailer: cannot fork");
832 		(void) close(mpvect[0]);
833 		(void) close(mpvect[1]);
834 #ifdef SMTP
835 		if (clever)
836 		{
837 			(void) close(rpvect[0]);
838 			(void) close(rpvect[1]);
839 		}
840 #endif SMTP
841 		return (-1);
842 	}
843 	else if (pid == 0)
844 	{
845 		int i;
846 		extern int DtableSize;
847 
848 		/* child -- set up input & exec mailer */
849 		/* make diagnostic output be standard output */
850 		(void) signal(SIGINT, SIG_IGN);
851 		(void) signal(SIGHUP, SIG_IGN);
852 		(void) signal(SIGTERM, SIG_DFL);
853 
854 		/* arrange to filter standard & diag output of command */
855 		if (clever)
856 		{
857 			(void) close(rpvect[0]);
858 			(void) close(1);
859 			(void) dup(rpvect[1]);
860 			(void) close(rpvect[1]);
861 		}
862 		else if (OpMode == MD_SMTP || HoldErrs)
863 		{
864 			/* put mailer output in transcript */
865 			(void) close(1);
866 			(void) dup(fileno(CurEnv->e_xfp));
867 		}
868 		(void) close(2);
869 		(void) dup(1);
870 
871 		/* arrange to get standard input */
872 		(void) close(mpvect[1]);
873 		(void) close(0);
874 		if (dup(mpvect[0]) < 0)
875 		{
876 			syserr("Cannot dup to zero!");
877 			_exit(EX_OSERR);
878 		}
879 		(void) close(mpvect[0]);
880 		if (!bitnset(M_RESTR, m->m_flags))
881 		{
882 			if (ctladdr == NULL || ctladdr->q_uid == 0)
883 			{
884 				(void) setgid(DefGid);
885 				(void) setuid(DefUid);
886 			}
887 			else
888 			{
889 				(void) setgid(ctladdr->q_gid);
890 				(void) setuid(ctladdr->q_uid);
891 			}
892 		}
893 
894 		/* arrange for all the files to be closed */
895 		for (i = 3; i < DtableSize; i++) {
896 			register int j;
897 			if ((j = fcntl(i, F_GETFD, 0)) != -1)
898 				(void)fcntl(i, F_SETFD, j|1);
899 		}
900 
901 		/* try to execute the mailer */
902 		execve(m->m_mailer, pvp, UserEnviron);
903 		syserr("Cannot exec %s", m->m_mailer);
904 		if (m == LocalMailer || errno == EIO || errno == EAGAIN ||
905 		    errno == ENOMEM || errno == EPROCLIM)
906 			_exit(EX_TEMPFAIL);
907 		else
908 			_exit(EX_UNAVAILABLE);
909 	}
910 
911 	/*
912 	**  Set up return value.
913 	*/
914 
915 	(void) close(mpvect[0]);
916 	mfile = fdopen(mpvect[1], "w");
917 	if (clever)
918 	{
919 		(void) close(rpvect[1]);
920 		rfile = fdopen(rpvect[0], "r");
921 	}
922 
923 	*pmfile = mfile;
924 	*prfile = rfile;
925 
926 	return (pid);
927 }
928 /*
929 **  GIVERESPONSE -- Interpret an error response from a mailer
930 **
931 **	Parameters:
932 **		stat -- the status code from the mailer (high byte
933 **			only; core dumps must have been taken care of
934 **			already).
935 **		m -- the mailer descriptor for this mailer.
936 **
937 **	Returns:
938 **		none.
939 **
940 **	Side Effects:
941 **		Errors may be incremented.
942 **		ExitStat may be set.
943 */
944 
945 giveresponse(stat, m, e)
946 	int stat;
947 	register MAILER *m;
948 	ENVELOPE *e;
949 {
950 	register char *statmsg;
951 	extern char *SysExMsg[];
952 	register int i;
953 	extern int N_SysEx;
954 #ifdef NAMED_BIND
955 	extern int h_errno;
956 #endif
957 	char buf[MAXLINE];
958 
959 #ifdef lint
960 	if (m == NULL)
961 		return;
962 #endif lint
963 
964 	/*
965 	**  Compute status message from code.
966 	*/
967 
968 	i = stat - EX__BASE;
969 	if (stat == 0)
970 		statmsg = "250 Sent";
971 	else if (i < 0 || i > N_SysEx)
972 	{
973 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
974 		stat = EX_UNAVAILABLE;
975 		statmsg = buf;
976 	}
977 	else if (stat == EX_TEMPFAIL)
978 	{
979 		(void) strcpy(buf, SysExMsg[i]);
980 #ifdef NAMED_BIND
981 		if (h_errno == TRY_AGAIN)
982 		{
983 			extern char *errstring();
984 
985 			statmsg = errstring(h_errno+MAX_ERRNO);
986 		}
987 		else
988 #endif
989 		{
990 			if (errno != 0)
991 			{
992 				extern char *errstring();
993 
994 				statmsg = errstring(errno);
995 			}
996 			else
997 			{
998 #ifdef SMTP
999 				extern char SmtpError[];
1000 
1001 				statmsg = SmtpError;
1002 #else SMTP
1003 				statmsg = NULL;
1004 #endif SMTP
1005 			}
1006 		}
1007 		if (statmsg != NULL && statmsg[0] != '\0')
1008 		{
1009 			(void) strcat(buf, ": ");
1010 			(void) strcat(buf, statmsg);
1011 		}
1012 		statmsg = buf;
1013 	}
1014 	else
1015 	{
1016 		statmsg = SysExMsg[i];
1017 	}
1018 
1019 	/*
1020 	**  Print the message as appropriate
1021 	*/
1022 
1023 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1024 		message(Arpa_Info, &statmsg[4]);
1025 	else
1026 	{
1027 		Errors++;
1028 		usrerr(statmsg);
1029 	}
1030 
1031 	/*
1032 	**  Final cleanup.
1033 	**	Log a record of the transaction.  Compute the new
1034 	**	ExitStat -- if we already had an error, stick with
1035 	**	that.
1036 	*/
1037 
1038 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
1039 		logdelivery(&statmsg[4]);
1040 
1041 	if (stat != EX_TEMPFAIL)
1042 		setstat(stat);
1043 	if (stat != EX_OK)
1044 	{
1045 		if (e->e_message != NULL)
1046 			free(e->e_message);
1047 		e->e_message = newstr(&statmsg[4]);
1048 	}
1049 	errno = 0;
1050 #ifdef NAMED_BIND
1051 	h_errno = 0;
1052 #endif
1053 }
1054 /*
1055 **  LOGDELIVERY -- log the delivery in the system log
1056 **
1057 **	Parameters:
1058 **		stat -- the message to print for the status
1059 **
1060 **	Returns:
1061 **		none
1062 **
1063 **	Side Effects:
1064 **		none
1065 */
1066 
1067 logdelivery(stat)
1068 	char *stat;
1069 {
1070 	extern char *pintvl();
1071 
1072 # ifdef LOG
1073 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", CurEnv->e_id,
1074 	       CurEnv->e_to, pintvl(curtime() - CurEnv->e_ctime, TRUE), stat);
1075 # endif LOG
1076 }
1077 /*
1078 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1079 **
1080 **	This can be made an arbitrary message separator by changing $l
1081 **
1082 **	One of the ugliest hacks seen by human eyes is contained herein:
1083 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1084 **	does a well-meaning programmer such as myself have to deal with
1085 **	this kind of antique garbage????
1086 **
1087 **	Parameters:
1088 **		fp -- the file to output to.
1089 **		m -- the mailer describing this entry.
1090 **
1091 **	Returns:
1092 **		none
1093 **
1094 **	Side Effects:
1095 **		outputs some text to fp.
1096 */
1097 
1098 putfromline(fp, m)
1099 	register FILE *fp;
1100 	register MAILER *m;
1101 {
1102 	char *template = "\001l\n";
1103 	char buf[MAXLINE];
1104 
1105 	if (bitnset(M_NHDR, m->m_flags))
1106 		return;
1107 
1108 # ifdef UGLYUUCP
1109 	if (bitnset(M_UGLYUUCP, m->m_flags))
1110 	{
1111 		char *bang;
1112 		char xbuf[MAXLINE];
1113 
1114 		expand("\001g", buf, &buf[sizeof buf - 1], CurEnv);
1115 		bang = index(buf, '!');
1116 		if (bang == NULL)
1117 			syserr("No ! in UUCP! (%s)", buf);
1118 		else
1119 		{
1120 			*bang++ = '\0';
1121 			(void) sprintf(xbuf, "From %s  \001d remote from %s\n", bang, buf);
1122 			template = xbuf;
1123 		}
1124 	}
1125 # endif UGLYUUCP
1126 	expand(template, buf, &buf[sizeof buf - 1], CurEnv);
1127 	putline(buf, fp, m);
1128 }
1129 /*
1130 **  PUTBODY -- put the body of a message.
1131 **
1132 **	Parameters:
1133 **		fp -- file to output onto.
1134 **		m -- a mailer descriptor to control output format.
1135 **		e -- the envelope to put out.
1136 **
1137 **	Returns:
1138 **		none.
1139 **
1140 **	Side Effects:
1141 **		The message is written onto fp.
1142 */
1143 
1144 putbody(fp, m, e)
1145 	FILE *fp;
1146 	MAILER *m;
1147 	register ENVELOPE *e;
1148 {
1149 	char buf[MAXLINE];
1150 
1151 	/*
1152 	**  Output the body of the message
1153 	*/
1154 
1155 	if (e->e_dfp == NULL)
1156 	{
1157 		if (e->e_df != NULL)
1158 		{
1159 			e->e_dfp = fopen(e->e_df, "r");
1160 			if (e->e_dfp == NULL)
1161 				syserr("Cannot open %s", e->e_df);
1162 		}
1163 		else
1164 			putline("<<< No Message Collected >>>", fp, m);
1165 	}
1166 	if (e->e_dfp != NULL)
1167 	{
1168 		rewind(e->e_dfp);
1169 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1170 		{
1171 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1172 			    strncmp(buf, "From", 4) == 0)
1173 				(void) putc('>', fp);
1174 			putline(buf, fp, m);
1175 		}
1176 
1177 		if (ferror(e->e_dfp))
1178 		{
1179 			syserr("putbody: read error");
1180 			ExitStat = EX_IOERR;
1181 		}
1182 	}
1183 
1184 	(void) fflush(fp);
1185 	if (ferror(fp) && errno != EPIPE)
1186 	{
1187 		syserr("putbody: write error");
1188 		ExitStat = EX_IOERR;
1189 	}
1190 	errno = 0;
1191 }
1192 /*
1193 **  MAILFILE -- Send a message to a file.
1194 **
1195 **	If the file has the setuid/setgid bits set, but NO execute
1196 **	bits, sendmail will try to become the owner of that file
1197 **	rather than the real user.  Obviously, this only works if
1198 **	sendmail runs as root.
1199 **
1200 **	This could be done as a subordinate mailer, except that it
1201 **	is used implicitly to save messages in ~/dead.letter.  We
1202 **	view this as being sufficiently important as to include it
1203 **	here.  For example, if the system is dying, we shouldn't have
1204 **	to create another process plus some pipes to save the message.
1205 **
1206 **	Parameters:
1207 **		filename -- the name of the file to send to.
1208 **		ctladdr -- the controlling address header -- includes
1209 **			the userid/groupid to be when sending.
1210 **
1211 **	Returns:
1212 **		The exit code associated with the operation.
1213 **
1214 **	Side Effects:
1215 **		none.
1216 */
1217 
1218 mailfile(filename, ctladdr)
1219 	char *filename;
1220 	ADDRESS *ctladdr;
1221 {
1222 	register FILE *f;
1223 	register int pid;
1224 
1225 	/*
1226 	**  Fork so we can change permissions here.
1227 	**	Note that we MUST use fork, not vfork, because of
1228 	**	the complications of calling subroutines, etc.
1229 	*/
1230 
1231 	DOFORK(fork);
1232 
1233 	if (pid < 0)
1234 		return (EX_OSERR);
1235 	else if (pid == 0)
1236 	{
1237 		/* child -- actually write to file */
1238 		struct stat stb;
1239 
1240 		(void) signal(SIGINT, SIG_DFL);
1241 		(void) signal(SIGHUP, SIG_DFL);
1242 		(void) signal(SIGTERM, SIG_DFL);
1243 		(void) umask(OldUmask);
1244 		if (stat(filename, &stb) < 0)
1245 		{
1246 			errno = 0;
1247 			stb.st_mode = 0666;
1248 		}
1249 		if (bitset(0111, stb.st_mode))
1250 			exit(EX_CANTCREAT);
1251 		if (ctladdr == NULL)
1252 			ctladdr = &CurEnv->e_from;
1253 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1254 		{
1255 			if (ctladdr->q_uid == 0)
1256 				(void) setgid(DefGid);
1257 			else
1258 				(void) setgid(ctladdr->q_gid);
1259 		}
1260 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1261 		{
1262 			if (ctladdr->q_uid == 0)
1263 				(void) setuid(DefUid);
1264 			else
1265 				(void) setuid(ctladdr->q_uid);
1266 		}
1267 		f = dfopen(filename, "a");
1268 		if (f == NULL)
1269 			exit(EX_CANTCREAT);
1270 
1271 		putfromline(f, ProgMailer);
1272 		(*CurEnv->e_puthdr)(f, ProgMailer, CurEnv);
1273 		putline("\n", f, ProgMailer);
1274 		(*CurEnv->e_putbody)(f, ProgMailer, CurEnv);
1275 		putline("\n", f, ProgMailer);
1276 		(void) fclose(f);
1277 		(void) fflush(stdout);
1278 
1279 		/* reset ISUID & ISGID bits for paranoid systems */
1280 		(void) chmod(filename, (int) stb.st_mode);
1281 		exit(EX_OK);
1282 		/*NOTREACHED*/
1283 	}
1284 	else
1285 	{
1286 		/* parent -- wait for exit status */
1287 		int st;
1288 
1289 		st = waitfor(pid);
1290 		if ((st & 0377) != 0)
1291 			return (EX_UNAVAILABLE);
1292 		else
1293 			return ((st >> 8) & 0377);
1294 	}
1295 }
1296 /*
1297 **  SENDALL -- actually send all the messages.
1298 **
1299 **	Parameters:
1300 **		e -- the envelope to send.
1301 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
1302 **			the current SendMode.
1303 **
1304 **	Returns:
1305 **		none.
1306 **
1307 **	Side Effects:
1308 **		Scans the send lists and sends everything it finds.
1309 **		Delivers any appropriate error messages.
1310 **		If we are running in a non-interactive mode, takes the
1311 **			appropriate action.
1312 */
1313 
1314 sendall(e, mode)
1315 	ENVELOPE *e;
1316 	char mode;
1317 {
1318 	register ADDRESS *q;
1319 	bool oldverbose;
1320 	int pid;
1321 
1322 	/* determine actual delivery mode */
1323 	if (mode == SM_DEFAULT)
1324 	{
1325 		extern bool shouldqueue();
1326 
1327 		if (shouldqueue(e->e_msgpriority))
1328 			mode = SM_QUEUE;
1329 		else
1330 			mode = SendMode;
1331 	}
1332 
1333 	if (tTd(13, 1))
1334 	{
1335 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1336 		printaddr(e->e_sendqueue, TRUE);
1337 	}
1338 
1339 	/*
1340 	**  Do any preprocessing necessary for the mode we are running.
1341 	**	Check to make sure the hop count is reasonable.
1342 	**	Delete sends to the sender in mailing lists.
1343 	*/
1344 
1345 	CurEnv = e;
1346 
1347 	if (e->e_hopcount > MAXHOP)
1348 	{
1349 		syserr("sendall: too many hops (%d max)", MAXHOP);
1350 		return;
1351 	}
1352 
1353 	if (!MeToo)
1354 	{
1355 		extern ADDRESS *recipient();
1356 
1357 		e->e_from.q_flags |= QDONTSEND;
1358 		(void) recipient(&e->e_from, &e->e_sendqueue);
1359 	}
1360 
1361 # ifdef QUEUE
1362 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1363 	     (mode != SM_VERIFY && SuperSafe)) &&
1364 	    !bitset(EF_INQUEUE, e->e_flags))
1365 		queueup(e, TRUE, mode == SM_QUEUE);
1366 #endif QUEUE
1367 
1368 	oldverbose = Verbose;
1369 	switch (mode)
1370 	{
1371 	  case SM_VERIFY:
1372 		Verbose = TRUE;
1373 		break;
1374 
1375 	  case SM_QUEUE:
1376 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1377 		return;
1378 
1379 	  case SM_FORK:
1380 		if (e->e_xfp != NULL)
1381 			(void) fflush(e->e_xfp);
1382 		pid = fork();
1383 		if (pid < 0)
1384 		{
1385 			mode = SM_DELIVER;
1386 			break;
1387 		}
1388 		else if (pid > 0)
1389 		{
1390 			/* be sure we leave the temp files to our child */
1391 			e->e_id = e->e_df = NULL;
1392 			return;
1393 		}
1394 
1395 		/* double fork to avoid zombies */
1396 		if (fork() > 0)
1397 			exit(EX_OK);
1398 
1399 		/* be sure we are immune from the terminal */
1400 		disconnect(FALSE);
1401 
1402 		break;
1403 	}
1404 
1405 	/*
1406 	**  Run through the list and send everything.
1407 	*/
1408 
1409 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1410 	{
1411 		if (mode == SM_VERIFY)
1412 		{
1413 			e->e_to = q->q_paddr;
1414 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1415 				message(Arpa_Info, "deliverable");
1416 		}
1417 		else
1418 			(void) deliver(e, q);
1419 	}
1420 	Verbose = oldverbose;
1421 
1422 	/*
1423 	**  Now run through and check for errors.
1424 	*/
1425 
1426 	if (mode == SM_VERIFY)
1427 		return;
1428 
1429 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1430 	{
1431 		register ADDRESS *qq;
1432 
1433 		if (tTd(13, 3))
1434 		{
1435 			printf("Checking ");
1436 			printaddr(q, FALSE);
1437 		}
1438 
1439 		/* only send errors if the message failed */
1440 		if (!bitset(QBADADDR, q->q_flags))
1441 			continue;
1442 
1443 		/* we have an address that failed -- find the parent */
1444 		for (qq = q; qq != NULL; qq = qq->q_alias)
1445 		{
1446 			char obuf[MAXNAME + 6];
1447 			extern char *aliaslookup();
1448 
1449 			/* we can only have owners for local addresses */
1450 			if (!bitnset(M_LOCAL, qq->q_mailer->m_flags))
1451 				continue;
1452 
1453 			/* see if the owner list exists */
1454 			(void) strcpy(obuf, "owner-");
1455 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1456 				(void) strcat(obuf, "owner");
1457 			else
1458 				(void) strcat(obuf, qq->q_user);
1459 			if (aliaslookup(obuf) == NULL)
1460 				continue;
1461 
1462 			if (tTd(13, 4))
1463 				printf("Errors to %s\n", obuf);
1464 
1465 			/* owner list exists -- add it to the error queue */
1466 			sendtolist(obuf, (ADDRESS *) NULL, &e->e_errorqueue);
1467 			ErrorMode = EM_MAIL;
1468 			break;
1469 		}
1470 
1471 		/* if we did not find an owner, send to the sender */
1472 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1473 			sendtolist(e->e_from.q_paddr, qq, &e->e_errorqueue);
1474 	}
1475 
1476 	if (mode == SM_FORK)
1477 		finis();
1478 }
1479