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