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