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