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