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