1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # include <sys/stat.h>
5 
6 SCCSID(@(#)deliver.c	3.138		01/01/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);
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);
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 					if (i == EX_TEMPFAIL)
364 						to->q_flags |= QQUEUEUP;
365 					else
366 						to->q_flags |= QBADADDR;
367 					giveresponse(i, m);
368 				}
369 				else
370 				{
371 					strcat(tobuf, ",");
372 					strcat(tobuf, to->q_paddr);
373 				}
374 			}
375 
376 			/* now send the data */
377 			if (tobuf[0] == '\0')
378 				e->e_to = NULL;
379 			else
380 			{
381 				e->e_to = tobuf + 1;
382 				rcode = smtpfinish(m, e);
383 			}
384 
385 			/* now close the connection */
386 			smtpquit(pv[0]);
387 		}
388 	}
389 	else
390 # endif SMTP
391 		rcode = sendoff(e, m, pv, ctladdr, FALSE);
392 
393 	/*
394 	**  Do final status disposal.
395 	**	We check for something in tobuf for the SMTP case.
396 	**	If we got a temporary failure, arrange to queue the
397 	**		addressees.
398 	*/
399 
400 	if (tobuf[0] != '\0')
401 		giveresponse(rcode, m);
402 	if (rcode != EX_OK)
403 	{
404 		for (to = tochain; to != NULL; to = to->q_tchain)
405 		{
406 			if (rcode == EX_TEMPFAIL)
407 				to->q_flags |= QQUEUEUP;
408 			else
409 				to->q_flags |= QBADADDR;
410 		}
411 	}
412 
413 	errno = 0;
414 	define('g', (char *) NULL, e);
415 	return (rcode);
416 }
417 /*
418 **  DOFORK -- do a fork, retrying a couple of times on failure.
419 **
420 **	This MUST be a macro, since after a vfork we are running
421 **	two processes on the same stack!!!
422 **
423 **	Parameters:
424 **		none.
425 **
426 **	Returns:
427 **		From a macro???  You've got to be kidding!
428 **
429 **	Side Effects:
430 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
431 **			pid of child in parent, zero in child.
432 **			-1 on unrecoverable error.
433 **
434 **	Notes:
435 **		I'm awfully sorry this looks so awful.  That's
436 **		vfork for you.....
437 */
438 
439 # define NFORKTRIES	5
440 # ifdef VMUNIX
441 # define XFORK	vfork
442 # else VMUNIX
443 # define XFORK	fork
444 # endif VMUNIX
445 
446 # define DOFORK(fORKfN) \
447 {\
448 	register int i;\
449 \
450 	for (i = NFORKTRIES; i-- > 0; )\
451 	{\
452 		pid = fORKfN();\
453 		if (pid >= 0)\
454 			break;\
455 		sleep(NFORKTRIES - i);\
456 	}\
457 }
458 /*
459 **  DOFORK -- simple fork interface to DOFORK.
460 **
461 **	Parameters:
462 **		none.
463 **
464 **	Returns:
465 **		pid of child in parent.
466 **		zero in child.
467 **		-1 on error.
468 **
469 **	Side Effects:
470 **		returns twice, once in parent and once in child.
471 */
472 
473 dofork()
474 {
475 	register int pid;
476 
477 	DOFORK(fork);
478 	return (pid);
479 }
480 /*
481 **  SENDOFF -- send off call to mailer & collect response.
482 **
483 **	Parameters:
484 **		e -- the envelope to mail.
485 **		m -- mailer descriptor.
486 **		pvp -- parameter vector to send to it.
487 **		ctladdr -- an address pointer controlling the
488 **			user/groupid etc. of the mailer.
489 **		crlf -- set if we want CRLF on the end of lines.
490 **
491 **	Returns:
492 **		exit status of mailer.
493 **
494 **	Side Effects:
495 **		none.
496 */
497 
498 sendoff(e, m, pvp, ctladdr, crlf)
499 	register ENVELOPE *e;
500 	MAILER *m;
501 	char **pvp;
502 	ADDRESS *ctladdr;
503 	bool crlf;
504 {
505 	auto FILE *mfile;
506 	auto FILE *rfile;
507 	register int i;
508 	int pid;
509 
510 	/*
511 	**  Create connection to mailer.
512 	*/
513 
514 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
515 	if (pid < 0)
516 		return (-1);
517 
518 	/*
519 	**  Format and send message.
520 	**	We ignore broken pipes so that the mailer need not read
521 	**	its input if it is not convenient to do so (e.g., on
522 	**	some error).
523 	*/
524 
525 	(void) signal(SIGPIPE, SIG_IGN);
526 	putfromline(mfile, m, crlf);
527 	(*e->e_puthdr)(mfile, m, e, crlf);
528 	fprintf(mfile, "\n");
529 	(*e->e_putbody)(mfile, m, FALSE, e, crlf);
530 	(void) fclose(mfile);
531 
532 	i = endmailer(pid, pvp[0]);
533 
534 	/* arrange a return receipt if requested */
535 	if (e->e_receiptto != NULL && bitset(M_LOCAL, m->m_flags))
536 	{
537 		e->e_flags |= EF_SENDRECEIPT;
538 		/* do we want to send back more info? */
539 	}
540 
541 	return (i);
542 }
543 /*
544 **  ENDMAILER -- Wait for mailer to terminate.
545 **
546 **	We should never get fatal errors (e.g., segmentation
547 **	violation), so we report those specially.  For other
548 **	errors, we choose a status message (into statmsg),
549 **	and if it represents an error, we print it.
550 **
551 **	Parameters:
552 **		pid -- pid of mailer.
553 **		name -- name of mailer (for error messages).
554 **
555 **	Returns:
556 **		exit code of mailer.
557 **
558 **	Side Effects:
559 **		none.
560 */
561 
562 endmailer(pid, name)
563 	int pid;
564 	char *name;
565 {
566 	int st;
567 
568 	/* in the IPC case there is nothing to wait for */
569 	if (pid == 0)
570 		return (EX_OK);
571 
572 	/* wait for the mailer process to die and collect status */
573 	st = waitfor(pid);
574 	if (st == -1)
575 	{
576 		syserr("endmailer %s: wait", name);
577 		return (EX_SOFTWARE);
578 	}
579 
580 	/* see if it died a horrid death */
581 	if ((st & 0377) != 0)
582 	{
583 		syserr("endmailer %s: stat %o", name, st);
584 		ExitStat = EX_UNAVAILABLE;
585 		return (EX_UNAVAILABLE);
586 	}
587 
588 	/* normal death -- return status */
589 	st = (st >> 8) & 0377;
590 	return (st);
591 }
592 /*
593 **  OPENMAILER -- open connection to mailer.
594 **
595 **	Parameters:
596 **		m -- mailer descriptor.
597 **		pvp -- parameter vector to pass to mailer.
598 **		ctladdr -- controlling address for user.
599 **		clever -- create a full duplex connection.
600 **		pmfile -- pointer to mfile (to mailer) connection.
601 **		prfile -- pointer to rfile (from mailer) connection.
602 **
603 **	Returns:
604 **		pid of mailer ( > 0 ).
605 **		-1 on error.
606 **		zero on an IPC connection.
607 **
608 **	Side Effects:
609 **		creates a mailer in a subprocess.
610 */
611 
612 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
613 	MAILER *m;
614 	char **pvp;
615 	ADDRESS *ctladdr;
616 	bool clever;
617 	FILE **pmfile;
618 	FILE **prfile;
619 {
620 	int pid;
621 	int mpvect[2];
622 	int rpvect[2];
623 	FILE *mfile;
624 	FILE *rfile;
625 	extern FILE *fdopen();
626 
627 # ifdef DEBUG
628 	if (tTd(11, 1))
629 	{
630 		printf("openmailer:");
631 		printav(pvp);
632 	}
633 # endif DEBUG
634 	errno = 0;
635 
636 	/*
637 	**  Deal with the special case of mail handled through an IPC
638 	**  connection.
639 	**	In this case we don't actually fork.  We must be
640 	**	running SMTP for this to work.  We will return a
641 	**	zero pid to indicate that we are running IPC.
642 	*/
643 
644 	if (strcmp(m->m_mailer, "[IPC]") == 0)
645 	{
646 #ifdef DAEMON
647 		register int i;
648 		register u_short port;
649 
650 		if (!clever)
651 			syserr("non-clever IPC");
652 		if (pvp[2] != NULL)
653 			port = atoi(pvp[2]);
654 		else
655 			port = 0;
656 		i = makeconnection(pvp[1], port, pmfile, prfile);
657 		if (i != EX_OK)
658 		{
659 			ExitStat = i;
660 			return (-1);
661 		}
662 		else
663 			return (0);
664 #else DAEMON
665 		syserr("openmailer: no IPC");
666 		return (-1);
667 #endif DAEMON
668 	}
669 
670 	/* create a pipe to shove the mail through */
671 	if (pipe(mpvect) < 0)
672 	{
673 		syserr("openmailer: pipe (to mailer)");
674 		return (-1);
675 	}
676 
677 #ifdef SMTP
678 	/* if this mailer speaks smtp, create a return pipe */
679 	if (clever && pipe(rpvect) < 0)
680 	{
681 		syserr("openmailer: pipe (from mailer)");
682 		(void) close(mpvect[0]);
683 		(void) close(mpvect[1]);
684 		return (-1);
685 	}
686 #endif SMTP
687 
688 	/*
689 	**  Actually fork the mailer process.
690 	**	DOFORK is clever about retrying.
691 	*/
692 
693 	if (CurEnv->e_xfp != NULL)
694 		(void) fflush(CurEnv->e_xfp);		/* for debugging */
695 	(void) fflush(stdout);
696 	DOFORK(XFORK);
697 	/* pid is set by DOFORK */
698 	if (pid < 0)
699 	{
700 		/* failure */
701 		syserr("openmailer: cannot fork");
702 		(void) close(mpvect[0]);
703 		(void) close(mpvect[1]);
704 #ifdef SMTP
705 		if (clever)
706 		{
707 			(void) close(rpvect[0]);
708 			(void) close(rpvect[1]);
709 		}
710 #endif SMTP
711 		return (-1);
712 	}
713 	else if (pid == 0)
714 	{
715 		/* child -- set up input & exec mailer */
716 		/* make diagnostic output be standard output */
717 		(void) signal(SIGINT, SIG_IGN);
718 		(void) signal(SIGHUP, SIG_IGN);
719 		(void) signal(SIGTERM, SIG_DFL);
720 
721 		/* arrange to filter standard & diag output of command */
722 		if (clever)
723 		{
724 			(void) close(rpvect[0]);
725 			(void) close(1);
726 			(void) dup(rpvect[1]);
727 			(void) close(rpvect[1]);
728 		}
729 		else if (OpMode == MD_SMTP || HoldErrs)
730 		{
731 			/* put mailer output in transcript */
732 			(void) close(1);
733 			(void) dup(fileno(CurEnv->e_xfp));
734 		}
735 		(void) close(2);
736 		(void) dup(1);
737 
738 		/* arrange to get standard input */
739 		(void) close(mpvect[1]);
740 		(void) close(0);
741 		if (dup(mpvect[0]) < 0)
742 		{
743 			syserr("Cannot dup to zero!");
744 			_exit(EX_OSERR);
745 		}
746 		(void) close(mpvect[0]);
747 		if (!bitset(M_RESTR, m->m_flags))
748 		{
749 			if (ctladdr->q_uid == 0)
750 			{
751 				(void) setgid(DefGid);
752 				(void) setuid(DefUid);
753 			}
754 			else
755 			{
756 				(void) setgid(ctladdr->q_gid);
757 				(void) setuid(ctladdr->q_uid);
758 			}
759 		}
760 
761 		/*
762 		**  We have to be careful with vfork - we can't mung up the
763 		**  memory but we don't want the mailer to inherit any extra
764 		**  open files.  Chances are the mailer won't
765 		**  care about an extra file, but then again you never know.
766 		**  Actually, we would like to close(fileno(pwf)), but it's
767 		**  declared static so we can't.  But if we fclose(pwf), which
768 		**  is what endpwent does, it closes it in the parent too and
769 		**  the next getpwnam will be slower.  If you have a weird
770 		**  mailer that chokes on the extra file you should do the
771 		**  endpwent().			-MRH
772 		**
773 		**  Similar comments apply to log.  However, openlog is
774 		**  clever enough to set the FIOCLEX mode on the file,
775 		**  so it will be closed automatically on the exec.
776 		*/
777 
778 		closeall();
779 
780 		/* try to execute the mailer */
781 		execv(m->m_mailer, pvp);
782 
783 		/* syserr fails because log is closed */
784 		/* syserr("Cannot exec %s", m->m_mailer); */
785 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
786 		(void) fflush(stdout);
787 		_exit(EX_UNAVAILABLE);
788 	}
789 
790 	/*
791 	**  Set up return value.
792 	*/
793 
794 	(void) close(mpvect[0]);
795 	mfile = fdopen(mpvect[1], "w");
796 	if (clever)
797 	{
798 		(void) close(rpvect[1]);
799 		rfile = fdopen(rpvect[0], "r");
800 	}
801 
802 	*pmfile = mfile;
803 	*prfile = rfile;
804 
805 	return (pid);
806 }
807 /*
808 **  GIVERESPONSE -- Interpret an error response from a mailer
809 **
810 **	Parameters:
811 **		stat -- the status code from the mailer (high byte
812 **			only; core dumps must have been taken care of
813 **			already).
814 **		m -- the mailer descriptor for this mailer.
815 **
816 **	Returns:
817 **		none.
818 **
819 **	Side Effects:
820 **		Errors may be incremented.
821 **		ExitStat may be set.
822 */
823 
824 /*ARGSUSED*/
825 giveresponse(stat, m)
826 	int stat;
827 	register MAILER *m;
828 {
829 	register char *statmsg;
830 	extern char *SysExMsg[];
831 	register int i;
832 	extern int N_SysEx;
833 	char buf[30];
834 
835 	/*
836 	**  Compute status message from code.
837 	*/
838 
839 	i = stat - EX__BASE;
840 	if (stat == 0)
841 		statmsg = "250 Sent";
842 	else if (i < 0 || i > N_SysEx)
843 	{
844 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
845 		stat = EX_UNAVAILABLE;
846 		statmsg = buf;
847 	}
848 	else
849 		statmsg = SysExMsg[i];
850 
851 	/*
852 	**  Print the message as appropriate
853 	*/
854 
855 	if (stat == 0)
856 		message(Arpa_Info, &statmsg[4]);
857 	else if (stat == EX_TEMPFAIL)
858 		message(Arpa_Info, "deferred");
859 	else
860 	{
861 		Errors++;
862 		usrerr(statmsg);
863 	}
864 
865 	/*
866 	**  Final cleanup.
867 	**	Log a record of the transaction.  Compute the new
868 	**	ExitStat -- if we already had an error, stick with
869 	**	that.
870 	*/
871 
872 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
873 		logdelivery(&statmsg[4]);
874 
875 	if (stat != EX_TEMPFAIL)
876 		setstat(stat);
877 }
878 /*
879 **  LOGDELIVERY -- log the delivery in the system log
880 **
881 **	Parameters:
882 **		stat -- the message to print for the status
883 **
884 **	Returns:
885 **		none
886 **
887 **	Side Effects:
888 **		none
889 */
890 
891 logdelivery(stat)
892 	char *stat;
893 {
894 	extern char *pintvl();
895 
896 # ifdef LOG
897 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", CurEnv->e_id,
898 	       CurEnv->e_to, pintvl(curtime() - CurEnv->e_ctime, TRUE), stat);
899 # endif LOG
900 }
901 /*
902 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
903 **
904 **	This can be made an arbitrary message separator by changing $l
905 **
906 **	One of the ugliest hacks seen by human eyes is
907 **	contained herein: UUCP wants those stupid
908 **	"emote from <host>" lines.  Why oh why does a
909 **	well-meaning programmer such as myself have to
910 **	deal with this kind of antique garbage????
911 **
912 **	Parameters:
913 **		fp -- the file to output to.
914 **		m -- the mailer describing this entry.
915 **		crlf -- set if we want a CRLF at the end of the line.
916 **
917 **	Returns:
918 **		none
919 **
920 **	Side Effects:
921 **		outputs some text to fp.
922 */
923 
924 putfromline(fp, m, crlf)
925 	register FILE *fp;
926 	register MAILER *m;
927 {
928 	char buf[MAXLINE];
929 
930 	if (bitset(M_NHDR, m->m_flags))
931 		return;
932 
933 # ifdef UGLYUUCP
934 	if (bitset(M_UGLYUUCP, m->m_flags))
935 	{
936 		extern char *macvalue();
937 		char *sys = macvalue('g', CurEnv);
938 		char *bang = index(sys, '!');
939 
940 		if (bang == NULL)
941 			syserr("No ! in UUCP! (%s)", sys);
942 		else
943 		{
944 			*bang = '\0';
945 			expand("From $f  $d remote from $g\n", buf,
946 					&buf[sizeof buf - 1], CurEnv);
947 			*bang = '!';
948 		}
949 	}
950 	else
951 # endif UGLYUUCP
952 		expand("$l\n", buf, &buf[sizeof buf - 1], CurEnv);
953 	putline(buf, fp, crlf, bitset(M_FULLSMTP, m->m_flags));
954 }
955 /*
956 **  PUTBODY -- put the body of a message.
957 **
958 **	Parameters:
959 **		fp -- file to output onto.
960 **		m -- a mailer descriptor.
961 **		xdot -- if set, use SMTP hidden dot algorithm.
962 **		e -- the envelope to put out.
963 **
964 **	Returns:
965 **		none.
966 **
967 **	Side Effects:
968 **		The message is written onto fp.
969 */
970 
971 putbody(fp, m, xdot, e, crlf)
972 	FILE *fp;
973 	MAILER *m;
974 	bool xdot;
975 	register ENVELOPE *e;
976 {
977 	char buf[MAXLINE + 1];
978 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
979 
980 	/*
981 	**  Output the body of the message
982 	*/
983 
984 	if (e->e_dfp == NULL)
985 	{
986 		if (e->e_df != NULL)
987 		{
988 			e->e_dfp = fopen(e->e_df, "r");
989 			if (e->e_dfp == NULL)
990 				syserr("Cannot open %s", e->e_df);
991 		}
992 		else
993 			putline("<<< No Message Collected >>>", fp, crlf, fullsmtp);
994 	}
995 	if (e->e_dfp != NULL)
996 	{
997 		rewind(e->e_dfp);
998 		buf[0] = '.';
999 		while (!ferror(fp) &&
1000 		       fgets(&buf[1], sizeof buf - 1, e->e_dfp) != NULL)
1001 		{
1002 			putline((xdot && buf[1] == '.') ? buf : &buf[1], fp, crlf, fullsmtp);
1003 		}
1004 
1005 		if (ferror(e->e_dfp))
1006 		{
1007 			syserr("putbody: read error");
1008 			ExitStat = EX_IOERR;
1009 		}
1010 	}
1011 
1012 	(void) fflush(fp);
1013 	if (ferror(fp) && errno != EPIPE)
1014 	{
1015 		syserr("putbody: write error");
1016 		ExitStat = EX_IOERR;
1017 	}
1018 	errno = 0;
1019 }
1020 /*
1021 **  MAILFILE -- Send a message to a file.
1022 **
1023 **	If the file has the setuid/setgid bits set, but NO execute
1024 **	bits, sendmail will try to become the owner of that file
1025 **	rather than the real user.  Obviously, this only works if
1026 **	sendmail runs as root.
1027 **
1028 **	This could be done as a subordinate mailer, except that it
1029 **	is used implicitly to save messages in ~/dead.letter.  We
1030 **	view this as being sufficiently important as to include it
1031 **	here.  For example, if the system is dying, we shouldn't have
1032 **	to create another process plus some pipes to save the message.
1033 **
1034 **	Parameters:
1035 **		filename -- the name of the file to send to.
1036 **		ctladdr -- the controlling address header -- includes
1037 **			the userid/groupid to be when sending.
1038 **
1039 **	Returns:
1040 **		The exit code associated with the operation.
1041 **
1042 **	Side Effects:
1043 **		none.
1044 */
1045 
1046 mailfile(filename, ctladdr)
1047 	char *filename;
1048 	ADDRESS *ctladdr;
1049 {
1050 	register FILE *f;
1051 	register int pid;
1052 
1053 	/*
1054 	**  Fork so we can change permissions here.
1055 	**	Note that we MUST use fork, not vfork, because of
1056 	**	the complications of calling subroutines, etc.
1057 	*/
1058 
1059 	DOFORK(fork);
1060 
1061 	if (pid < 0)
1062 		return (EX_OSERR);
1063 	else if (pid == 0)
1064 	{
1065 		/* child -- actually write to file */
1066 		struct stat stb;
1067 
1068 		(void) signal(SIGINT, SIG_DFL);
1069 		(void) signal(SIGHUP, SIG_DFL);
1070 		(void) signal(SIGTERM, SIG_DFL);
1071 		umask(OldUmask);
1072 		if (stat(filename, &stb) < 0)
1073 			stb.st_mode = 0666;
1074 		if (bitset(0111, stb.st_mode))
1075 			exit(EX_CANTCREAT);
1076 		if (ctladdr == NULL)
1077 			ctladdr = &CurEnv->e_from;
1078 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1079 		{
1080 			if (ctladdr->q_uid == 0)
1081 				(void) setgid(DefGid);
1082 			else
1083 				(void) setgid(ctladdr->q_gid);
1084 		}
1085 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1086 		{
1087 			if (ctladdr->q_uid == 0)
1088 				(void) setuid(DefUid);
1089 			else
1090 				(void) setuid(ctladdr->q_uid);
1091 		}
1092 		f = dfopen(filename, "a");
1093 		if (f == NULL)
1094 			exit(EX_CANTCREAT);
1095 
1096 		putfromline(f, ProgMailer, FALSE);
1097 		(*CurEnv->e_puthdr)(f, ProgMailer, CurEnv, FALSE);
1098 		fputs("\n", f);
1099 		(*CurEnv->e_putbody)(f, ProgMailer, FALSE, CurEnv, FALSE);
1100 		fputs("\n", f);
1101 		(void) fclose(f);
1102 		(void) fflush(stdout);
1103 
1104 		/* reset ISUID & ISGID bits for paranoid systems */
1105 		(void) chmod(filename, (int) stb.st_mode);
1106 		exit(EX_OK);
1107 		/*NOTREACHED*/
1108 	}
1109 	else
1110 	{
1111 		/* parent -- wait for exit status */
1112 		int st;
1113 
1114 		st = waitfor(pid);
1115 		if ((st & 0377) != 0)
1116 			return (EX_UNAVAILABLE);
1117 		else
1118 			return ((st >> 8) & 0377);
1119 	}
1120 }
1121 /*
1122 **  SENDALL -- actually send all the messages.
1123 **
1124 **	Parameters:
1125 **		e -- the envelope to send.
1126 **		mode -- the delivery mode to use.
1127 **
1128 **	Returns:
1129 **		none.
1130 **
1131 **	Side Effects:
1132 **		Scans the send lists and sends everything it finds.
1133 **		Delivers any appropriate error messages.
1134 **		If we are running in a non-interactive mode, takes the
1135 **			appropriate action.
1136 */
1137 
1138 sendall(e, mode)
1139 	ENVELOPE *e;
1140 	char mode;
1141 {
1142 	register ADDRESS *q;
1143 	bool oldverbose;
1144 	int pid;
1145 
1146 #ifdef DEBUG
1147 	if (tTd(13, 1))
1148 	{
1149 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1150 		printaddr(e->e_sendqueue, TRUE);
1151 	}
1152 #endif DEBUG
1153 
1154 	/*
1155 	**  Do any preprocessing necessary for the mode we are running.
1156 	**	Check to make sure the hop count is reasonable.
1157 	**	Delete sends to the sender in mailing lists.
1158 	*/
1159 
1160 	CurEnv = e;
1161 
1162 	if (e->e_hopcount > MAXHOP)
1163 	{
1164 		syserr("sendall: too many hops (%d max)", MAXHOP);
1165 		return;
1166 	}
1167 
1168 	if (!MeToo)
1169 	{
1170 		e->e_from.q_flags |= QDONTSEND;
1171 		recipient(&e->e_from, &e->e_sendqueue);
1172 	}
1173 
1174 # ifdef QUEUE
1175 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1176 	     (mode != SM_VERIFY && SuperSafe)) &&
1177 	    !bitset(EF_INQUEUE, e->e_flags))
1178 		queueup(e, TRUE, mode == SM_QUEUE);
1179 #endif QUEUE
1180 
1181 	oldverbose = Verbose;
1182 	switch (mode)
1183 	{
1184 	  case SM_VERIFY:
1185 		Verbose = TRUE;
1186 		break;
1187 
1188 	  case SM_QUEUE:
1189 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1190 		return;
1191 
1192 	  case SM_FORK:
1193 		if (e->e_xfp != NULL)
1194 			(void) fflush(e->e_xfp);
1195 		pid = fork();
1196 		if (pid < 0)
1197 		{
1198 			mode = SM_DELIVER;
1199 			break;
1200 		}
1201 		else if (pid > 0)
1202 		{
1203 			/* be sure we leave the temp files to our child */
1204 			e->e_id = e->e_df = NULL;
1205 			return;
1206 		}
1207 
1208 		/* double fork to avoid zombies */
1209 		if (fork() > 0)
1210 			exit(EX_OK);
1211 
1212 		/* be sure we are immune from the terminal */
1213 		disconnect();
1214 
1215 		break;
1216 	}
1217 
1218 	/*
1219 	**  Run through the list and send everything.
1220 	*/
1221 
1222 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1223 	{
1224 		if (mode == SM_VERIFY)
1225 		{
1226 			e->e_to = q->q_paddr;
1227 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1228 				message(Arpa_Info, "deliverable");
1229 		}
1230 		else
1231 			(void) deliver(e, q);
1232 	}
1233 	Verbose = oldverbose;
1234 
1235 	/*
1236 	**  Now run through and check for errors.
1237 	*/
1238 
1239 	if (mode == SM_VERIFY)
1240 		return;
1241 
1242 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1243 	{
1244 		register ADDRESS *qq;
1245 
1246 # ifdef DEBUG
1247 		if (tTd(13, 3))
1248 		{
1249 			printf("Checking ");
1250 			printaddr(q, FALSE);
1251 		}
1252 # endif DEBUG
1253 
1254 		/* only send errors if the message failed */
1255 		if (!bitset(QBADADDR, q->q_flags))
1256 			continue;
1257 
1258 		/* we have an address that failed -- find the parent */
1259 		for (qq = q; qq != NULL; qq = qq->q_alias)
1260 		{
1261 			char obuf[MAXNAME + 6];
1262 			extern char *aliaslookup();
1263 
1264 			/* we can only have owners for local addresses */
1265 			if (!bitset(M_LOCAL, qq->q_mailer->m_flags))
1266 				continue;
1267 
1268 			/* see if the owner list exists */
1269 			(void) strcpy(obuf, "owner-");
1270 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1271 				(void) strcat(obuf, "owner");
1272 			else
1273 				(void) strcat(obuf, qq->q_user);
1274 			if (aliaslookup(obuf) == NULL)
1275 				continue;
1276 
1277 # ifdef DEBUG
1278 			if (tTd(13, 4))
1279 				printf("Errors to %s\n", obuf);
1280 # endif DEBUG
1281 
1282 			/* owner list exists -- add it to the error queue */
1283 			sendtolist(obuf, (ADDRESS *) NULL, &e->e_errorqueue);
1284 			ErrorMode == EM_MAIL;
1285 			break;
1286 		}
1287 
1288 		/* if we did not find an owner, send to the sender */
1289 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1290 			sendtolist(e->e_from.q_paddr, qq, &e->e_errorqueue);
1291 	}
1292 
1293 	if (mode == SM_FORK)
1294 		finis();
1295 }
1296