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