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