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.6 (Berkeley) 09/24/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("mailer %s died with signal %o", name, st);
632 		ExitStat = EX_TEMPFAIL;
633 		return (EX_TEMPFAIL);
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 HOSTINFO
706 		register STAB *st;
707 		extern STAB *stab();
708 #endif HOSTINFO
709 #ifdef DAEMON
710 		register int i;
711 		register u_short port;
712 
713 		if (!clever)
714 			syserr("non-clever IPC");
715 		if (pvp[2] != NULL)
716 			port = atoi(pvp[2]);
717 		else
718 			port = 0;
719 #ifdef HOSTINFO
720 		/* see if we have already determined that this host is fried */
721 		st = stab(pvp[1], ST_HOST, ST_FIND);
722 		if (st == NULL || st->s_host.ho_exitstat == EX_OK)
723 			i = makeconnection(pvp[1], port, pmfile, prfile);
724 		else
725 			i = st->s_host.ho_exitstat;
726 #else HOSTINFO
727 		i = makeconnection(pvp[1], port, pmfile, prfile);
728 #endif HOSTINFO
729 		if (i != EX_OK)
730 		{
731 #ifdef HOSTINFO
732 			/* enter status of this host */
733 			if (st == NULL)
734 				st = stab(pvp[1], ST_HOST, ST_ENTER);
735 			st->s_host.ho_exitstat = i;
736 			st->s_host.ho_errno = errno;
737 #endif HOSTINFO
738 			ExitStat = i;
739 			return (-1);
740 		}
741 		else
742 			return (0);
743 #else DAEMON
744 		syserr("openmailer: no IPC");
745 		return (-1);
746 #endif DAEMON
747 	}
748 
749 	/* create a pipe to shove the mail through */
750 	if (pipe(mpvect) < 0)
751 	{
752 		syserr("openmailer: pipe (to mailer)");
753 		return (-1);
754 	}
755 
756 #ifdef SMTP
757 	/* if this mailer speaks smtp, create a return pipe */
758 	if (clever && pipe(rpvect) < 0)
759 	{
760 		syserr("openmailer: pipe (from mailer)");
761 		(void) close(mpvect[0]);
762 		(void) close(mpvect[1]);
763 		return (-1);
764 	}
765 #endif SMTP
766 
767 	/*
768 	**  Actually fork the mailer process.
769 	**	DOFORK is clever about retrying.
770 	*/
771 
772 	if (CurEnv->e_xfp != NULL)
773 		(void) fflush(CurEnv->e_xfp);		/* for debugging */
774 	(void) fflush(stdout);
775 	DOFORK(XFORK);
776 	/* pid is set by DOFORK */
777 	if (pid < 0)
778 	{
779 		/* failure */
780 		syserr("openmailer: cannot fork");
781 		(void) close(mpvect[0]);
782 		(void) close(mpvect[1]);
783 #ifdef SMTP
784 		if (clever)
785 		{
786 			(void) close(rpvect[0]);
787 			(void) close(rpvect[1]);
788 		}
789 #endif SMTP
790 		return (-1);
791 	}
792 	else if (pid == 0)
793 	{
794 		int i;
795 		extern int DtableSize;
796 
797 		/* child -- set up input & exec mailer */
798 		/* make diagnostic output be standard output */
799 		(void) signal(SIGINT, SIG_IGN);
800 		(void) signal(SIGHUP, SIG_IGN);
801 		(void) signal(SIGTERM, SIG_DFL);
802 
803 		/* arrange to filter standard & diag output of command */
804 		if (clever)
805 		{
806 			(void) close(rpvect[0]);
807 			(void) close(1);
808 			(void) dup(rpvect[1]);
809 			(void) close(rpvect[1]);
810 		}
811 		else if (OpMode == MD_SMTP || HoldErrs)
812 		{
813 			/* put mailer output in transcript */
814 			(void) close(1);
815 			(void) dup(fileno(CurEnv->e_xfp));
816 		}
817 		(void) close(2);
818 		(void) dup(1);
819 
820 		/* arrange to get standard input */
821 		(void) close(mpvect[1]);
822 		(void) close(0);
823 		if (dup(mpvect[0]) < 0)
824 		{
825 			syserr("Cannot dup to zero!");
826 			_exit(EX_OSERR);
827 		}
828 		(void) close(mpvect[0]);
829 		if (!bitnset(M_RESTR, m->m_flags))
830 		{
831 			if (ctladdr == NULL || ctladdr->q_uid == 0)
832 			{
833 				(void) setgid(DefGid);
834 				(void) setuid(DefUid);
835 			}
836 			else
837 			{
838 				(void) setgid(ctladdr->q_gid);
839 				(void) setuid(ctladdr->q_uid);
840 			}
841 		}
842 
843 		/* arrange for all the files to be closed */
844 		for (i = 3; i < DtableSize; i++)
845 #ifdef FIOCLEX
846 			(void) ioctl(i, FIOCLEX, 0);
847 #else FIOCLEX
848 			(void) close(i);
849 #endif FIOCLEX
850 
851 		/* try to execute the mailer */
852 		execve(m->m_mailer, pvp, UserEnviron);
853 
854 #ifdef FIOCLEX
855 		syserr("Cannot exec %s", m->m_mailer);
856 #else FIOCLEX
857 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
858 		(void) fflush(stdout);
859 #endif FIOCLEX
860 		if (m == LocalMailer || errno == EIO || errno == EAGAIN ||
861 		    errno == ENOMEM || errno == EPROCLIM)
862 			_exit(EX_TEMPFAIL);
863 		else
864 			_exit(EX_UNAVAILABLE);
865 	}
866 
867 	/*
868 	**  Set up return value.
869 	*/
870 
871 	(void) close(mpvect[0]);
872 	mfile = fdopen(mpvect[1], "w");
873 	if (clever)
874 	{
875 		(void) close(rpvect[1]);
876 		rfile = fdopen(rpvect[0], "r");
877 	}
878 
879 	*pmfile = mfile;
880 	*prfile = rfile;
881 
882 	return (pid);
883 }
884 /*
885 **  GIVERESPONSE -- Interpret an error response from a mailer
886 **
887 **	Parameters:
888 **		stat -- the status code from the mailer (high byte
889 **			only; core dumps must have been taken care of
890 **			already).
891 **		m -- the mailer descriptor for this mailer.
892 **
893 **	Returns:
894 **		none.
895 **
896 **	Side Effects:
897 **		Errors may be incremented.
898 **		ExitStat may be set.
899 */
900 
901 giveresponse(stat, m, e)
902 	int stat;
903 	register MAILER *m;
904 	ENVELOPE *e;
905 {
906 	register char *statmsg;
907 	extern char *SysExMsg[];
908 	register int i;
909 	extern int N_SysEx;
910 	char buf[MAXLINE];
911 
912 #ifdef lint
913 	if (m == NULL)
914 		return;
915 #endif lint
916 
917 	/*
918 	**  Compute status message from code.
919 	*/
920 
921 	i = stat - EX__BASE;
922 	if (stat == 0)
923 		statmsg = "250 Sent";
924 	else if (i < 0 || i > N_SysEx)
925 	{
926 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
927 		stat = EX_UNAVAILABLE;
928 		statmsg = buf;
929 	}
930 	else if (stat == EX_TEMPFAIL)
931 	{
932 		(void) strcpy(buf, SysExMsg[i]);
933 		if (errno != 0)
934 		{
935 			extern char *errstring();
936 
937 			statmsg = errstring(errno);
938 		}
939 		else
940 		{
941 #ifdef SMTP
942 			extern char SmtpError[];
943 
944 			statmsg = SmtpError;
945 #else SMTP
946 			statmsg = NULL;
947 #endif SMTP
948 		}
949 		if (statmsg != NULL && statmsg[0] != '\0')
950 		{
951 			(void) strcat(buf, ": ");
952 			(void) strcat(buf, statmsg);
953 		}
954 		statmsg = buf;
955 	}
956 	else
957 	{
958 		statmsg = SysExMsg[i];
959 	}
960 
961 	/*
962 	**  Print the message as appropriate
963 	*/
964 
965 	if (stat == EX_OK || stat == EX_TEMPFAIL)
966 		message(Arpa_Info, &statmsg[4]);
967 	else
968 	{
969 		Errors++;
970 		usrerr(statmsg);
971 	}
972 
973 	/*
974 	**  Final cleanup.
975 	**	Log a record of the transaction.  Compute the new
976 	**	ExitStat -- if we already had an error, stick with
977 	**	that.
978 	*/
979 
980 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
981 		logdelivery(&statmsg[4]);
982 
983 	if (stat != EX_TEMPFAIL)
984 		setstat(stat);
985 	if (stat != EX_OK)
986 	{
987 		if (e->e_message != NULL)
988 			free(e->e_message);
989 		e->e_message = newstr(&statmsg[4]);
990 	}
991 	errno = 0;
992 }
993 /*
994 **  LOGDELIVERY -- log the delivery in the system log
995 **
996 **	Parameters:
997 **		stat -- the message to print for the status
998 **
999 **	Returns:
1000 **		none
1001 **
1002 **	Side Effects:
1003 **		none
1004 */
1005 
1006 logdelivery(stat)
1007 	char *stat;
1008 {
1009 	extern char *pintvl();
1010 
1011 # ifdef LOG
1012 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", CurEnv->e_id,
1013 	       CurEnv->e_to, pintvl(curtime() - CurEnv->e_ctime, TRUE), stat);
1014 # endif LOG
1015 }
1016 /*
1017 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
1018 **
1019 **	This can be made an arbitrary message separator by changing $l
1020 **
1021 **	One of the ugliest hacks seen by human eyes is contained herein:
1022 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
1023 **	does a well-meaning programmer such as myself have to deal with
1024 **	this kind of antique garbage????
1025 **
1026 **	Parameters:
1027 **		fp -- the file to output to.
1028 **		m -- the mailer describing this entry.
1029 **
1030 **	Returns:
1031 **		none
1032 **
1033 **	Side Effects:
1034 **		outputs some text to fp.
1035 */
1036 
1037 putfromline(fp, m)
1038 	register FILE *fp;
1039 	register MAILER *m;
1040 {
1041 	char *template = "\001l\n";
1042 	char buf[MAXLINE];
1043 
1044 	if (bitnset(M_NHDR, m->m_flags))
1045 		return;
1046 
1047 # ifdef UGLYUUCP
1048 	if (bitnset(M_UGLYUUCP, m->m_flags))
1049 	{
1050 		char *bang;
1051 		char xbuf[MAXLINE];
1052 
1053 		expand("\001g", buf, &buf[sizeof buf - 1], CurEnv);
1054 		bang = index(buf, '!');
1055 		if (bang == NULL)
1056 			syserr("No ! in UUCP! (%s)", buf);
1057 		else
1058 		{
1059 			*bang++ = '\0';
1060 			(void) sprintf(xbuf, "From %s  \001d remote from %s\n", bang, buf);
1061 			template = xbuf;
1062 		}
1063 	}
1064 # endif UGLYUUCP
1065 	expand(template, buf, &buf[sizeof buf - 1], CurEnv);
1066 	putline(buf, fp, m);
1067 }
1068 /*
1069 **  PUTBODY -- put the body of a message.
1070 **
1071 **	Parameters:
1072 **		fp -- file to output onto.
1073 **		m -- a mailer descriptor to control output format.
1074 **		e -- the envelope to put out.
1075 **
1076 **	Returns:
1077 **		none.
1078 **
1079 **	Side Effects:
1080 **		The message is written onto fp.
1081 */
1082 
1083 putbody(fp, m, e)
1084 	FILE *fp;
1085 	MAILER *m;
1086 	register ENVELOPE *e;
1087 {
1088 	char buf[MAXLINE];
1089 
1090 	/*
1091 	**  Output the body of the message
1092 	*/
1093 
1094 	if (e->e_dfp == NULL)
1095 	{
1096 		if (e->e_df != NULL)
1097 		{
1098 			e->e_dfp = fopen(e->e_df, "r");
1099 			if (e->e_dfp == NULL)
1100 				syserr("Cannot open %s", e->e_df);
1101 		}
1102 		else
1103 			putline("<<< No Message Collected >>>", fp, m);
1104 	}
1105 	if (e->e_dfp != NULL)
1106 	{
1107 		rewind(e->e_dfp);
1108 		while (!ferror(fp) && fgets(buf, sizeof buf, e->e_dfp) != NULL)
1109 		{
1110 			if (buf[0] == 'F' && bitnset(M_ESCFROM, m->m_flags) &&
1111 			    strncmp(buf, "From", 4) == 0)
1112 				(void) putc('>', fp);
1113 			putline(buf, fp, m);
1114 		}
1115 
1116 		if (ferror(e->e_dfp))
1117 		{
1118 			syserr("putbody: read error");
1119 			ExitStat = EX_IOERR;
1120 		}
1121 	}
1122 
1123 	(void) fflush(fp);
1124 	if (ferror(fp) && errno != EPIPE)
1125 	{
1126 		syserr("putbody: write error");
1127 		ExitStat = EX_IOERR;
1128 	}
1129 	errno = 0;
1130 }
1131 /*
1132 **  MAILFILE -- Send a message to a file.
1133 **
1134 **	If the file has the setuid/setgid bits set, but NO execute
1135 **	bits, sendmail will try to become the owner of that file
1136 **	rather than the real user.  Obviously, this only works if
1137 **	sendmail runs as root.
1138 **
1139 **	This could be done as a subordinate mailer, except that it
1140 **	is used implicitly to save messages in ~/dead.letter.  We
1141 **	view this as being sufficiently important as to include it
1142 **	here.  For example, if the system is dying, we shouldn't have
1143 **	to create another process plus some pipes to save the message.
1144 **
1145 **	Parameters:
1146 **		filename -- the name of the file to send to.
1147 **		ctladdr -- the controlling address header -- includes
1148 **			the userid/groupid to be when sending.
1149 **
1150 **	Returns:
1151 **		The exit code associated with the operation.
1152 **
1153 **	Side Effects:
1154 **		none.
1155 */
1156 
1157 mailfile(filename, ctladdr)
1158 	char *filename;
1159 	ADDRESS *ctladdr;
1160 {
1161 	register FILE *f;
1162 	register int pid;
1163 
1164 	/*
1165 	**  Fork so we can change permissions here.
1166 	**	Note that we MUST use fork, not vfork, because of
1167 	**	the complications of calling subroutines, etc.
1168 	*/
1169 
1170 	DOFORK(fork);
1171 
1172 	if (pid < 0)
1173 		return (EX_OSERR);
1174 	else if (pid == 0)
1175 	{
1176 		/* child -- actually write to file */
1177 		struct stat stb;
1178 
1179 		(void) signal(SIGINT, SIG_DFL);
1180 		(void) signal(SIGHUP, SIG_DFL);
1181 		(void) signal(SIGTERM, SIG_DFL);
1182 		(void) umask(OldUmask);
1183 		if (stat(filename, &stb) < 0)
1184 		{
1185 			errno = 0;
1186 			stb.st_mode = 0666;
1187 		}
1188 		if (bitset(0111, stb.st_mode))
1189 			exit(EX_CANTCREAT);
1190 		if (ctladdr == NULL)
1191 			ctladdr = &CurEnv->e_from;
1192 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1193 		{
1194 			if (ctladdr->q_uid == 0)
1195 				(void) setgid(DefGid);
1196 			else
1197 				(void) setgid(ctladdr->q_gid);
1198 		}
1199 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1200 		{
1201 			if (ctladdr->q_uid == 0)
1202 				(void) setuid(DefUid);
1203 			else
1204 				(void) setuid(ctladdr->q_uid);
1205 		}
1206 		f = dfopen(filename, "a");
1207 		if (f == NULL)
1208 			exit(EX_CANTCREAT);
1209 
1210 		putfromline(f, ProgMailer);
1211 		(*CurEnv->e_puthdr)(f, ProgMailer, CurEnv);
1212 		putline("\n", f, ProgMailer);
1213 		(*CurEnv->e_putbody)(f, ProgMailer, CurEnv);
1214 		putline("\n", f, ProgMailer);
1215 		(void) fclose(f);
1216 		(void) fflush(stdout);
1217 
1218 		/* reset ISUID & ISGID bits for paranoid systems */
1219 		(void) chmod(filename, (int) stb.st_mode);
1220 		exit(EX_OK);
1221 		/*NOTREACHED*/
1222 	}
1223 	else
1224 	{
1225 		/* parent -- wait for exit status */
1226 		int st;
1227 
1228 		st = waitfor(pid);
1229 		if ((st & 0377) != 0)
1230 			return (EX_UNAVAILABLE);
1231 		else
1232 			return ((st >> 8) & 0377);
1233 	}
1234 }
1235 /*
1236 **  SENDALL -- actually send all the messages.
1237 **
1238 **	Parameters:
1239 **		e -- the envelope to send.
1240 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
1241 **			the current SendMode.
1242 **
1243 **	Returns:
1244 **		none.
1245 **
1246 **	Side Effects:
1247 **		Scans the send lists and sends everything it finds.
1248 **		Delivers any appropriate error messages.
1249 **		If we are running in a non-interactive mode, takes the
1250 **			appropriate action.
1251 */
1252 
1253 sendall(e, mode)
1254 	ENVELOPE *e;
1255 	char mode;
1256 {
1257 	register ADDRESS *q;
1258 	bool oldverbose;
1259 	int pid;
1260 
1261 	/* determine actual delivery mode */
1262 	if (mode == SM_DEFAULT)
1263 	{
1264 		extern bool shouldqueue();
1265 
1266 		if (shouldqueue(e->e_msgpriority))
1267 			mode = SM_QUEUE;
1268 		else
1269 			mode = SendMode;
1270 	}
1271 
1272 #ifdef DEBUG
1273 	if (tTd(13, 1))
1274 	{
1275 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1276 		printaddr(e->e_sendqueue, TRUE);
1277 	}
1278 #endif DEBUG
1279 
1280 	/*
1281 	**  Do any preprocessing necessary for the mode we are running.
1282 	**	Check to make sure the hop count is reasonable.
1283 	**	Delete sends to the sender in mailing lists.
1284 	*/
1285 
1286 	CurEnv = e;
1287 
1288 	if (e->e_hopcount > MAXHOP)
1289 	{
1290 		syserr("sendall: too many hops (%d max)", MAXHOP);
1291 		return;
1292 	}
1293 
1294 	if (!MeToo)
1295 	{
1296 		extern ADDRESS *recipient();
1297 
1298 		e->e_from.q_flags |= QDONTSEND;
1299 		(void) recipient(&e->e_from, &e->e_sendqueue);
1300 	}
1301 
1302 # ifdef QUEUE
1303 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1304 	     (mode != SM_VERIFY && SuperSafe)) &&
1305 	    !bitset(EF_INQUEUE, e->e_flags))
1306 		queueup(e, TRUE, mode == SM_QUEUE);
1307 #endif QUEUE
1308 
1309 	oldverbose = Verbose;
1310 	switch (mode)
1311 	{
1312 	  case SM_VERIFY:
1313 		Verbose = TRUE;
1314 		break;
1315 
1316 	  case SM_QUEUE:
1317 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1318 		return;
1319 
1320 	  case SM_FORK:
1321 		if (e->e_xfp != NULL)
1322 			(void) fflush(e->e_xfp);
1323 		pid = fork();
1324 		if (pid < 0)
1325 		{
1326 			mode = SM_DELIVER;
1327 			break;
1328 		}
1329 		else if (pid > 0)
1330 		{
1331 			/* be sure we leave the temp files to our child */
1332 			e->e_id = e->e_df = NULL;
1333 			return;
1334 		}
1335 
1336 		/* double fork to avoid zombies */
1337 		if (fork() > 0)
1338 			exit(EX_OK);
1339 
1340 		/* be sure we are immune from the terminal */
1341 		disconnect(FALSE);
1342 
1343 		break;
1344 	}
1345 
1346 	/*
1347 	**  Run through the list and send everything.
1348 	*/
1349 
1350 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1351 	{
1352 		if (mode == SM_VERIFY)
1353 		{
1354 			e->e_to = q->q_paddr;
1355 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1356 				message(Arpa_Info, "deliverable");
1357 		}
1358 		else
1359 			(void) deliver(e, q);
1360 	}
1361 	Verbose = oldverbose;
1362 
1363 	/*
1364 	**  Now run through and check for errors.
1365 	*/
1366 
1367 	if (mode == SM_VERIFY)
1368 		return;
1369 
1370 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1371 	{
1372 		register ADDRESS *qq;
1373 
1374 # ifdef DEBUG
1375 		if (tTd(13, 3))
1376 		{
1377 			printf("Checking ");
1378 			printaddr(q, FALSE);
1379 		}
1380 # endif DEBUG
1381 
1382 		/* only send errors if the message failed */
1383 		if (!bitset(QBADADDR, q->q_flags))
1384 			continue;
1385 
1386 		/* we have an address that failed -- find the parent */
1387 		for (qq = q; qq != NULL; qq = qq->q_alias)
1388 		{
1389 			char obuf[MAXNAME + 6];
1390 			extern char *aliaslookup();
1391 
1392 			/* we can only have owners for local addresses */
1393 			if (!bitnset(M_LOCAL, qq->q_mailer->m_flags))
1394 				continue;
1395 
1396 			/* see if the owner list exists */
1397 			(void) strcpy(obuf, "owner-");
1398 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1399 				(void) strcat(obuf, "owner");
1400 			else
1401 				(void) strcat(obuf, qq->q_user);
1402 			if (aliaslookup(obuf) == NULL)
1403 				continue;
1404 
1405 # ifdef DEBUG
1406 			if (tTd(13, 4))
1407 				printf("Errors to %s\n", obuf);
1408 # endif DEBUG
1409 
1410 			/* owner list exists -- add it to the error queue */
1411 			sendtolist(obuf, (ADDRESS *) NULL, &e->e_errorqueue);
1412 			ErrorMode = EM_MAIL;
1413 			break;
1414 		}
1415 
1416 		/* if we did not find an owner, send to the sender */
1417 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1418 			sendtolist(e->e_from.q_paddr, qq, &e->e_errorqueue);
1419 	}
1420 
1421 	if (mode == SM_FORK)
1422 		finis();
1423 }
1424