1/*
2 * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers.
3 *	All rights reserved.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5 * Copyright (c) 1988, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
11 *
12 */
13
14#pragma ident	"%Z%%M%	%I%	%E% SMI"
15
16#include <sendmail.h>
17
18SM_RCSID("@(#)$Id: recipient.c,v 8.349 2007/07/10 17:01:22 ca Exp $")
19
20static void	includetimeout __P((int));
21static ADDRESS	*self_reference __P((ADDRESS *));
22static int	sortexpensive __P((ADDRESS *, ADDRESS *));
23static int	sortbysignature __P((ADDRESS *, ADDRESS *));
24static int	sorthost __P((ADDRESS *, ADDRESS *));
25
26typedef int	sortfn_t __P((ADDRESS *, ADDRESS *));
27
28/*
29**  SORTHOST -- strcmp()-like func for host portion of an ADDRESS
30**
31**	Parameters:
32**		xx -- first ADDRESS
33**		yy -- second ADDRESS
34**
35**	Returns:
36**		<0 when xx->q_host is less than yy->q_host
37**		>0 when xx->q_host is greater than yy->q_host
38**		0 when equal
39*/
40
41static int
42sorthost(xx, yy)
43	register ADDRESS *xx;
44	register ADDRESS *yy;
45{
46#if _FFR_HOST_SORT_REVERSE
47	/* XXX maybe compare hostnames from the end? */
48	return sm_strrevcasecmp(xx->q_host, yy->q_host);
49#else /* _FFR_HOST_SORT_REVERSE */
50	return sm_strcasecmp(xx->q_host, yy->q_host);
51#endif /* _FFR_HOST_SORT_REVERSE */
52}
53
54/*
55**  SORTEXPENSIVE -- strcmp()-like func for expensive mailers
56**
57**  The mailer has been noted already as "expensive" for 'xx'. This
58**  will give a result relative to 'yy'. Expensive mailers get rated
59**  "greater than" non-expensive mailers because during the delivery phase
60**  it will get queued -- no use it getting in the way of less expensive
61**  recipients. We avoid an MX RR lookup when both 'xx' and 'yy' are
62**  expensive since an MX RR lookup happens when extracted from the queue
63**  later.
64**
65**	Parameters:
66**		xx -- first ADDRESS
67**		yy -- second ADDRESS
68**
69**	Returns:
70**		<0 when xx->q_host is less than yy->q_host and both are
71**			expensive
72**		>0 when xx->q_host is greater than yy->q_host, or when
73**			'yy' is non-expensive
74**		0 when equal (by expense and q_host)
75*/
76
77static int
78sortexpensive(xx, yy)
79	ADDRESS *xx;
80	ADDRESS *yy;
81{
82	if (!bitnset(M_EXPENSIVE, yy->q_mailer->m_flags))
83		return 1; /* xx should go later */
84#if _FFR_HOST_SORT_REVERSE
85	/* XXX maybe compare hostnames from the end? */
86	return sm_strrevcasecmp(xx->q_host, yy->q_host);
87#else /* _FFR_HOST_SORT_REVERSE */
88	return sm_strcasecmp(xx->q_host, yy->q_host);
89#endif /* _FFR_HOST_SORT_REVERSE */
90}
91
92/*
93**  SORTBYSIGNATURE -- a strcmp()-like func for q_mailer and q_host in ADDRESS
94**
95**	Parameters:
96**		xx -- first ADDRESS
97**		yy -- second ADDRESS
98**
99**	Returns:
100**		0 when the "signature"'s are same
101**		<0 when xx->q_signature is less than yy->q_signature
102**		>0 when xx->q_signature is greater than yy->q_signature
103**
104**	Side Effect:
105**		May set ADDRESS pointer for q_signature if not already set.
106*/
107
108static int
109sortbysignature(xx, yy)
110	ADDRESS *xx;
111	ADDRESS *yy;
112{
113	register int ret;
114
115	/* Let's avoid redoing the signature over and over again */
116	if (xx->q_signature == NULL)
117		xx->q_signature = hostsignature(xx->q_mailer, xx->q_host);
118	if (yy->q_signature == NULL)
119		yy->q_signature = hostsignature(yy->q_mailer, yy->q_host);
120	ret = strcmp(xx->q_signature, yy->q_signature);
121
122	/*
123	**  If the two signatures are the same then we will return a sort
124	**  value based on 'q_user'. But note that we have reversed xx and yy
125	**  on purpose. This additional compare helps reduce the number of
126	**  sameaddr() calls and loops in recipient() for the case when
127	**  the rcpt list has been provided already in-order.
128	*/
129
130	if (ret == 0)
131		return strcmp(yy->q_user, xx->q_user);
132	else
133		return ret;
134}
135
136/*
137**  SENDTOLIST -- Designate a send list.
138**
139**	The parameter is a comma-separated list of people to send to.
140**	This routine arranges to send to all of them.
141**
142**	Parameters:
143**		list -- the send list.
144**		ctladdr -- the address template for the person to
145**			send to -- effective uid/gid are important.
146**			This is typically the alias that caused this
147**			expansion.
148**		sendq -- a pointer to the head of a queue to put
149**			these people into.
150**		aliaslevel -- the current alias nesting depth -- to
151**			diagnose loops.
152**		e -- the envelope in which to add these recipients.
153**
154**	Returns:
155**		The number of addresses actually on the list.
156*/
157
158/* q_flags bits inherited from ctladdr */
159#define QINHERITEDBITS	(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY)
160
161int
162sendtolist(list, ctladdr, sendq, aliaslevel, e)
163	char *list;
164	ADDRESS *ctladdr;
165	ADDRESS **sendq;
166	int aliaslevel;
167	register ENVELOPE *e;
168{
169	register char *p;
170	register ADDRESS *SM_NONVOLATILE al; /* list of addresses to send to */
171	SM_NONVOLATILE char delimiter;		/* the address delimiter */
172	SM_NONVOLATILE int naddrs;
173	SM_NONVOLATILE int i;
174	char *endp;
175	char *oldto = e->e_to;
176	char *SM_NONVOLATILE bufp;
177	char buf[MAXNAME + 1];
178
179	if (list == NULL)
180	{
181		syserr("sendtolist: null list");
182		return 0;
183	}
184
185	if (tTd(25, 1))
186	{
187		sm_dprintf("sendto: %s\n   ctladdr=", list);
188		printaddr(sm_debug_file(), ctladdr, false);
189	}
190
191	/* heuristic to determine old versus new style addresses */
192	if (ctladdr == NULL &&
193	    (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
194	     strchr(list, '<') != NULL || strchr(list, '(') != NULL))
195		e->e_flags &= ~EF_OLDSTYLE;
196	delimiter = ' ';
197	if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
198		delimiter = ',';
199
200	al = NULL;
201	naddrs = 0;
202
203	/* make sure we have enough space to copy the string */
204	i = strlen(list) + 1;
205	if (i <= sizeof(buf))
206	{
207		bufp = buf;
208		i = sizeof(buf);
209	}
210	else
211		bufp = sm_malloc_x(i);
212	endp = bufp + i;
213
214	SM_TRY
215	{
216		(void) sm_strlcpy(bufp, denlstring(list, false, true), i);
217
218		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
219		for (p = bufp; *p != '\0'; )
220		{
221			auto char *delimptr;
222			register ADDRESS *a;
223
224			SM_ASSERT(p < endp);
225
226			/* parse the address */
227			while ((isascii(*p) && isspace(*p)) || *p == ',')
228				p++;
229			SM_ASSERT(p < endp);
230			a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter,
231				      &delimptr, e, true);
232			p = delimptr;
233			SM_ASSERT(p < endp);
234			if (a == NULL)
235				continue;
236			a->q_next = al;
237			a->q_alias = ctladdr;
238
239			/* arrange to inherit attributes from parent */
240			if (ctladdr != NULL)
241			{
242				ADDRESS *b;
243
244				/* self reference test */
245				if (sameaddr(ctladdr, a))
246				{
247					if (tTd(27, 5))
248					{
249						sm_dprintf("sendtolist: QSELFREF ");
250						printaddr(sm_debug_file(), ctladdr, false);
251					}
252					ctladdr->q_flags |= QSELFREF;
253				}
254
255				/* check for address loops */
256				b = self_reference(a);
257				if (b != NULL)
258				{
259					b->q_flags |= QSELFREF;
260					if (tTd(27, 5))
261					{
262						sm_dprintf("sendtolist: QSELFREF ");
263						printaddr(sm_debug_file(), b, false);
264					}
265					if (a != b)
266					{
267						if (tTd(27, 5))
268						{
269							sm_dprintf("sendtolist: QS_DONTSEND ");
270							printaddr(sm_debug_file(), a, false);
271						}
272						a->q_state = QS_DONTSEND;
273						b->q_flags |= a->q_flags & QNOTREMOTE;
274						continue;
275					}
276				}
277
278				/* full name */
279				if (a->q_fullname == NULL)
280					a->q_fullname = ctladdr->q_fullname;
281
282				/* various flag bits */
283				a->q_flags &= ~QINHERITEDBITS;
284				a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
285
286				/* DSN recipient information */
287				a->q_finalrcpt = ctladdr->q_finalrcpt;
288				a->q_orcpt = ctladdr->q_orcpt;
289			}
290
291			al = a;
292		}
293
294		/* arrange to send to everyone on the local send list */
295		while (al != NULL)
296		{
297			register ADDRESS *a = al;
298
299			al = a->q_next;
300			a = recipient(a, sendq, aliaslevel, e);
301			naddrs++;
302		}
303	}
304	SM_FINALLY
305	{
306		e->e_to = oldto;
307		if (bufp != buf)
308			sm_free(bufp);
309		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
310	}
311	SM_END_TRY
312	return naddrs;
313}
314
315#if MILTER
316/*
317**  REMOVEFROMLIST -- Remove addresses from a send list.
318**
319**	The parameter is a comma-separated list of recipients to remove.
320**	Note that it only deletes matching addresses.  If those addresses
321**	have been expanded already in the sendq, it won't mark the
322**	expanded recipients as QS_REMOVED.
323**
324**	Parameters:
325**		list -- the list to remove.
326**		sendq -- a pointer to the head of a queue to remove
327**			these addresses from.
328**		e -- the envelope in which to remove these recipients.
329**
330**	Returns:
331**		The number of addresses removed from the list.
332**
333*/
334
335int
336removefromlist(list, sendq, e)
337	char *list;
338	ADDRESS **sendq;
339	ENVELOPE *e;
340{
341	SM_NONVOLATILE char delimiter;		/* the address delimiter */
342	SM_NONVOLATILE int naddrs;
343	SM_NONVOLATILE int i;
344	char *p;
345	char *oldto = e->e_to;
346	char *SM_NONVOLATILE bufp;
347	char buf[MAXNAME + 1];
348
349	if (list == NULL)
350	{
351		syserr("removefromlist: null list");
352		return 0;
353	}
354
355	if (tTd(25, 1))
356		sm_dprintf("removefromlist: %s\n", list);
357
358	/* heuristic to determine old versus new style addresses */
359	if (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
360	    strchr(list, '<') != NULL || strchr(list, '(') != NULL)
361		e->e_flags &= ~EF_OLDSTYLE;
362	delimiter = ' ';
363	if (!bitset(EF_OLDSTYLE, e->e_flags))
364		delimiter = ',';
365
366	naddrs = 0;
367
368	/* make sure we have enough space to copy the string */
369	i = strlen(list) + 1;
370	if (i <= sizeof(buf))
371	{
372		bufp = buf;
373		i = sizeof(buf);
374	}
375	else
376		bufp = sm_malloc_x(i);
377
378	SM_TRY
379	{
380		(void) sm_strlcpy(bufp, denlstring(list, false, true), i);
381
382#if _FFR_ADDR_TYPE_MODES
383		if (AddrTypeModes)
384			macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
385				  "e r d");
386		else
387#endif /* _FFR_ADDR_TYPE_MODES */
388		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
389		for (p = bufp; *p != '\0'; )
390		{
391			ADDRESS a;	/* parsed address to be removed */
392			ADDRESS *q;
393			ADDRESS **pq;
394			char *delimptr;
395
396			/* parse the address */
397			while ((isascii(*p) && isspace(*p)) || *p == ',')
398				p++;
399			if (parseaddr(p, &a, RF_COPYALL|RF_RM_ADDR,
400				      delimiter, &delimptr, e, true) == NULL)
401			{
402				p = delimptr;
403				continue;
404			}
405			p = delimptr;
406			for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
407			{
408				if (!QS_IS_DEAD(q->q_state) &&
409				    (sameaddr(q, &a) ||
410				     strcmp(q->q_paddr, a.q_paddr) == 0))
411				{
412					if (tTd(25, 5))
413					{
414						sm_dprintf("removefromlist: QS_REMOVED ");
415						printaddr(sm_debug_file(), &a, false);
416					}
417					q->q_state = QS_REMOVED;
418					naddrs++;
419					break;
420				}
421			}
422		}
423	}
424	SM_FINALLY
425	{
426		e->e_to = oldto;
427		if (bufp != buf)
428			sm_free(bufp);
429		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
430	}
431	SM_END_TRY
432	return naddrs;
433}
434#endif /* MILTER */
435
436/*
437**  RECIPIENT -- Designate a message recipient
438**	Saves the named person for future mailing (after some checks).
439**
440**	Parameters:
441**		new -- the (preparsed) address header for the recipient.
442**		sendq -- a pointer to the head of a queue to put the
443**			recipient in.  Duplicate suppression is done
444**			in this queue.
445**		aliaslevel -- the current alias nesting depth.
446**		e -- the current envelope.
447**
448**	Returns:
449**		The actual address in the queue.  This will be "a" if
450**		the address is not a duplicate, else the original address.
451**
452*/
453
454ADDRESS *
455recipient(new, sendq, aliaslevel, e)
456	register ADDRESS *new;
457	register ADDRESS **sendq;
458	int aliaslevel;
459	register ENVELOPE *e;
460{
461	register ADDRESS *q;
462	ADDRESS **pq;
463	ADDRESS **prev;
464	register struct mailer *m;
465	register char *p;
466	int i, buflen;
467	bool quoted;		/* set if the addr has a quote bit */
468	bool insert;
469	int findusercount;
470	bool initialdontsend;
471	char *buf;
472	char buf0[MAXNAME + 1];		/* unquoted image of the user name */
473	sortfn_t *sortfn;
474
475	p = NULL;
476	quoted = false;
477	insert = false;
478	findusercount = 0;
479	initialdontsend = QS_IS_DEAD(new->q_state);
480	e->e_to = new->q_paddr;
481	m = new->q_mailer;
482	errno = 0;
483	if (aliaslevel == 0)
484		new->q_flags |= QPRIMARY;
485	if (tTd(26, 1))
486	{
487		sm_dprintf("\nrecipient (%d): ", aliaslevel);
488		printaddr(sm_debug_file(), new, false);
489	}
490
491	/* if this is primary, use it as original recipient */
492	if (new->q_alias == NULL)
493	{
494		if (e->e_origrcpt == NULL)
495			e->e_origrcpt = new->q_paddr;
496		else if (e->e_origrcpt != new->q_paddr)
497			e->e_origrcpt = "";
498	}
499
500	/* find parent recipient for finalrcpt and orcpt */
501	for (q = new; q->q_alias != NULL; q = q->q_alias)
502		continue;
503
504	/* find final recipient DSN address */
505	if (new->q_finalrcpt == NULL &&
506	    e->e_from.q_mailer != NULL)
507	{
508		char frbuf[MAXLINE];
509
510		p = e->e_from.q_mailer->m_addrtype;
511		if (p == NULL)
512			p = "rfc822";
513		if (sm_strcasecmp(p, "rfc822") != 0)
514		{
515			(void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s",
516					   q->q_mailer->m_addrtype,
517					   q->q_user);
518		}
519		else if (strchr(q->q_user, '@') != NULL)
520		{
521			(void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s",
522					   p, q->q_user);
523		}
524		else if (strchr(q->q_paddr, '@') != NULL)
525		{
526			char *qp;
527			bool b;
528
529			qp = q->q_paddr;
530
531			/* strip brackets from address */
532			b = false;
533			if (*qp == '<')
534			{
535				b = qp[strlen(qp) - 1] == '>';
536				if (b)
537					qp[strlen(qp) - 1] = '\0';
538				qp++;
539			}
540			(void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s",
541					   p, qp);
542
543			/* undo damage */
544			if (b)
545				qp[strlen(qp)] = '>';
546		}
547		else
548		{
549			(void) sm_snprintf(frbuf, sizeof(frbuf),
550					   "%s; %.700s@%.100s",
551					   p, q->q_user, MyHostName);
552		}
553		new->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool, frbuf);
554	}
555
556#if _FFR_GEN_ORCPT
557	/* set ORCPT DSN arg if not already set */
558	if (new->q_orcpt == NULL)
559	{
560		/* check for an existing ORCPT */
561		if (q->q_orcpt != NULL)
562			new->q_orcpt = q->q_orcpt;
563		else
564		{
565			/* make our own */
566			bool b = false;
567			char *qp;
568			char obuf[MAXLINE];
569
570			if (e->e_from.q_mailer != NULL)
571				p = e->e_from.q_mailer->m_addrtype;
572			if (p == NULL)
573				p = "rfc822";
574			(void) sm_strlcpyn(obuf, sizeof(obuf), 2, p, ";");
575
576			qp = q->q_paddr;
577
578			/* FFR: Needs to strip comments from stdin addrs */
579
580			/* strip brackets from address */
581			if (*qp == '<')
582			{
583				b = qp[strlen(qp) - 1] == '>';
584				if (b)
585					qp[strlen(qp) - 1] = '\0';
586				qp++;
587			}
588
589			p = xtextify(denlstring(qp, true, false), "=");
590
591			if (sm_strlcat(obuf, p, sizeof(obuf)) >= sizeof(obuf))
592			{
593				/* if too big, don't use it */
594				obuf[0] = '\0';
595			}
596
597			/* undo damage */
598			if (b)
599				qp[strlen(qp)] = '>';
600
601			if (obuf[0] != '\0')
602				new->q_orcpt =
603					sm_rpool_strdup_x(e->e_rpool, obuf);
604		}
605	}
606#endif /* _FFR_GEN_ORCPT */
607
608	/* break aliasing loops */
609	if (aliaslevel > MaxAliasRecursion)
610	{
611		new->q_state = QS_BADADDR;
612		new->q_status = "5.4.6";
613		if (new->q_alias != NULL)
614		{
615			new->q_alias->q_state = QS_BADADDR;
616			new->q_alias->q_status = "5.4.6";
617		}
618		if ((SuprErrs || !LogUsrErrs) && LogLevel > 0)
619		{
620			sm_syslog(LOG_ERR, e->e_id,
621				"aliasing/forwarding loop broken: %s (%d aliases deep; %d max)",
622				FileName != NULL ? FileName : "", aliaslevel,
623				MaxAliasRecursion);
624		}
625		usrerrenh(new->q_status,
626			  "554 aliasing/forwarding loop broken (%d aliases deep; %d max)",
627			  aliaslevel, MaxAliasRecursion);
628		return new;
629	}
630
631	/*
632	**  Finish setting up address structure.
633	*/
634
635	/* get unquoted user for file, program or user.name check */
636	i = strlen(new->q_user);
637	if (i >= sizeof(buf0))
638	{
639		buflen = i + 1;
640		buf = xalloc(buflen);
641	}
642	else
643	{
644		buf = buf0;
645		buflen = sizeof(buf0);
646	}
647	(void) sm_strlcpy(buf, new->q_user, buflen);
648	for (p = buf; *p != '\0' && !quoted; p++)
649	{
650		if (*p == '\\')
651			quoted = true;
652	}
653	stripquotes(buf);
654
655	/* check for direct mailing to restricted mailers */
656	if (m == ProgMailer)
657	{
658		if (new->q_alias == NULL || UseMSP ||
659		    bitset(EF_UNSAFE, e->e_flags))
660		{
661			new->q_state = QS_BADADDR;
662			new->q_status = "5.7.1";
663			usrerrenh(new->q_status,
664				  "550 Cannot mail directly to programs");
665		}
666		else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
667		{
668			new->q_state = QS_BADADDR;
669			new->q_status = "5.7.1";
670			if (new->q_alias->q_ruser == NULL)
671				usrerrenh(new->q_status,
672					  "550 UID %d is an unknown user: cannot mail to programs",
673					  new->q_alias->q_uid);
674			else
675				usrerrenh(new->q_status,
676					  "550 User %s@%s doesn't have a valid shell for mailing to programs",
677					  new->q_alias->q_ruser, MyHostName);
678		}
679		else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
680		{
681			new->q_state = QS_BADADDR;
682			new->q_status = "5.7.1";
683			new->q_rstatus = "550 Unsafe for mailing to programs";
684			usrerrenh(new->q_status,
685				  "550 Address %s is unsafe for mailing to programs",
686				  new->q_alias->q_paddr);
687		}
688	}
689
690	/*
691	**  Look up this person in the recipient list.
692	**	If they are there already, return, otherwise continue.
693	**	If the list is empty, just add it.  Notice the cute
694	**	hack to make from addresses suppress things correctly:
695	**	the QS_DUPLICATE state will be set in the send list.
696	**	[Please note: the emphasis is on "hack."]
697	*/
698
699	prev = NULL;
700
701	/*
702	**  If this message is going to the queue or FastSplit is set
703	**  and it is the first try and the envelope hasn't split, then we
704	**  avoid doing an MX RR lookup now because one will be done when the
705	**  message is extracted from the queue later. It can go to the queue
706	**  because all messages are going to the queue or this mailer of
707	**  the current recipient is marked expensive.
708	*/
709
710	if (UseMSP || WILL_BE_QUEUED(e->e_sendmode) ||
711	    (!bitset(EF_SPLIT, e->e_flags) && e->e_ntries == 0 &&
712	     FastSplit > 0))
713		sortfn = sorthost;
714	else if (NoConnect && bitnset(M_EXPENSIVE, new->q_mailer->m_flags))
715		sortfn = sortexpensive;
716	else
717		sortfn = sortbysignature;
718
719	for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
720	{
721		/*
722		**  If address is "less than" it should be inserted now.
723		**  If address is "greater than" current comparison it'll
724		**  insert later in the list; so loop again (if possible).
725		**  If address is "equal" (different equal than sameaddr()
726		**  call) then check if sameaddr() will be true.
727		**  Because this list is now sorted, it'll mean fewer
728		**  comparisons and fewer loops which is important for more
729		**  recipients.
730		*/
731
732		i = (*sortfn)(new, q);
733		if (i == 0) /* equal */
734		{
735			/*
736			**  Sortbysignature() has said that the two have
737			**  equal MX RR's and the same user. Calling sameaddr()
738			**  now checks if the two hosts are as identical as the
739			**  MX RR's are (which might not be the case)
740			**  before saying these are the identical addresses.
741			*/
742
743			if (sameaddr(q, new) &&
744			    (bitset(QRCPTOK, q->q_flags) ||
745			     !bitset(QPRIMARY, q->q_flags)))
746			{
747				if (tTd(26, 1))
748				{
749					sm_dprintf("%s in sendq: ",
750						   new->q_paddr);
751					printaddr(sm_debug_file(), q, false);
752				}
753				if (!bitset(QPRIMARY, q->q_flags))
754				{
755					if (!QS_IS_DEAD(new->q_state))
756						message("duplicate suppressed");
757					else
758						q->q_state = QS_DUPLICATE;
759					q->q_flags |= new->q_flags;
760				}
761				else if (bitset(QSELFREF, q->q_flags)
762					 || q->q_state == QS_REMOVED)
763				{
764					/*
765					**  If an earlier milter removed the
766					**  address, a later one can still add
767					**  it back.
768					*/
769
770					q->q_state = new->q_state;
771					q->q_flags |= new->q_flags;
772				}
773				new = q;
774				goto done;
775			}
776		}
777		else if (i < 0) /* less than */
778		{
779			insert = true;
780			break;
781		}
782		prev = pq;
783	}
784
785	/* pq should point to an address, never NULL */
786	SM_ASSERT(pq != NULL);
787
788	/* add address on list */
789	if (insert)
790	{
791		/*
792		**  insert before 'pq'. Only possible when at least 1
793		**  ADDRESS is in the list already.
794		*/
795
796		new->q_next = *pq;
797		if (prev == NULL)
798			*sendq = new; /* To be the first ADDRESS */
799		else
800			(*prev)->q_next = new;
801	}
802	else
803	{
804		/*
805		**  Place in list at current 'pq' position. Possible
806		**  when there are 0 or more ADDRESS's in the list.
807		*/
808
809		new->q_next = NULL;
810		*pq = new;
811	}
812
813	/* added a new address: clear split flag */
814	e->e_flags &= ~EF_SPLIT;
815
816	/*
817	**  Alias the name and handle special mailer types.
818	*/
819
820  trylocaluser:
821	if (tTd(29, 7))
822	{
823		sm_dprintf("at trylocaluser: ");
824		printaddr(sm_debug_file(), new, false);
825	}
826
827	if (!QS_IS_OK(new->q_state))
828	{
829		if (QS_IS_UNDELIVERED(new->q_state))
830			e->e_nrcpts++;
831		goto testselfdestruct;
832	}
833
834	if (m == InclMailer)
835	{
836		new->q_state = QS_INCLUDED;
837		if (new->q_alias == NULL || UseMSP ||
838		    bitset(EF_UNSAFE, e->e_flags))
839		{
840			new->q_state = QS_BADADDR;
841			new->q_status = "5.7.1";
842			usrerrenh(new->q_status,
843				  "550 Cannot mail directly to :include:s");
844		}
845		else
846		{
847			int ret;
848
849			message("including file %s", new->q_user);
850			ret = include(new->q_user, false, new,
851				      sendq, aliaslevel, e);
852			if (transienterror(ret))
853			{
854				if (LogLevel > 2)
855					sm_syslog(LOG_ERR, e->e_id,
856						  "include %s: transient error: %s",
857						  shortenstring(new->q_user,
858								MAXSHORTSTR),
859								sm_errstring(ret));
860				new->q_state = QS_QUEUEUP;
861				usrerr("451 4.2.4 Cannot open %s: %s",
862					shortenstring(new->q_user,
863						      MAXSHORTSTR),
864					sm_errstring(ret));
865			}
866			else if (ret != 0)
867			{
868				new->q_state = QS_BADADDR;
869				new->q_status = "5.2.4";
870				usrerrenh(new->q_status,
871					  "550 Cannot open %s: %s",
872					  shortenstring(new->q_user,
873							MAXSHORTSTR),
874					  sm_errstring(ret));
875			}
876		}
877	}
878	else if (m == FileMailer)
879	{
880		/* check if allowed */
881		if (new->q_alias == NULL || UseMSP ||
882		    bitset(EF_UNSAFE, e->e_flags))
883		{
884			new->q_state = QS_BADADDR;
885			new->q_status = "5.7.1";
886			usrerrenh(new->q_status,
887				  "550 Cannot mail directly to files");
888		}
889		else if (bitset(QBOGUSSHELL, new->q_alias->q_flags))
890		{
891			new->q_state = QS_BADADDR;
892			new->q_status = "5.7.1";
893			if (new->q_alias->q_ruser == NULL)
894				usrerrenh(new->q_status,
895					  "550 UID %d is an unknown user: cannot mail to files",
896					  new->q_alias->q_uid);
897			else
898				usrerrenh(new->q_status,
899					  "550 User %s@%s doesn't have a valid shell for mailing to files",
900					  new->q_alias->q_ruser, MyHostName);
901		}
902		else if (bitset(QUNSAFEADDR, new->q_alias->q_flags))
903		{
904			new->q_state = QS_BADADDR;
905			new->q_status = "5.7.1";
906			new->q_rstatus = "550 Unsafe for mailing to files";
907			usrerrenh(new->q_status,
908				  "550 Address %s is unsafe for mailing to files",
909				  new->q_alias->q_paddr);
910		}
911	}
912
913	/* try aliasing */
914	if (!quoted && QS_IS_OK(new->q_state) &&
915	    bitnset(M_ALIASABLE, m->m_flags))
916		alias(new, sendq, aliaslevel, e);
917
918#if USERDB
919	/* if not aliased, look it up in the user database */
920	if (!bitset(QNOTREMOTE, new->q_flags) &&
921	    QS_IS_SENDABLE(new->q_state) &&
922	    bitnset(M_CHECKUDB, m->m_flags))
923	{
924		if (udbexpand(new, sendq, aliaslevel, e) == EX_TEMPFAIL)
925		{
926			new->q_state = QS_QUEUEUP;
927			if (e->e_message == NULL)
928				e->e_message = sm_rpool_strdup_x(e->e_rpool,
929						"Deferred: user database error");
930			if (new->q_message == NULL)
931				new->q_message = "Deferred: user database error";
932			if (LogLevel > 8)
933				sm_syslog(LOG_INFO, e->e_id,
934					  "deferred: udbexpand: %s",
935					  sm_errstring(errno));
936			message("queued (user database error): %s",
937				sm_errstring(errno));
938			e->e_nrcpts++;
939			goto testselfdestruct;
940		}
941	}
942#endif /* USERDB */
943
944	/*
945	**  If we have a level two config file, then pass the name through
946	**  Ruleset 5 before sending it off.  Ruleset 5 has the right
947	**  to rewrite it to another mailer.  This gives us a hook
948	**  after local aliasing has been done.
949	*/
950
951	if (tTd(29, 5))
952	{
953		sm_dprintf("recipient: testing local?  cl=%d, rr5=%p\n\t",
954			   ConfigLevel, RewriteRules[5]);
955		printaddr(sm_debug_file(), new, false);
956	}
957	if (ConfigLevel >= 2 && RewriteRules[5] != NULL &&
958	    bitnset(M_TRYRULESET5, m->m_flags) &&
959	    !bitset(QNOTREMOTE, new->q_flags) &&
960	    QS_IS_OK(new->q_state))
961	{
962		maplocaluser(new, sendq, aliaslevel + 1, e);
963	}
964
965	/*
966	**  If it didn't get rewritten to another mailer, go ahead
967	**  and deliver it.
968	*/
969
970	if (QS_IS_OK(new->q_state) &&
971	    bitnset(M_HASPWENT, m->m_flags))
972	{
973		auto bool fuzzy;
974		SM_MBDB_T user;
975		int status;
976
977		/* warning -- finduser may trash buf */
978		status = finduser(buf, &fuzzy, &user);
979		switch (status)
980		{
981		  case EX_TEMPFAIL:
982			new->q_state = QS_QUEUEUP;
983			new->q_status = "4.5.2";
984			giveresponse(EX_TEMPFAIL, new->q_status, m, NULL,
985				     new->q_alias, (time_t) 0, e, new);
986			break;
987		  default:
988			new->q_state = QS_BADADDR;
989			new->q_status = "5.1.1";
990			new->q_rstatus = "550 5.1.1 User unknown";
991			giveresponse(EX_NOUSER, new->q_status, m, NULL,
992				     new->q_alias, (time_t) 0, e, new);
993			break;
994		  case EX_OK:
995			if (fuzzy)
996			{
997				/* name was a fuzzy match */
998				new->q_user = sm_rpool_strdup_x(e->e_rpool,
999								user.mbdb_name);
1000				if (findusercount++ > 3)
1001				{
1002					new->q_state = QS_BADADDR;
1003					new->q_status = "5.4.6";
1004					usrerrenh(new->q_status,
1005						  "554 aliasing/forwarding loop for %s broken",
1006						  user.mbdb_name);
1007					goto done;
1008				}
1009
1010				/* see if it aliases */
1011				(void) sm_strlcpy(buf, user.mbdb_name, buflen);
1012				goto trylocaluser;
1013			}
1014			if (*user.mbdb_homedir == '\0')
1015				new->q_home = NULL;
1016			else if (strcmp(user.mbdb_homedir, "/") == 0)
1017				new->q_home = "";
1018			else
1019				new->q_home = sm_rpool_strdup_x(e->e_rpool,
1020							user.mbdb_homedir);
1021			if (user.mbdb_uid != SM_NO_UID)
1022			{
1023				new->q_uid = user.mbdb_uid;
1024				new->q_gid = user.mbdb_gid;
1025				new->q_flags |= QGOODUID;
1026			}
1027			new->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1028							 user.mbdb_name);
1029			if (user.mbdb_fullname[0] != '\0')
1030				new->q_fullname = sm_rpool_strdup_x(e->e_rpool,
1031							user.mbdb_fullname);
1032			if (!usershellok(user.mbdb_name, user.mbdb_shell))
1033			{
1034				new->q_flags |= QBOGUSSHELL;
1035			}
1036			if (bitset(EF_VRFYONLY, e->e_flags))
1037			{
1038				/* don't do any more now */
1039				new->q_state = QS_VERIFIED;
1040			}
1041			else if (!quoted)
1042				forward(new, sendq, aliaslevel, e);
1043		}
1044	}
1045	if (!QS_IS_DEAD(new->q_state))
1046		e->e_nrcpts++;
1047
1048  testselfdestruct:
1049	new->q_flags |= QTHISPASS;
1050	if (tTd(26, 8))
1051	{
1052		sm_dprintf("testselfdestruct: ");
1053		printaddr(sm_debug_file(), new, false);
1054		if (tTd(26, 10))
1055		{
1056			sm_dprintf("SENDQ:\n");
1057			printaddr(sm_debug_file(), *sendq, true);
1058			sm_dprintf("----\n");
1059		}
1060	}
1061	if (new->q_alias == NULL && new != &e->e_from &&
1062	    QS_IS_DEAD(new->q_state))
1063	{
1064		for (q = *sendq; q != NULL; q = q->q_next)
1065		{
1066			if (!QS_IS_DEAD(q->q_state))
1067				break;
1068		}
1069		if (q == NULL)
1070		{
1071			new->q_state = QS_BADADDR;
1072			new->q_status = "5.4.6";
1073			usrerrenh(new->q_status,
1074				  "554 aliasing/forwarding loop broken");
1075		}
1076	}
1077
1078  done:
1079	new->q_flags |= QTHISPASS;
1080	if (buf != buf0)
1081		sm_free(buf); /* XXX leak if above code raises exception */
1082
1083	/*
1084	**  If we are at the top level, check to see if this has
1085	**  expanded to exactly one address.  If so, it can inherit
1086	**  the primaryness of the address.
1087	**
1088	**  While we're at it, clear the QTHISPASS bits.
1089	*/
1090
1091	if (aliaslevel == 0)
1092	{
1093		int nrcpts = 0;
1094		ADDRESS *only = NULL;
1095
1096		for (q = *sendq; q != NULL; q = q->q_next)
1097		{
1098			if (bitset(QTHISPASS, q->q_flags) &&
1099			    QS_IS_SENDABLE(q->q_state))
1100			{
1101				nrcpts++;
1102				only = q;
1103			}
1104			q->q_flags &= ~QTHISPASS;
1105		}
1106		if (nrcpts == 1)
1107		{
1108			/* check to see if this actually got a new owner */
1109			q = only;
1110			while ((q = q->q_alias) != NULL)
1111			{
1112				if (q->q_owner != NULL)
1113					break;
1114			}
1115			if (q == NULL)
1116				only->q_flags |= QPRIMARY;
1117		}
1118		else if (!initialdontsend && nrcpts > 0)
1119		{
1120			/* arrange for return receipt */
1121			e->e_flags |= EF_SENDRECEIPT;
1122			new->q_flags |= QEXPANDED;
1123			if (e->e_xfp != NULL &&
1124			    bitset(QPINGONSUCCESS, new->q_flags))
1125				(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1126						     "%s... expanded to multiple addresses\n",
1127						     new->q_paddr);
1128		}
1129	}
1130	new->q_flags |= QRCPTOK;
1131	(void) sm_snprintf(buf0, sizeof(buf0), "%d", e->e_nrcpts);
1132	macdefine(&e->e_macro, A_TEMP, macid("{nrcpts}"), buf0);
1133	return new;
1134}
1135
1136/*
1137**  FINDUSER -- find the password entry for a user.
1138**
1139**	This looks a lot like getpwnam, except that it may want to
1140**	do some fancier pattern matching in /etc/passwd.
1141**
1142**	This routine contains most of the time of many sendmail runs.
1143**	It deserves to be optimized.
1144**
1145**	Parameters:
1146**		name -- the name to match against.
1147**		fuzzyp -- an outarg that is set to true if this entry
1148**			was found using the fuzzy matching algorithm;
1149**			set to false otherwise.
1150**		user -- structure to fill in if user is found
1151**
1152**	Returns:
1153**		On success, fill in *user, set *fuzzyp and return EX_OK.
1154**		If the user was not found, return EX_NOUSER.
1155**		On error, return EX_TEMPFAIL or EX_OSERR.
1156**
1157**	Side Effects:
1158**		may modify name.
1159*/
1160
1161int
1162finduser(name, fuzzyp, user)
1163	char *name;
1164	bool *fuzzyp;
1165	SM_MBDB_T *user;
1166{
1167#if MATCHGECOS
1168	register struct passwd *pw;
1169#endif /* MATCHGECOS */
1170	register char *p;
1171	bool tryagain;
1172	int status;
1173
1174	if (tTd(29, 4))
1175		sm_dprintf("finduser(%s): ", name);
1176
1177	*fuzzyp = false;
1178
1179#if HESIOD
1180	/* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
1181	for (p = name; *p != '\0'; p++)
1182		if (!isascii(*p) || !isdigit(*p))
1183			break;
1184	if (*p == '\0')
1185	{
1186		if (tTd(29, 4))
1187			sm_dprintf("failed (numeric input)\n");
1188		return EX_NOUSER;
1189	}
1190#endif /* HESIOD */
1191
1192	/* look up this login name using fast path */
1193	status = sm_mbdb_lookup(name, user);
1194	if (status != EX_NOUSER)
1195	{
1196		if (tTd(29, 4))
1197			sm_dprintf("%s (non-fuzzy)\n", sm_strexit(status));
1198		return status;
1199	}
1200
1201	/* try mapping it to lower case */
1202	tryagain = false;
1203	for (p = name; *p != '\0'; p++)
1204	{
1205		if (isascii(*p) && isupper(*p))
1206		{
1207			*p = tolower(*p);
1208			tryagain = true;
1209		}
1210	}
1211	if (tryagain && (status = sm_mbdb_lookup(name, user)) != EX_NOUSER)
1212	{
1213		if (tTd(29, 4))
1214			sm_dprintf("%s (lower case)\n", sm_strexit(status));
1215		*fuzzyp = true;
1216		return status;
1217	}
1218
1219#if MATCHGECOS
1220	/* see if fuzzy matching allowed */
1221	if (!MatchGecos)
1222	{
1223		if (tTd(29, 4))
1224			sm_dprintf("not found (fuzzy disabled)\n");
1225		return EX_NOUSER;
1226	}
1227
1228	/* search for a matching full name instead */
1229	for (p = name; *p != '\0'; p++)
1230	{
1231		if (*p == (SpaceSub & 0177) || *p == '_')
1232			*p = ' ';
1233	}
1234	(void) setpwent();
1235	while ((pw = getpwent()) != NULL)
1236	{
1237		char buf[MAXNAME + 1];
1238
1239# if 0
1240		if (sm_strcasecmp(pw->pw_name, name) == 0)
1241		{
1242			if (tTd(29, 4))
1243				sm_dprintf("found (case wrapped)\n");
1244			break;
1245		}
1246# endif /* 0 */
1247
1248		sm_pwfullname(pw->pw_gecos, pw->pw_name, buf, sizeof(buf));
1249		if (strchr(buf, ' ') != NULL && sm_strcasecmp(buf, name) == 0)
1250		{
1251			if (tTd(29, 4))
1252				sm_dprintf("fuzzy matches %s\n", pw->pw_name);
1253			message("sending to login name %s", pw->pw_name);
1254			break;
1255		}
1256	}
1257	if (pw != NULL)
1258		*fuzzyp = true;
1259	else if (tTd(29, 4))
1260		sm_dprintf("no fuzzy match found\n");
1261# if DEC_OSF_BROKEN_GETPWENT	/* DEC OSF/1 3.2 or earlier */
1262	endpwent();
1263# endif /* DEC_OSF_BROKEN_GETPWENT */
1264	if (pw == NULL)
1265		return EX_NOUSER;
1266	sm_mbdb_frompw(user, pw);
1267	return EX_OK;
1268#else /* MATCHGECOS */
1269	if (tTd(29, 4))
1270		sm_dprintf("not found (fuzzy disabled)\n");
1271	return EX_NOUSER;
1272#endif /* MATCHGECOS */
1273}
1274
1275/*
1276**  WRITABLE -- predicate returning if the file is writable.
1277**
1278**	This routine must duplicate the algorithm in sys/fio.c.
1279**	Unfortunately, we cannot use the access call since we
1280**	won't necessarily be the real uid when we try to
1281**	actually open the file.
1282**
1283**	Notice that ANY file with ANY execute bit is automatically
1284**	not writable.  This is also enforced by mailfile.
1285**
1286**	Parameters:
1287**		filename -- the file name to check.
1288**		ctladdr -- the controlling address for this file.
1289**		flags -- SFF_* flags to control the function.
1290**
1291**	Returns:
1292**		true -- if we will be able to write this file.
1293**		false -- if we cannot write this file.
1294**
1295**	Side Effects:
1296**		none.
1297*/
1298
1299bool
1300writable(filename, ctladdr, flags)
1301	char *filename;
1302	ADDRESS *ctladdr;
1303	long flags;
1304{
1305	uid_t euid = 0;
1306	gid_t egid = 0;
1307	char *user = NULL;
1308
1309	if (tTd(44, 5))
1310		sm_dprintf("writable(%s, 0x%lx)\n", filename, flags);
1311
1312	/*
1313	**  File does exist -- check that it is writable.
1314	*/
1315
1316	if (geteuid() != 0)
1317	{
1318		euid = geteuid();
1319		egid = getegid();
1320		user = NULL;
1321	}
1322	else if (ctladdr != NULL)
1323	{
1324		euid = ctladdr->q_uid;
1325		egid = ctladdr->q_gid;
1326		user = ctladdr->q_user;
1327	}
1328	else if (bitset(SFF_RUNASREALUID, flags))
1329	{
1330		euid = RealUid;
1331		egid = RealGid;
1332		user = RealUserName;
1333	}
1334	else if (FileMailer != NULL && !bitset(SFF_ROOTOK, flags))
1335	{
1336		if (FileMailer->m_uid == NO_UID)
1337		{
1338			euid = DefUid;
1339			user = DefUser;
1340		}
1341		else
1342		{
1343			euid = FileMailer->m_uid;
1344			user = NULL;
1345		}
1346		if (FileMailer->m_gid == NO_GID)
1347			egid = DefGid;
1348		else
1349			egid = FileMailer->m_gid;
1350	}
1351	else
1352	{
1353		euid = egid = 0;
1354		user = NULL;
1355	}
1356	if (!bitset(SFF_ROOTOK, flags))
1357	{
1358		if (euid == 0)
1359		{
1360			euid = DefUid;
1361			user = DefUser;
1362		}
1363		if (egid == 0)
1364			egid = DefGid;
1365	}
1366	if (geteuid() == 0 &&
1367	    (ctladdr == NULL || !bitset(QGOODUID, ctladdr->q_flags)))
1368		flags |= SFF_SETUIDOK;
1369
1370	if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
1371		flags |= SFF_NOSLINK;
1372	if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
1373		flags |= SFF_NOHLINK;
1374
1375	errno = safefile(filename, euid, egid, user, flags, S_IWRITE, NULL);
1376	return errno == 0;
1377}
1378
1379/*
1380**  INCLUDE -- handle :include: specification.
1381**
1382**	Parameters:
1383**		fname -- filename to include.
1384**		forwarding -- if true, we are reading a .forward file.
1385**			if false, it's a :include: file.
1386**		ctladdr -- address template to use to fill in these
1387**			addresses -- effective user/group id are
1388**			the important things.
1389**		sendq -- a pointer to the head of the send queue
1390**			to put these addresses in.
1391**		aliaslevel -- the alias nesting depth.
1392**		e -- the current envelope.
1393**
1394**	Returns:
1395**		open error status
1396**
1397**	Side Effects:
1398**		reads the :include: file and sends to everyone
1399**		listed in that file.
1400**
1401**	Security Note:
1402**		If you have restricted chown (that is, you can't
1403**		give a file away), it is reasonable to allow programs
1404**		and files called from this :include: file to be to be
1405**		run as the owner of the :include: file.  This is bogus
1406**		if there is any chance of someone giving away a file.
1407**		We assume that pre-POSIX systems can give away files.
1408**
1409**		There is an additional restriction that if you
1410**		forward to a :include: file, it will not take on
1411**		the ownership of the :include: file.  This may not
1412**		be necessary, but shouldn't hurt.
1413*/
1414
1415static jmp_buf	CtxIncludeTimeout;
1416
1417int
1418include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
1419	char *fname;
1420	bool forwarding;
1421	ADDRESS *ctladdr;
1422	ADDRESS **sendq;
1423	int aliaslevel;
1424	ENVELOPE *e;
1425{
1426	SM_FILE_T *volatile fp = NULL;
1427	char *oldto = e->e_to;
1428	char *oldfilename = FileName;
1429	int oldlinenumber = LineNumber;
1430	register SM_EVENT *ev = NULL;
1431	int nincludes;
1432	int mode;
1433	volatile bool maxreached = false;
1434	register ADDRESS *ca;
1435	volatile uid_t saveduid;
1436	volatile gid_t savedgid;
1437	volatile uid_t uid;
1438	volatile gid_t gid;
1439	char *volatile user;
1440	int rval = 0;
1441	volatile long sfflags = SFF_REGONLY;
1442	register char *p;
1443	bool safechown = false;
1444	volatile bool safedir = false;
1445	struct stat st;
1446	char buf[MAXLINE];
1447
1448	if (tTd(27, 2))
1449		sm_dprintf("include(%s)\n", fname);
1450	if (tTd(27, 4))
1451		sm_dprintf("   ruid=%d euid=%d\n",
1452			(int) getuid(), (int) geteuid());
1453	if (tTd(27, 14))
1454	{
1455		sm_dprintf("ctladdr ");
1456		printaddr(sm_debug_file(), ctladdr, false);
1457	}
1458
1459	if (tTd(27, 9))
1460		sm_dprintf("include: old uid = %d/%d\n",
1461			   (int) getuid(), (int) geteuid());
1462
1463	if (forwarding)
1464	{
1465		sfflags |= SFF_MUSTOWN|SFF_ROOTOK;
1466		if (!bitnset(DBS_GROUPWRITABLEFORWARDFILE, DontBlameSendmail))
1467			sfflags |= SFF_NOGWFILES;
1468		if (!bitnset(DBS_WORLDWRITABLEFORWARDFILE, DontBlameSendmail))
1469			sfflags |= SFF_NOWWFILES;
1470	}
1471	else
1472	{
1473		if (!bitnset(DBS_GROUPWRITABLEINCLUDEFILE, DontBlameSendmail))
1474			sfflags |= SFF_NOGWFILES;
1475		if (!bitnset(DBS_WORLDWRITABLEINCLUDEFILE, DontBlameSendmail))
1476			sfflags |= SFF_NOWWFILES;
1477	}
1478
1479	/*
1480	**  If RunAsUser set, won't be able to run programs as user
1481	**  so mark them as unsafe unless the administrator knows better.
1482	*/
1483
1484	if ((geteuid() != 0 || RunAsUid != 0) &&
1485	    !bitnset(DBS_NONROOTSAFEADDR, DontBlameSendmail))
1486	{
1487		if (tTd(27, 4))
1488			sm_dprintf("include: not safe (euid=%d, RunAsUid=%d)\n",
1489				   (int) geteuid(), (int) RunAsUid);
1490		ctladdr->q_flags |= QUNSAFEADDR;
1491	}
1492
1493	ca = getctladdr(ctladdr);
1494	if (ca == NULL ||
1495	    (ca->q_uid == DefUid && ca->q_gid == 0))
1496	{
1497		uid = DefUid;
1498		gid = DefGid;
1499		user = DefUser;
1500	}
1501	else
1502	{
1503		uid = ca->q_uid;
1504		gid = ca->q_gid;
1505		user = ca->q_user;
1506	}
1507#if MAILER_SETUID_METHOD != USE_SETUID
1508	saveduid = geteuid();
1509	savedgid = getegid();
1510	if (saveduid == 0)
1511	{
1512		if (!DontInitGroups)
1513		{
1514			if (initgroups(user, gid) == -1)
1515			{
1516				rval = EAGAIN;
1517				syserr("include: initgroups(%s, %d) failed",
1518					user, gid);
1519				goto resetuid;
1520			}
1521		}
1522		else
1523		{
1524			GIDSET_T gidset[1];
1525
1526			gidset[0] = gid;
1527			if (setgroups(1, gidset) == -1)
1528			{
1529				rval = EAGAIN;
1530				syserr("include: setgroups() failed");
1531				goto resetuid;
1532			}
1533		}
1534
1535		if (gid != 0 && setgid(gid) < -1)
1536		{
1537			rval = EAGAIN;
1538			syserr("setgid(%d) failure", gid);
1539			goto resetuid;
1540		}
1541		if (uid != 0)
1542		{
1543# if MAILER_SETUID_METHOD == USE_SETEUID
1544			if (seteuid(uid) < 0)
1545			{
1546				rval = EAGAIN;
1547				syserr("seteuid(%d) failure (real=%d, eff=%d)",
1548					uid, (int) getuid(), (int) geteuid());
1549				goto resetuid;
1550			}
1551# endif /* MAILER_SETUID_METHOD == USE_SETEUID */
1552# if MAILER_SETUID_METHOD == USE_SETREUID
1553			if (setreuid(0, uid) < 0)
1554			{
1555				rval = EAGAIN;
1556				syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
1557					uid, (int) getuid(), (int) geteuid());
1558				goto resetuid;
1559			}
1560# endif /* MAILER_SETUID_METHOD == USE_SETREUID */
1561		}
1562	}
1563#endif /* MAILER_SETUID_METHOD != USE_SETUID */
1564
1565	if (tTd(27, 9))
1566		sm_dprintf("include: new uid = %d/%d\n",
1567			   (int) getuid(), (int) geteuid());
1568
1569	/*
1570	**  If home directory is remote mounted but server is down,
1571	**  this can hang or give errors; use a timeout to avoid this
1572	*/
1573
1574	if (setjmp(CtxIncludeTimeout) != 0)
1575	{
1576		ctladdr->q_state = QS_QUEUEUP;
1577		errno = 0;
1578
1579		/* return pseudo-error code */
1580		rval = E_SM_OPENTIMEOUT;
1581		goto resetuid;
1582	}
1583	if (TimeOuts.to_fileopen > 0)
1584		ev = sm_setevent(TimeOuts.to_fileopen, includetimeout, 0);
1585	else
1586		ev = NULL;
1587
1588
1589	/* check for writable parent directory */
1590	p = strrchr(fname, '/');
1591	if (p != NULL)
1592	{
1593		int ret;
1594
1595		*p = '\0';
1596		ret = safedirpath(fname, uid, gid, user,
1597				  sfflags|SFF_SAFEDIRPATH, 0, 0);
1598		if (ret == 0)
1599		{
1600			/* in safe directory: relax chown & link rules */
1601			safedir = true;
1602			sfflags |= SFF_NOPATHCHECK;
1603		}
1604		else
1605		{
1606			if (bitnset((forwarding ?
1607				     DBS_FORWARDFILEINUNSAFEDIRPATH :
1608				     DBS_INCLUDEFILEINUNSAFEDIRPATH),
1609				    DontBlameSendmail))
1610				sfflags |= SFF_NOPATHCHECK;
1611			else if (bitnset((forwarding ?
1612					  DBS_FORWARDFILEINGROUPWRITABLEDIRPATH :
1613					  DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH),
1614					 DontBlameSendmail) &&
1615				 ret == E_SM_GWDIR)
1616			{
1617				setbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1618					DontBlameSendmail);
1619				ret = safedirpath(fname, uid, gid, user,
1620						  sfflags|SFF_SAFEDIRPATH,
1621						  0, 0);
1622				clrbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1623					DontBlameSendmail);
1624				if (ret == 0)
1625					sfflags |= SFF_NOPATHCHECK;
1626				else
1627					sfflags |= SFF_SAFEDIRPATH;
1628			}
1629			else
1630				sfflags |= SFF_SAFEDIRPATH;
1631			if (ret > E_PSEUDOBASE &&
1632			    !bitnset((forwarding ?
1633				      DBS_FORWARDFILEINUNSAFEDIRPATHSAFE :
1634				      DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE),
1635				     DontBlameSendmail))
1636			{
1637				if (LogLevel > 11)
1638					sm_syslog(LOG_INFO, e->e_id,
1639						  "%s: unsafe directory path, marked unsafe",
1640						  shortenstring(fname, MAXSHORTSTR));
1641				ctladdr->q_flags |= QUNSAFEADDR;
1642			}
1643		}
1644		*p = '/';
1645	}
1646
1647	/* allow links only in unwritable directories */
1648	if (!safedir &&
1649	    !bitnset((forwarding ?
1650		      DBS_LINKEDFORWARDFILEINWRITABLEDIR :
1651		      DBS_LINKEDINCLUDEFILEINWRITABLEDIR),
1652		     DontBlameSendmail))
1653		sfflags |= SFF_NOLINK;
1654
1655	rval = safefile(fname, uid, gid, user, sfflags, S_IREAD, &st);
1656	if (rval != 0)
1657	{
1658		/* don't use this :include: file */
1659		if (tTd(27, 4))
1660			sm_dprintf("include: not safe (uid=%d): %s\n",
1661				   (int) uid, sm_errstring(rval));
1662	}
1663	else if ((fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fname,
1664				  SM_IO_RDONLY, NULL)) == NULL)
1665	{
1666		rval = errno;
1667		if (tTd(27, 4))
1668			sm_dprintf("include: open: %s\n", sm_errstring(rval));
1669	}
1670	else if (filechanged(fname, sm_io_getinfo(fp,SM_IO_WHAT_FD, NULL), &st))
1671	{
1672		rval = E_SM_FILECHANGE;
1673		if (tTd(27, 4))
1674			sm_dprintf("include: file changed after open\n");
1675	}
1676	if (ev != NULL)
1677		sm_clrevent(ev);
1678
1679resetuid:
1680
1681#if HASSETREUID || USESETEUID
1682	if (saveduid == 0)
1683	{
1684		if (uid != 0)
1685		{
1686# if USESETEUID
1687			if (seteuid(0) < 0)
1688				syserr("!seteuid(0) failure (real=%d, eff=%d)",
1689				       (int) getuid(), (int) geteuid());
1690# else /* USESETEUID */
1691			if (setreuid(-1, 0) < 0)
1692				syserr("!setreuid(-1, 0) failure (real=%d, eff=%d)",
1693				       (int) getuid(), (int) geteuid());
1694			if (setreuid(RealUid, 0) < 0)
1695				syserr("!setreuid(%d, 0) failure (real=%d, eff=%d)",
1696				       (int) RealUid, (int) getuid(),
1697				       (int) geteuid());
1698# endif /* USESETEUID */
1699		}
1700		if (setgid(savedgid) < 0)
1701			syserr("!setgid(%d) failure (real=%d eff=%d)",
1702			       (int) savedgid, (int) getgid(),
1703			       (int) getegid());
1704	}
1705#endif /* HASSETREUID || USESETEUID */
1706
1707	if (tTd(27, 9))
1708		sm_dprintf("include: reset uid = %d/%d\n",
1709			   (int) getuid(), (int) geteuid());
1710
1711	if (rval == E_SM_OPENTIMEOUT)
1712		usrerr("451 4.4.1 open timeout on %s", fname);
1713
1714	if (fp == NULL)
1715		return rval;
1716
1717	if (fstat(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), &st) < 0)
1718	{
1719		rval = errno;
1720		syserr("Cannot fstat %s!", fname);
1721		(void) sm_io_close(fp, SM_TIME_DEFAULT);
1722		return rval;
1723	}
1724
1725	/* if path was writable, check to avoid file giveaway tricks */
1726	safechown = chownsafe(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), safedir);
1727	if (tTd(27, 6))
1728		sm_dprintf("include: parent of %s is %s, chown is %ssafe\n",
1729			   fname, safedir ? "safe" : "dangerous",
1730			   safechown ? "" : "un");
1731
1732	/* if no controlling user or coming from an alias delivery */
1733	if (safechown &&
1734	    (ca == NULL ||
1735	     (ca->q_uid == DefUid && ca->q_gid == 0)))
1736	{
1737		ctladdr->q_uid = st.st_uid;
1738		ctladdr->q_gid = st.st_gid;
1739		ctladdr->q_flags |= QGOODUID;
1740	}
1741	if (ca != NULL && ca->q_uid == st.st_uid)
1742	{
1743		/* optimization -- avoid getpwuid if we already have info */
1744		ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL;
1745		ctladdr->q_ruser = ca->q_ruser;
1746	}
1747	else if (!forwarding)
1748	{
1749		register struct passwd *pw;
1750
1751		pw = sm_getpwuid(st.st_uid);
1752		if (pw == NULL)
1753		{
1754			ctladdr->q_uid = st.st_uid;
1755			ctladdr->q_flags |= QBOGUSSHELL;
1756		}
1757		else
1758		{
1759			char *sh;
1760
1761			ctladdr->q_ruser = sm_rpool_strdup_x(e->e_rpool,
1762							     pw->pw_name);
1763			if (safechown)
1764				sh = pw->pw_shell;
1765			else
1766				sh = "/SENDMAIL/ANY/SHELL/";
1767			if (!usershellok(pw->pw_name, sh))
1768			{
1769				if (LogLevel > 11)
1770					sm_syslog(LOG_INFO, e->e_id,
1771						  "%s: user %s has bad shell %s, marked %s",
1772						  shortenstring(fname,
1773								MAXSHORTSTR),
1774						  pw->pw_name, sh,
1775						  safechown ? "bogus" : "unsafe");
1776				if (safechown)
1777					ctladdr->q_flags |= QBOGUSSHELL;
1778				else
1779					ctladdr->q_flags |= QUNSAFEADDR;
1780			}
1781		}
1782	}
1783
1784	if (bitset(EF_VRFYONLY, e->e_flags))
1785	{
1786		/* don't do any more now */
1787		ctladdr->q_state = QS_VERIFIED;
1788		e->e_nrcpts++;
1789		(void) sm_io_close(fp, SM_TIME_DEFAULT);
1790		return rval;
1791	}
1792
1793	/*
1794	**  Check to see if some bad guy can write this file
1795	**
1796	**	Group write checking could be more clever, e.g.,
1797	**	guessing as to which groups are actually safe ("sys"
1798	**	may be; "user" probably is not).
1799	*/
1800
1801	mode = S_IWOTH;
1802	if (!bitnset((forwarding ?
1803		      DBS_GROUPWRITABLEFORWARDFILESAFE :
1804		      DBS_GROUPWRITABLEINCLUDEFILESAFE),
1805		     DontBlameSendmail))
1806		mode |= S_IWGRP;
1807
1808	if (bitset(mode, st.st_mode))
1809	{
1810		if (tTd(27, 6))
1811			sm_dprintf("include: %s is %s writable, marked unsafe\n",
1812				   shortenstring(fname, MAXSHORTSTR),
1813				   bitset(S_IWOTH, st.st_mode) ? "world"
1814							       : "group");
1815		if (LogLevel > 11)
1816			sm_syslog(LOG_INFO, e->e_id,
1817				  "%s: %s writable %s file, marked unsafe",
1818				  shortenstring(fname, MAXSHORTSTR),
1819				  bitset(S_IWOTH, st.st_mode) ? "world" : "group",
1820				  forwarding ? "forward" : ":include:");
1821		ctladdr->q_flags |= QUNSAFEADDR;
1822	}
1823
1824	/* read the file -- each line is a comma-separated list. */
1825	FileName = fname;
1826	LineNumber = 0;
1827	ctladdr->q_flags &= ~QSELFREF;
1828	nincludes = 0;
1829	while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL &&
1830	       !maxreached)
1831	{
1832		fixcrlf(buf, true);
1833		LineNumber++;
1834		if (buf[0] == '#' || buf[0] == '\0')
1835			continue;
1836
1837		/* <sp>#@# introduces a comment anywhere */
1838		/* for Japanese character sets */
1839		for (p = buf; (p = strchr(++p, '#')) != NULL; )
1840		{
1841			if (p[1] == '@' && p[2] == '#' &&
1842			    isascii(p[-1]) && isspace(p[-1]) &&
1843			    (p[3] == '\0' || (isascii(p[3]) && isspace(p[3]))))
1844			{
1845				--p;
1846				while (p > buf && isascii(p[-1]) &&
1847				       isspace(p[-1]))
1848					--p;
1849				p[0] = '\0';
1850				break;
1851			}
1852		}
1853		if (buf[0] == '\0')
1854			continue;
1855
1856		e->e_to = NULL;
1857		message("%s to %s",
1858			forwarding ? "forwarding" : "sending", buf);
1859		if (forwarding && LogLevel > 10)
1860			sm_syslog(LOG_INFO, e->e_id,
1861				  "forward %.200s => %s",
1862				  oldto, shortenstring(buf, MAXSHORTSTR));
1863
1864		nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1865
1866		if (forwarding &&
1867		    MaxForwardEntries > 0 &&
1868		    nincludes >= MaxForwardEntries)
1869		{
1870			/* just stop reading and processing further entries */
1871#if 0
1872			/* additional: (?) */
1873			ctladdr->q_state = QS_DONTSEND;
1874#endif /* 0 */
1875
1876			syserr("Attempt to forward to more than %d addresses (in %s)!",
1877				MaxForwardEntries, fname);
1878			maxreached = true;
1879		}
1880	}
1881
1882	if (sm_io_error(fp) && tTd(27, 3))
1883		sm_dprintf("include: read error: %s\n", sm_errstring(errno));
1884	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1885	{
1886		if (aliaslevel <= MaxAliasRecursion ||
1887		    ctladdr->q_state != QS_BADADDR)
1888		{
1889			ctladdr->q_state = QS_DONTSEND;
1890			if (tTd(27, 5))
1891			{
1892				sm_dprintf("include: QS_DONTSEND ");
1893				printaddr(sm_debug_file(), ctladdr, false);
1894			}
1895		}
1896	}
1897
1898	(void) sm_io_close(fp, SM_TIME_DEFAULT);
1899	FileName = oldfilename;
1900	LineNumber = oldlinenumber;
1901	e->e_to = oldto;
1902	return rval;
1903}
1904
1905static void
1906includetimeout(ignore)
1907	int ignore;
1908{
1909	/*
1910	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
1911	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1912	**	DOING.
1913	*/
1914
1915	errno = ETIMEDOUT;
1916	longjmp(CtxIncludeTimeout, 1);
1917}
1918
1919/*
1920**  SENDTOARGV -- send to an argument vector.
1921**
1922**	Parameters:
1923**		argv -- argument vector to send to.
1924**		e -- the current envelope.
1925**
1926**	Returns:
1927**		none.
1928**
1929**	Side Effects:
1930**		puts all addresses on the argument vector onto the
1931**			send queue.
1932*/
1933
1934void
1935sendtoargv(argv, e)
1936	register char **argv;
1937	register ENVELOPE *e;
1938{
1939	register char *p;
1940
1941	while ((p = *argv++) != NULL)
1942		(void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1943}
1944
1945/*
1946**  GETCTLADDR -- get controlling address from an address header.
1947**
1948**	If none, get one corresponding to the effective userid.
1949**
1950**	Parameters:
1951**		a -- the address to find the controller of.
1952**
1953**	Returns:
1954**		the controlling address.
1955*/
1956
1957ADDRESS *
1958getctladdr(a)
1959	register ADDRESS *a;
1960{
1961	while (a != NULL && !bitset(QGOODUID, a->q_flags))
1962		a = a->q_alias;
1963	return a;
1964}
1965
1966/*
1967**  SELF_REFERENCE -- check to see if an address references itself
1968**
1969**	The check is done through a chain of aliases.  If it is part of
1970**	a loop, break the loop at the "best" address, that is, the one
1971**	that exists as a real user.
1972**
1973**	This is to handle the case of:
1974**		awc:		Andrew.Chang
1975**		Andrew.Chang:	awc@mail.server
1976**	which is a problem only on mail.server.
1977**
1978**	Parameters:
1979**		a -- the address to check.
1980**
1981**	Returns:
1982**		The address that should be retained.
1983*/
1984
1985static ADDRESS *
1986self_reference(a)
1987	ADDRESS *a;
1988{
1989	ADDRESS *b;		/* top entry in self ref loop */
1990	ADDRESS *c;		/* entry that point to a real mail box */
1991
1992	if (tTd(27, 1))
1993		sm_dprintf("self_reference(%s)\n", a->q_paddr);
1994
1995	for (b = a->q_alias; b != NULL; b = b->q_alias)
1996	{
1997		if (sameaddr(a, b))
1998			break;
1999	}
2000
2001	if (b == NULL)
2002	{
2003		if (tTd(27, 1))
2004			sm_dprintf("\t... no self ref\n");
2005		return NULL;
2006	}
2007
2008	/*
2009	**  Pick the first address that resolved to a real mail box
2010	**  i.e has a mbdb entry.  The returned value will be marked
2011	**  QSELFREF in recipient(), which in turn will disable alias()
2012	**  from marking it as QS_IS_DEAD(), which mean it will be used
2013	**  as a deliverable address.
2014	**
2015	**  The 2 key thing to note here are:
2016	**	1) we are in a recursive call sequence:
2017	**		alias->sendtolist->recipient->alias
2018	**	2) normally, when we return back to alias(), the address
2019	**	   will be marked QS_EXPANDED, since alias() assumes the
2020	**	   expanded form will be used instead of the current address.
2021	**	   This behaviour is turned off if the address is marked
2022	**	   QSELFREF.  We set QSELFREF when we return to recipient().
2023	*/
2024
2025	c = a;
2026	while (c != NULL)
2027	{
2028		if (tTd(27, 10))
2029			sm_dprintf("  %s", c->q_user);
2030		if (bitnset(M_HASPWENT, c->q_mailer->m_flags))
2031		{
2032			SM_MBDB_T user;
2033
2034			if (tTd(27, 2))
2035				sm_dprintf("\t... getpwnam(%s)... ", c->q_user);
2036			if (sm_mbdb_lookup(c->q_user, &user) == EX_OK)
2037			{
2038				if (tTd(27, 2))
2039					sm_dprintf("found\n");
2040
2041				/* ought to cache results here */
2042				if (sameaddr(b, c))
2043					return b;
2044				else
2045					return c;
2046			}
2047			if (tTd(27, 2))
2048				sm_dprintf("failed\n");
2049		}
2050		else
2051		{
2052			/* if local delivery, compare usernames */
2053			if (bitnset(M_LOCALMAILER, c->q_mailer->m_flags) &&
2054			    b->q_mailer == c->q_mailer)
2055			{
2056				if (tTd(27, 2))
2057					sm_dprintf("\t... local match (%s)\n",
2058						c->q_user);
2059				if (sameaddr(b, c))
2060					return b;
2061				else
2062					return c;
2063			}
2064		}
2065		if (tTd(27, 10))
2066			sm_dprintf("\n");
2067		c = c->q_alias;
2068	}
2069
2070	if (tTd(27, 1))
2071		sm_dprintf("\t... cannot break loop for \"%s\"\n", a->q_paddr);
2072
2073	return NULL;
2074}
2075