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