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