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