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