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