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