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