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