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