recipient.c revision 64562
137Srgrimes/*
237Srgrimes * Copyright (c) 1998-2000 Sendmail, Inc. and its suppliers.
337Srgrimes *	All rights reserved.
437Srgrimes * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
537Srgrimes * Copyright (c) 1988, 1993
637Srgrimes *	The Regents of the University of California.  All rights reserved.
737Srgrimes *
837Srgrimes * By using this file, you agree to the terms and conditions set
99306Sbde * forth in the LICENSE file which can be found at the top level of
1037Srgrimes * the sendmail distribution.
11646Sdg *
129306Sbde */
13646Sdg
146489Sjoerg#ifndef lint
156489Sjoergstatic char id[] = "@(#)$Id: recipient.c,v 8.231.14.5 2000/06/27 20:15:46 gshapiro Exp $";
166489Sjoerg#endif /* ! lint */
176489Sjoerg
186489Sjoerg#include <sendmail.h>
199306Sbde
209306Sbde
21646Sdgstatic void	includetimeout __P((void));
22646Sdgstatic ADDRESS	*self_reference __P((ADDRESS *));
23646Sdg
24646Sdg/*
25646Sdg**  SENDTOLIST -- Designate a send list.
26646Sdg**
27646Sdg**	The parameter is a comma-separated list of people to send to.
28646Sdg**	This routine arranges to send to all of them.
29646Sdg**
30646Sdg**	Parameters:
31646Sdg**		list -- the send list.
326489Sjoerg**		ctladdr -- the address template for the person to
33646Sdg**			send to -- effective uid/gid are important.
34646Sdg**			This is typically the alias that caused this
35646Sdg**			expansion.
36646Sdg**		sendq -- a pointer to the head of a queue to put
37646Sdg**			these people into.
38646Sdg**		aliaslevel -- the current alias nesting depth -- to
3937Srgrimes**			diagnose loops.
4018364Sjkh**		e -- the envelope in which to add these recipients.
4137Srgrimes**
4237Srgrimes**	Returns:
4337Srgrimes**		The number of addresses actually on the list.
4437Srgrimes**
4537Srgrimes**	Side Effects:
4637Srgrimes**		none.
4737Srgrimes*/
4837Srgrimes
4937Srgrimes/* q_flags bits inherited from ctladdr */
5037Srgrimes#define QINHERITEDBITS	(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY)
5137Srgrimes
5237Srgrimesint
53862Sachesendtolist(list, ctladdr, sendq, aliaslevel, e)
5437Srgrimes	char *list;
55862Sache	ADDRESS *ctladdr;
5637Srgrimes	ADDRESS **sendq;
57862Sache	int aliaslevel;
5837Srgrimes	register ENVELOPE *e;
59862Sache{
6037Srgrimes	register char *p;
61862Sache	register ADDRESS *al;	/* list of addresses to send to */
6237Srgrimes	char delimiter;		/* the address delimiter */
63862Sache	int naddrs;
6437Srgrimes	int i;
65862Sache	char *oldto = e->e_to;
6637Srgrimes	char *bufp;
67862Sache	char buf[MAXNAME + 1];
6837Srgrimes
69862Sache	if (list == NULL)
7037Srgrimes	{
71862Sache		syserr("sendtolist: null list");
72154Srgrimes		return 0;
73862Sache	}
74154Srgrimes
75862Sache	if (tTd(25, 1))
76154Srgrimes	{
77862Sache		dprintf("sendto: %s\n   ctladdr=", list);
7837Srgrimes		printaddr(ctladdr, FALSE);
7937Srgrimes	}
8029610Sjoerg
8129610Sjoerg	/* heuristic to determine old versus new style addresses */
8229610Sjoerg	if (ctladdr == NULL &&
8329610Sjoerg	    (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
8429610Sjoerg	     strchr(list, '<') != NULL || strchr(list, '(') != NULL))
8529610Sjoerg		e->e_flags &= ~EF_OLDSTYLE;
8629610Sjoerg	delimiter = ' ';
8729610Sjoerg	if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
8829610Sjoerg		delimiter = ',';
8929610Sjoerg
9029610Sjoerg	al = NULL;
9129610Sjoerg	naddrs = 0;
9229610Sjoerg
9329610Sjoerg	/* make sure we have enough space to copy the string */
9429610Sjoerg	i = strlen(list) + 1;
9529610Sjoerg	if (i <= sizeof buf)
9629610Sjoerg	{
9729610Sjoerg		bufp = buf;
9829610Sjoerg		i = sizeof buf;
9929610Sjoerg	}
10037Srgrimes	else
10137Srgrimes		bufp = xalloc(i);
10237Srgrimes	(void) strlcpy(bufp, denlstring(list, FALSE, TRUE), i);
10337Srgrimes
10437Srgrimes#if _FFR_ADDR_TYPE
10537Srgrimes	define(macid("{addr_type}", NULL), "e r", e);
10637Srgrimes#endif /* _FFR_ADDR_TYPE */
10737Srgrimes	for (p = bufp; *p != '\0'; )
10837Srgrimes	{
10937Srgrimes		auto char *delimptr;
11037Srgrimes		register ADDRESS *a;
11137Srgrimes
11237Srgrimes		/* parse the address */
11337Srgrimes		while ((isascii(*p) && isspace(*p)) || *p == ',')
11437Srgrimes			p++;
11537Srgrimes		a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter, &delimptr, e);
11637Srgrimes		p = delimptr;
11737Srgrimes		if (a == NULL)
11837Srgrimes			continue;
11937Srgrimes		a->q_next = al;
12037Srgrimes		a->q_alias = ctladdr;
12137Srgrimes
12237Srgrimes		/* arrange to inherit attributes from parent */
12337Srgrimes		if (ctladdr != NULL)
12437Srgrimes		{
12537Srgrimes			ADDRESS *b;
12637Srgrimes
12737Srgrimes			/* self reference test */
12837Srgrimes			if (sameaddr(ctladdr, a))
12937Srgrimes			{
13037Srgrimes				if (tTd(27, 5))
13137Srgrimes				{
13237Srgrimes					dprintf("sendtolist: QSELFREF ");
13337Srgrimes					printaddr(ctladdr, FALSE);
13437Srgrimes				}
135289Srgrimes				ctladdr->q_flags |= QSELFREF;
13637Srgrimes			}
13737Srgrimes
13837Srgrimes			/* check for address loops */
13937Srgrimes			b = self_reference(a);
14037Srgrimes			if (b != NULL)
14137Srgrimes			{
14237Srgrimes				b->q_flags |= QSELFREF;
14337Srgrimes				if (tTd(27, 5))
14437Srgrimes				{
14537Srgrimes					dprintf("sendtolist: QSELFREF ");
14637Srgrimes					printaddr(b, FALSE);
14737Srgrimes				}
14837Srgrimes				if (a != b)
14937Srgrimes				{
15037Srgrimes					if (tTd(27, 5))
15137Srgrimes					{
15237Srgrimes						dprintf("sendtolist: QS_DONTSEND ");
15337Srgrimes						printaddr(a, FALSE);
15437Srgrimes					}
15537Srgrimes					a->q_state = QS_DONTSEND;
15637Srgrimes					b->q_flags |= a->q_flags & QNOTREMOTE;
15737Srgrimes					continue;
15837Srgrimes				}
15937Srgrimes			}
16037Srgrimes
16137Srgrimes			/* full name */
16237Srgrimes			if (a->q_fullname == NULL)
1631096Sache				a->q_fullname = ctladdr->q_fullname;
16437Srgrimes
16537Srgrimes			/* various flag bits */
16637Srgrimes			a->q_flags &= ~QINHERITEDBITS;
16737Srgrimes			a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
16837Srgrimes
16937Srgrimes			/* original recipient information */
17037Srgrimes			a->q_orcpt = ctladdr->q_orcpt;
17137Srgrimes		}
17237Srgrimes
17337Srgrimes		al = a;
17437Srgrimes	}
17537Srgrimes
17637Srgrimes	/* arrange to send to everyone on the local send list */
17737Srgrimes	while (al != NULL)
17837Srgrimes	{
17937Srgrimes		register ADDRESS *a = al;
18037Srgrimes
18137Srgrimes		al = a->q_next;
18237Srgrimes		a = recipient(a, sendq, aliaslevel, e);
18337Srgrimes		naddrs++;
18437Srgrimes	}
18537Srgrimes
18637Srgrimes	e->e_to = oldto;
18737Srgrimes	if (bufp != buf)
18837Srgrimes		free(bufp);
18937Srgrimes#if _FFR_ADDR_TYPE
19037Srgrimes	define(macid("{addr_type}", NULL), NULL, e);
19137Srgrimes#endif /* _FFR_ADDR_TYPE */
19237Srgrimes	return naddrs;
19337Srgrimes}
19437Srgrimes/*
19537Srgrimes**  REMOVEFROMLIST -- Remove addresses from a send list.
19637Srgrimes**
19737Srgrimes**	The parameter is a comma-separated list of recipients to remove.
198**	Note that it only deletes matching addresses.  If those addresses
199**	have been expended already in the sendq, it won't mark the
200**	expanded recipients as QS_REMOVED.
201**
202**	Parameters:
203**		list -- the list to remove.
204**		sendq -- a pointer to the head of a queue to remove
205**			these addresses from.
206**		e -- the envelope in which to remove these recipients.
207**
208**	Returns:
209**		The number of addresses removed from the list.
210**
211*/
212
213int
214removefromlist(list, sendq, e)
215	char *list;
216	ADDRESS **sendq;
217	ENVELOPE *e;
218{
219	char delimiter;		/* the address delimiter */
220	int naddrs;
221	int i;
222	char *p;
223	char *oldto = e->e_to;
224	char *bufp;
225	char buf[MAXNAME + 1];
226
227	if (list == NULL)
228	{
229		syserr("removefromlist: null list");
230		return 0;
231	}
232
233	if (tTd(25, 1))
234		dprintf("removefromlist: %s\n", list);
235
236	/* heuristic to determine old versus new style addresses */
237	if (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
238	    strchr(list, '<') != NULL || strchr(list, '(') != NULL)
239		e->e_flags &= ~EF_OLDSTYLE;
240	delimiter = ' ';
241	if (!bitset(EF_OLDSTYLE, e->e_flags))
242		delimiter = ',';
243
244	naddrs = 0;
245
246	/* make sure we have enough space to copy the string */
247	i = strlen(list) + 1;
248	if (i <= sizeof buf)
249	{
250		bufp = buf;
251		i = sizeof buf;
252	}
253	else
254		bufp = xalloc(i);
255	(void) strlcpy(bufp, denlstring(list, FALSE, TRUE), i);
256
257#if _FFR_ADDR_TYPE
258	define(macid("{addr_type}", NULL), "e r", e);
259#endif /* _FFR_ADDR_TYPE */
260	for (p = bufp; *p != '\0'; )
261	{
262		ADDRESS a;		/* parsed address to be removed */
263		ADDRESS *q;
264		ADDRESS **pq;
265		char *delimptr;
266
267		/* parse the address */
268		while ((isascii(*p) && isspace(*p)) || *p == ',')
269			p++;
270		if (parseaddr(p, &a, RF_COPYALL,
271			      delimiter, &delimptr, e) == NULL)
272		{
273			p = delimptr;
274			continue;
275		}
276		p = delimptr;
277		for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
278		{
279			if (!QS_IS_DEAD(q->q_state) &&
280			    sameaddr(q, &a))
281			{
282				if (tTd(25, 5))
283				{
284					dprintf("removefromlist: QS_REMOVED ");
285					printaddr(&a, FALSE);
286				}
287				q->q_state = QS_REMOVED;
288				naddrs++;
289				break;
290			}
291		}
292	}
293
294	e->e_to = oldto;
295	if (bufp != buf)
296		free(bufp);
297#if _FFR_ADDR_TYPE
298	define(macid("{addr_type}", NULL), NULL, e);
299#endif /* _FFR_ADDR_TYPE */
300	return naddrs;
301}
302/*
303**  RECIPIENT -- Designate a message recipient
304**
305**	Saves the named person for future mailing.
306**
307**	Parameters:
308**		a -- the (preparsed) address header for the recipient.
309**		sendq -- a pointer to the head of a queue to put the
310**			recipient in.  Duplicate suppression is done
311**			in this queue.
312**		aliaslevel -- the current alias nesting depth.
313**		e -- the current envelope.
314**
315**	Returns:
316**		The actual address in the queue.  This will be "a" if
317**		the address is not a duplicate, else the original address.
318**
319**	Side Effects:
320**		none.
321*/
322
323ADDRESS *
324recipient(a, sendq, aliaslevel, e)
325	register ADDRESS *a;
326	register ADDRESS **sendq;
327	int aliaslevel;
328	register ENVELOPE *e;
329{
330	register ADDRESS *q;
331	ADDRESS **pq;
332	register struct mailer *m;
333	register char *p = NULL;
334	bool quoted = FALSE;		/* set if the addr has a quote bit */
335	int findusercount = 0;
336	bool initialdontsend = QS_IS_DEAD(a->q_state);
337	int i, buflen;
338	char *buf;
339	char buf0[MAXNAME + 1];		/* unquoted image of the user name */
340
341	e->e_to = a->q_paddr;
342	m = a->q_mailer;
343	errno = 0;
344	if (aliaslevel == 0)
345		a->q_flags |= QPRIMARY;
346	if (tTd(26, 1))
347	{
348		dprintf("\nrecipient (%d): ", aliaslevel);
349		printaddr(a, FALSE);
350	}
351
352	/* if this is primary, add it to the original recipient list */
353	if (a->q_alias == NULL)
354	{
355		if (e->e_origrcpt == NULL)
356			e->e_origrcpt = a->q_paddr;
357		else if (e->e_origrcpt != a->q_paddr)
358			e->e_origrcpt = "";
359	}
360
361#if _FFR_GEN_ORCPT
362	/* set ORCPT DSN arg if not already set */
363	if (a->q_orcpt == NULL)
364	{
365		for (q = a; q->q_alias != NULL; q = q->q_alias)
366			continue;
367
368		/* check for an existing ORCPT */
369		if (q->q_orcpt != NULL)
370			a->q_orcpt = q->q_orcpt;
371		else
372		{
373			/* make our own */
374			bool b = FALSE;
375			char *qp;
376			char obuf[MAXLINE];
377
378			if (e->e_from.q_mailer != NULL)
379				p = e->e_from.q_mailer->m_addrtype;
380			if (p == NULL)
381				p = "rfc822";
382			(void) strlcpy(obuf, p, sizeof obuf);
383			(void) strlcat(obuf, ";", sizeof obuf);
384
385			qp = q->q_paddr;
386
387			/* FFR: Needs to strip comments from stdin addrs */
388
389			/* strip brackets from address */
390			if (*qp == '<')
391			{
392				b = qp[strlen(qp) - 1] == '>';
393				if (b)
394					qp[strlen(qp) - 1] = '\0';
395				qp++;
396			}
397
398			p = xtextify(denlstring(qp, TRUE, FALSE), NULL);
399
400			if (strlcat(obuf, p, sizeof obuf) >= sizeof obuf)
401			{
402				/* if too big, don't use it */
403				obuf[0] = '\0';
404			}
405
406			/* undo damage */
407			if (b)
408				qp[strlen(qp)] = '>';
409
410			if (obuf[0] != '\0')
411				a->q_orcpt = newstr(obuf);
412		}
413	}
414#endif /* _FFR_GEN_ORCPT */
415
416	/* break aliasing loops */
417	if (aliaslevel > MaxAliasRecursion)
418	{
419		a->q_state = QS_BADADDR;
420		a->q_status = "5.4.6";
421		usrerrenh(a->q_status,
422			  "554 aliasing/forwarding loop broken (%d aliases deep; %d max)",
423			  aliaslevel, MaxAliasRecursion);
424		return a;
425	}
426
427	/*
428	**  Finish setting up address structure.
429	*/
430
431	/* get unquoted user for file, program or user.name check */
432	i = strlen(a->q_user);
433	if (i >= sizeof buf0)
434	{
435		buflen = i + 1;
436		buf = xalloc(buflen);
437	}
438	else
439	{
440		buf = buf0;
441		buflen = sizeof buf0;
442	}
443	(void) strlcpy(buf, a->q_user, buflen);
444	for (p = buf; *p != '\0' && !quoted; p++)
445	{
446		if (*p == '\\')
447			quoted = TRUE;
448	}
449	stripquotes(buf);
450
451	/* check for direct mailing to restricted mailers */
452	if (m == ProgMailer)
453	{
454		if (a->q_alias == NULL)
455		{
456			a->q_state = QS_BADADDR;
457			a->q_status = "5.7.1";
458			usrerrenh(a->q_status,
459				  "550 Cannot mail directly to programs");
460		}
461		else if (bitset(QBOGUSSHELL, a->q_alias->q_flags))
462		{
463			a->q_state = QS_BADADDR;
464			a->q_status = "5.7.1";
465			if (a->q_alias->q_ruser == NULL)
466				usrerrenh(a->q_status,
467					  "550 UID %d is an unknown user: cannot mail to programs",
468					  a->q_alias->q_uid);
469			else
470				usrerrenh(a->q_status,
471					  "550 User %s@%s doesn't have a valid shell for mailing to programs",
472					  a->q_alias->q_ruser, MyHostName);
473		}
474		else if (bitset(QUNSAFEADDR, a->q_alias->q_flags))
475		{
476			a->q_state = QS_BADADDR;
477			a->q_status = "5.7.1";
478			a->q_rstatus = newstr("550 Unsafe for mailing to programs");
479			usrerrenh(a->q_status,
480				  "550 Address %s is unsafe for mailing to programs",
481				  a->q_alias->q_paddr);
482		}
483	}
484
485	/*
486	**  Look up this person in the recipient list.
487	**	If they are there already, return, otherwise continue.
488	**	If the list is empty, just add it.  Notice the cute
489	**	hack to make from addresses suppress things correctly:
490	**	the QS_DUPLICATE state will be set in the send list.
491	**	[Please note: the emphasis is on "hack."]
492	*/
493
494	for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
495	{
496		if (sameaddr(q, a) &&
497		    (bitset(QRCPTOK, q->q_flags) ||
498		     !bitset(QPRIMARY, q->q_flags)))
499		{
500			if (tTd(26, 1))
501			{
502				dprintf("%s in sendq: ", a->q_paddr);
503				printaddr(q, FALSE);
504			}
505			if (!bitset(QPRIMARY, q->q_flags))
506			{
507				if (!QS_IS_DEAD(a->q_state))
508					message("duplicate suppressed");
509				else
510					q->q_state = QS_DUPLICATE;
511				q->q_flags |= a->q_flags;
512			}
513			else if (bitset(QSELFREF, q->q_flags)
514#if _FFR_MILTER
515				 || q->q_state == QS_REMOVED
516#endif /* _FFR_MILTER */
517				 )
518			{
519#if _FFR_MILTER
520				/*
521				**  If an earlier milter removed the address,
522				**  a later one can still add it back.
523				*/
524#endif /* _FFR_MILTER */
525				q->q_state = a->q_state;
526				q->q_flags |= a->q_flags;
527			}
528			a = q;
529			goto done;
530		}
531	}
532
533	/* add address on list */
534	if (pq != NULL)
535	{
536		*pq = a;
537		a->q_next = NULL;
538	}
539
540	/*
541	**  Alias the name and handle special mailer types.
542	*/
543
544  trylocaluser:
545	if (tTd(29, 7))
546	{
547		dprintf("at trylocaluser: ");
548		printaddr(a, FALSE);
549	}
550
551	if (!QS_IS_OK(a->q_state))
552		goto testselfdestruct;
553
554	if (m == InclMailer)
555	{
556		a->q_state = QS_INCLUDED;
557		if (a->q_alias == NULL)
558		{
559			a->q_state = QS_BADADDR;
560			a->q_status = "5.7.1";
561			usrerrenh(a->q_status,
562				  "550 Cannot mail directly to :include:s");
563		}
564		else
565		{
566			int ret;
567
568			message("including file %s", a->q_user);
569			ret = include(a->q_user, FALSE, a, sendq, aliaslevel, e);
570			if (transienterror(ret))
571			{
572				if (LogLevel > 2)
573					sm_syslog(LOG_ERR, e->e_id,
574						  "include %s: transient error: %s",
575						  shortenstring(a->q_user, MAXSHORTSTR),
576						  errstring(ret));
577				a->q_state = QS_QUEUEUP;
578				usrerr("451 4.2.4 Cannot open %s: %s",
579					shortenstring(a->q_user, MAXSHORTSTR),
580					errstring(ret));
581			}
582			else if (ret != 0)
583			{
584				a->q_state = QS_BADADDR;
585				a->q_status = "5.2.4";
586				usrerrenh(a->q_status,
587					  "550 Cannot open %s: %s",
588					  shortenstring(a->q_user, MAXSHORTSTR),
589					  errstring(ret));
590			}
591		}
592	}
593	else if (m == FileMailer)
594	{
595		/* check if writable or creatable */
596		if (a->q_alias == NULL)
597		{
598			a->q_state = QS_BADADDR;
599			a->q_status = "5.7.1";
600			usrerrenh(a->q_status,
601				  "550 Cannot mail directly to files");
602		}
603		else if (bitset(QBOGUSSHELL, a->q_alias->q_flags))
604		{
605			a->q_state = QS_BADADDR;
606			a->q_status = "5.7.1";
607			if (a->q_alias->q_ruser == NULL)
608				usrerrenh(a->q_status,
609					  "550 UID %d is an unknown user: cannot mail to files",
610					  a->q_alias->q_uid);
611			else
612				usrerrenh(a->q_status,
613					  "550 User %s@%s doesn't have a valid shell for mailing to files",
614					  a->q_alias->q_ruser, MyHostName);
615		}
616		else if (bitset(QUNSAFEADDR, a->q_alias->q_flags))
617		{
618			a->q_state = QS_BADADDR;
619			a->q_status = "5.7.1";
620			a->q_rstatus = newstr("550 Unsafe for mailing to files");
621			usrerrenh(a->q_status,
622				  "550 Address %s is unsafe for mailing to files",
623				  a->q_alias->q_paddr);
624		}
625	}
626
627	/* try aliasing */
628	if (!quoted && QS_IS_OK(a->q_state) &&
629	    bitnset(M_ALIASABLE, m->m_flags))
630		alias(a, sendq, aliaslevel, e);
631
632#if USERDB
633	/* if not aliased, look it up in the user database */
634	if (!bitset(QNOTREMOTE, a->q_flags) &&
635	    QS_IS_SENDABLE(a->q_state) &&
636	    bitnset(M_CHECKUDB, m->m_flags))
637	{
638		if (udbexpand(a, sendq, aliaslevel, e) == EX_TEMPFAIL)
639		{
640			a->q_state = QS_QUEUEUP;
641			if (e->e_message == NULL)
642				e->e_message = newstr("Deferred: user database error");
643			if (LogLevel > 8)
644				sm_syslog(LOG_INFO, e->e_id,
645					  "deferred: udbexpand: %s",
646					  errstring(errno));
647			message("queued (user database error): %s",
648				errstring(errno));
649			e->e_nrcpts++;
650			goto testselfdestruct;
651		}
652	}
653#endif /* USERDB */
654
655	/*
656	**  If we have a level two config file, then pass the name through
657	**  Ruleset 5 before sending it off.  Ruleset 5 has the right
658	**  to send rewrite it to another mailer.  This gives us a hook
659	**  after local aliasing has been done.
660	*/
661
662	if (tTd(29, 5))
663	{
664		dprintf("recipient: testing local?  cl=%d, rr5=%lx\n\t",
665			ConfigLevel, (u_long) RewriteRules[5]);
666		printaddr(a, FALSE);
667	}
668	if (ConfigLevel >= 2 && RewriteRules[5] != NULL &&
669	    bitnset(M_TRYRULESET5, m->m_flags) &&
670	    !bitset(QNOTREMOTE, a->q_flags) &&
671	    QS_IS_OK(a->q_state))
672	{
673		maplocaluser(a, sendq, aliaslevel + 1, e);
674	}
675
676	/*
677	**  If it didn't get rewritten to another mailer, go ahead
678	**  and deliver it.
679	*/
680
681	if (QS_IS_OK(a->q_state) &&
682	    bitnset(M_HASPWENT, m->m_flags))
683	{
684		auto bool fuzzy;
685		register struct passwd *pw;
686
687		/* warning -- finduser may trash buf */
688		pw = finduser(buf, &fuzzy);
689		if (pw == NULL || strlen(pw->pw_name) > MAXNAME)
690		{
691			{
692				a->q_state = QS_BADADDR;
693				a->q_status = "5.1.1";
694				a->q_rstatus = newstr("550 5.1.1 User unknown");
695				giveresponse(EX_NOUSER, a->q_status, m, NULL,
696					     a->q_alias, (time_t) 0, e);
697			}
698		}
699		else
700		{
701			char nbuf[MAXNAME + 1];
702
703			if (fuzzy)
704			{
705				/* name was a fuzzy match */
706				a->q_user = newstr(pw->pw_name);
707				if (findusercount++ > 3)
708				{
709					a->q_state = QS_BADADDR;
710					a->q_status = "5.4.6";
711					usrerrenh(a->q_status,
712						  "554 aliasing/forwarding loop for %s broken",
713						  pw->pw_name);
714					goto done;
715				}
716
717				/* see if it aliases */
718				(void) strlcpy(buf, pw->pw_name, buflen);
719				goto trylocaluser;
720			}
721			if (strcmp(pw->pw_dir, "/") == 0)
722				a->q_home = "";
723			else
724				a->q_home = newstr(pw->pw_dir);
725			a->q_uid = pw->pw_uid;
726			a->q_gid = pw->pw_gid;
727			a->q_ruser = newstr(pw->pw_name);
728			a->q_flags |= QGOODUID;
729			buildfname(pw->pw_gecos, pw->pw_name, nbuf, sizeof nbuf);
730			if (nbuf[0] != '\0')
731				a->q_fullname = newstr(nbuf);
732			if (!usershellok(pw->pw_name, pw->pw_shell))
733			{
734				a->q_flags |= QBOGUSSHELL;
735			}
736			if (bitset(EF_VRFYONLY, e->e_flags))
737			{
738				/* don't do any more now */
739				a->q_state = QS_VERIFIED;
740			}
741			else if (!quoted)
742				forward(a, sendq, aliaslevel, e);
743		}
744	}
745	if (!QS_IS_DEAD(a->q_state))
746		e->e_nrcpts++;
747
748  testselfdestruct:
749	a->q_flags |= QTHISPASS;
750	if (tTd(26, 8))
751	{
752		dprintf("testselfdestruct: ");
753		printaddr(a, FALSE);
754		if (tTd(26, 10))
755		{
756			dprintf("SENDQ:\n");
757			printaddr(*sendq, TRUE);
758			dprintf("----\n");
759		}
760	}
761	if (a->q_alias == NULL && a != &e->e_from &&
762	    QS_IS_DEAD(a->q_state))
763	{
764		for (q = *sendq; q != NULL; q = q->q_next)
765		{
766			if (!QS_IS_DEAD(q->q_state))
767				break;
768		}
769		if (q == NULL)
770		{
771			a->q_state = QS_BADADDR;
772			a->q_status = "5.4.6";
773			usrerrenh(a->q_status,
774				  "554 aliasing/forwarding loop broken");
775		}
776	}
777
778  done:
779	a->q_flags |= QTHISPASS;
780	if (buf != buf0)
781		free(buf);
782
783	/*
784	**  If we are at the top level, check to see if this has
785	**  expanded to exactly one address.  If so, it can inherit
786	**  the primaryness of the address.
787	**
788	**  While we're at it, clear the QTHISPASS bits.
789	*/
790
791	if (aliaslevel == 0)
792	{
793		int nrcpts = 0;
794		ADDRESS *only = NULL;
795
796		for (q = *sendq; q != NULL; q = q->q_next)
797		{
798			if (bitset(QTHISPASS, q->q_flags) &&
799			    QS_IS_SENDABLE(q->q_state))
800			{
801				nrcpts++;
802				only = q;
803			}
804			q->q_flags &= ~QTHISPASS;
805		}
806		if (nrcpts == 1)
807		{
808			/* check to see if this actually got a new owner */
809			q = only;
810			while ((q = q->q_alias) != NULL)
811			{
812				if (q->q_owner != NULL)
813					break;
814			}
815			if (q == NULL)
816				only->q_flags |= QPRIMARY;
817		}
818		else if (!initialdontsend && nrcpts > 0)
819		{
820			/* arrange for return receipt */
821			e->e_flags |= EF_SENDRECEIPT;
822			a->q_flags |= QEXPANDED;
823			if (e->e_xfp != NULL &&
824			    bitset(QPINGONSUCCESS, a->q_flags))
825				fprintf(e->e_xfp,
826					"%s... expanded to multiple addresses\n",
827					a->q_paddr);
828		}
829	}
830	a->q_flags |= QRCPTOK;
831	return a;
832}
833/*
834**  FINDUSER -- find the password entry for a user.
835**
836**	This looks a lot like getpwnam, except that it may want to
837**	do some fancier pattern matching in /etc/passwd.
838**
839**	This routine contains most of the time of many sendmail runs.
840**	It deserves to be optimized.
841**
842**	Parameters:
843**		name -- the name to match against.
844**		fuzzyp -- an outarg that is set to TRUE if this entry
845**			was found using the fuzzy matching algorithm;
846**			set to FALSE otherwise.
847**
848**	Returns:
849**		A pointer to a pw struct.
850**		NULL if name is unknown or ambiguous.
851**
852**	Side Effects:
853**		may modify name.
854*/
855
856struct passwd *
857finduser(name, fuzzyp)
858	char *name;
859	bool *fuzzyp;
860{
861	register struct passwd *pw;
862	register char *p;
863	bool tryagain;
864
865	if (tTd(29, 4))
866		dprintf("finduser(%s): ", name);
867
868	*fuzzyp = FALSE;
869
870#ifdef HESIOD
871	/* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
872	for (p = name; *p != '\0'; p++)
873		if (!isascii(*p) || !isdigit(*p))
874			break;
875	if (*p == '\0')
876	{
877		if (tTd(29, 4))
878			dprintf("failed (numeric input)\n");
879		return NULL;
880	}
881#endif /* HESIOD */
882
883	/* look up this login name using fast path */
884	if ((pw = sm_getpwnam(name)) != NULL)
885	{
886		if (tTd(29, 4))
887			dprintf("found (non-fuzzy)\n");
888		return pw;
889	}
890
891	/* try mapping it to lower case */
892	tryagain = FALSE;
893	for (p = name; *p != '\0'; p++)
894	{
895		if (isascii(*p) && isupper(*p))
896		{
897			*p = tolower(*p);
898			tryagain = TRUE;
899		}
900	}
901	if (tryagain && (pw = sm_getpwnam(name)) != NULL)
902	{
903		if (tTd(29, 4))
904			dprintf("found (lower case)\n");
905		*fuzzyp = TRUE;
906		return pw;
907	}
908
909#if MATCHGECOS
910	/* see if fuzzy matching allowed */
911	if (!MatchGecos)
912	{
913		if (tTd(29, 4))
914			dprintf("not found (fuzzy disabled)\n");
915		return NULL;
916	}
917
918	/* search for a matching full name instead */
919	for (p = name; *p != '\0'; p++)
920	{
921		if (*p == (SpaceSub & 0177) || *p == '_')
922			*p = ' ';
923	}
924	(void) setpwent();
925	while ((pw = getpwent()) != NULL)
926	{
927		char buf[MAXNAME + 1];
928
929# if 0
930		if (strcasecmp(pw->pw_name, name) == 0)
931		{
932			if (tTd(29, 4))
933				dprintf("found (case wrapped)\n");
934			break;
935		}
936# endif /* 0 */
937
938		buildfname(pw->pw_gecos, pw->pw_name, buf, sizeof buf);
939		if (strchr(buf, ' ') != NULL && strcasecmp(buf, name) == 0)
940		{
941			if (tTd(29, 4))
942				dprintf("fuzzy matches %s\n", pw->pw_name);
943			message("sending to login name %s", pw->pw_name);
944			break;
945		}
946	}
947	if (pw != NULL)
948		*fuzzyp = TRUE;
949	else if (tTd(29, 4))
950		dprintf("no fuzzy match found\n");
951# if DEC_OSF_BROKEN_GETPWENT	/* DEC OSF/1 3.2 or earlier */
952	endpwent();
953# endif /* DEC_OSF_BROKEN_GETPWENT */
954	return pw;
955#else /* MATCHGECOS */
956	if (tTd(29, 4))
957		dprintf("not found (fuzzy disabled)\n");
958	return NULL;
959#endif /* MATCHGECOS */
960}
961/*
962**  WRITABLE -- predicate returning if the file is writable.
963**
964**	This routine must duplicate the algorithm in sys/fio.c.
965**	Unfortunately, we cannot use the access call since we
966**	won't necessarily be the real uid when we try to
967**	actually open the file.
968**
969**	Notice that ANY file with ANY execute bit is automatically
970**	not writable.  This is also enforced by mailfile.
971**
972**	Parameters:
973**		filename -- the file name to check.
974**		ctladdr -- the controlling address for this file.
975**		flags -- SFF_* flags to control the function.
976**
977**	Returns:
978**		TRUE -- if we will be able to write this file.
979**		FALSE -- if we cannot write this file.
980**
981**	Side Effects:
982**		none.
983*/
984
985bool
986writable(filename, ctladdr, flags)
987	char *filename;
988	ADDRESS *ctladdr;
989	long flags;
990{
991	uid_t euid = 0;
992	gid_t egid = 0;
993	char *user = NULL;
994
995	if (tTd(44, 5))
996		dprintf("writable(%s, 0x%lx)\n", filename, flags);
997
998	/*
999	**  File does exist -- check that it is writable.
1000	*/
1001
1002	if (geteuid() != 0)
1003	{
1004		euid = geteuid();
1005		egid = getegid();
1006		user = NULL;
1007	}
1008	else if (ctladdr != NULL)
1009	{
1010		euid = ctladdr->q_uid;
1011		egid = ctladdr->q_gid;
1012		user = ctladdr->q_user;
1013	}
1014	else if (bitset(SFF_RUNASREALUID, flags))
1015	{
1016		euid = RealUid;
1017		egid = RealGid;
1018		user = RealUserName;
1019	}
1020	else if (FileMailer != NULL && !bitset(SFF_ROOTOK, flags))
1021	{
1022		euid = FileMailer->m_uid;
1023		egid = FileMailer->m_gid;
1024		user = NULL;
1025	}
1026	else
1027	{
1028		euid = egid = 0;
1029		user = NULL;
1030	}
1031	if (!bitset(SFF_ROOTOK, flags))
1032	{
1033		if (euid == 0)
1034		{
1035			euid = DefUid;
1036			user = DefUser;
1037		}
1038		if (egid == 0)
1039			egid = DefGid;
1040	}
1041	if (geteuid() == 0 &&
1042	    (ctladdr == NULL || !bitset(QGOODUID, ctladdr->q_flags)))
1043		flags |= SFF_SETUIDOK;
1044
1045	if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
1046		flags |= SFF_NOSLINK;
1047	if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
1048		flags |= SFF_NOHLINK;
1049
1050	errno = safefile(filename, euid, egid, user, flags, S_IWRITE, NULL);
1051	return errno == 0;
1052}
1053/*
1054**  INCLUDE -- handle :include: specification.
1055**
1056**	Parameters:
1057**		fname -- filename to include.
1058**		forwarding -- if TRUE, we are reading a .forward file.
1059**			if FALSE, it's a :include: file.
1060**		ctladdr -- address template to use to fill in these
1061**			addresses -- effective user/group id are
1062**			the important things.
1063**		sendq -- a pointer to the head of the send queue
1064**			to put these addresses in.
1065**		aliaslevel -- the alias nesting depth.
1066**		e -- the current envelope.
1067**
1068**	Returns:
1069**		open error status
1070**
1071**	Side Effects:
1072**		reads the :include: file and sends to everyone
1073**		listed in that file.
1074**
1075**	Security Note:
1076**		If you have restricted chown (that is, you can't
1077**		give a file away), it is reasonable to allow programs
1078**		and files called from this :include: file to be to be
1079**		run as the owner of the :include: file.  This is bogus
1080**		if there is any chance of someone giving away a file.
1081**		We assume that pre-POSIX systems can give away files.
1082**
1083**		There is an additional restriction that if you
1084**		forward to a :include: file, it will not take on
1085**		the ownership of the :include: file.  This may not
1086**		be necessary, but shouldn't hurt.
1087*/
1088
1089static jmp_buf	CtxIncludeTimeout;
1090
1091int
1092include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
1093	char *fname;
1094	bool forwarding;
1095	ADDRESS *ctladdr;
1096	ADDRESS **sendq;
1097	int aliaslevel;
1098	ENVELOPE *e;
1099{
1100	FILE *volatile fp = NULL;
1101	char *oldto = e->e_to;
1102	char *oldfilename = FileName;
1103	int oldlinenumber = LineNumber;
1104	register EVENT *ev = NULL;
1105	int nincludes;
1106	int mode;
1107	volatile bool maxreached = FALSE;
1108	register ADDRESS *ca;
1109	volatile uid_t saveduid;
1110	volatile gid_t savedgid;
1111	volatile uid_t uid;
1112	volatile gid_t gid;
1113	char *volatile user;
1114	int rval = 0;
1115	volatile long sfflags = SFF_REGONLY;
1116	register char *p;
1117	bool safechown = FALSE;
1118	volatile bool safedir = FALSE;
1119	struct stat st;
1120	char buf[MAXLINE];
1121
1122	if (tTd(27, 2))
1123		dprintf("include(%s)\n", fname);
1124	if (tTd(27, 4))
1125		dprintf("   ruid=%d euid=%d\n",
1126			(int) getuid(), (int) geteuid());
1127	if (tTd(27, 14))
1128	{
1129		dprintf("ctladdr ");
1130		printaddr(ctladdr, FALSE);
1131	}
1132
1133	if (tTd(27, 9))
1134		dprintf("include: old uid = %d/%d\n",
1135			(int) getuid(), (int) geteuid());
1136
1137	if (forwarding)
1138		sfflags |= SFF_MUSTOWN|SFF_ROOTOK|SFF_NOWLINK;
1139
1140	/*
1141	**  If RunAsUser set, won't be able to run programs as user
1142	**  so mark them as unsafe unless the administrator knows better.
1143	*/
1144
1145	if ((geteuid() != 0 || RunAsUid != 0) &&
1146	    !bitnset(DBS_NONROOTSAFEADDR, DontBlameSendmail))
1147	{
1148		if (tTd(27, 4))
1149			dprintf("include: not safe (euid=%d, RunAsUid=%d)\n",
1150				(int) geteuid(), (int) RunAsUid);
1151		ctladdr->q_flags |= QUNSAFEADDR;
1152	}
1153
1154	ca = getctladdr(ctladdr);
1155	if (ca == NULL ||
1156	    (ca->q_uid == DefUid && ca->q_gid == 0))
1157	{
1158		uid = DefUid;
1159		gid = DefGid;
1160		user = DefUser;
1161	}
1162	else
1163	{
1164		uid = ca->q_uid;
1165		gid = ca->q_gid;
1166		user = ca->q_user;
1167	}
1168#if MAILER_SETUID_METHOD != USE_SETUID
1169	saveduid = geteuid();
1170	savedgid = getegid();
1171	if (saveduid == 0)
1172	{
1173		if (!DontInitGroups)
1174		{
1175			if (initgroups(user, gid) == -1)
1176			{
1177				rval = EAGAIN;
1178				syserr("include: initgroups(%s, %d) failed",
1179					user, gid);
1180				goto resetuid;
1181			}
1182		}
1183		else
1184		{
1185			GIDSET_T gidset[1];
1186
1187			gidset[0] = gid;
1188			if (setgroups(1, gidset) == -1)
1189			{
1190				rval = EAGAIN;
1191				syserr("include: setgroups() failed");
1192				goto resetuid;
1193			}
1194		}
1195
1196		if (gid != 0 && setgid(gid) < -1)
1197		{
1198			rval = EAGAIN;
1199			syserr("setgid(%d) failure", gid);
1200			goto resetuid;
1201		}
1202		if (uid != 0)
1203		{
1204# if MAILER_SETUID_METHOD == USE_SETEUID
1205			if (seteuid(uid) < 0)
1206			{
1207				rval = EAGAIN;
1208				syserr("seteuid(%d) failure (real=%d, eff=%d)",
1209					uid, getuid(), geteuid());
1210				goto resetuid;
1211			}
1212# endif /* MAILER_SETUID_METHOD == USE_SETEUID */
1213# if MAILER_SETUID_METHOD == USE_SETREUID
1214			if (setreuid(0, uid) < 0)
1215			{
1216				rval = EAGAIN;
1217				syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
1218					uid, getuid(), geteuid());
1219				goto resetuid;
1220			}
1221# endif /* MAILER_SETUID_METHOD == USE_SETREUID */
1222		}
1223	}
1224#endif /* MAILER_SETUID_METHOD != USE_SETUID */
1225
1226	if (tTd(27, 9))
1227		dprintf("include: new uid = %d/%d\n",
1228			(int) getuid(), (int) geteuid());
1229
1230	/*
1231	**  If home directory is remote mounted but server is down,
1232	**  this can hang or give errors; use a timeout to avoid this
1233	*/
1234
1235	if (setjmp(CtxIncludeTimeout) != 0)
1236	{
1237		ctladdr->q_state = QS_QUEUEUP;
1238		errno = 0;
1239
1240		/* return pseudo-error code */
1241		rval = E_SM_OPENTIMEOUT;
1242		goto resetuid;
1243	}
1244	if (TimeOuts.to_fileopen > 0)
1245		ev = setevent(TimeOuts.to_fileopen, includetimeout, 0);
1246	else
1247		ev = NULL;
1248
1249
1250	/* check for writable parent directory */
1251	p = strrchr(fname, '/');
1252	if (p != NULL)
1253	{
1254		int ret;
1255
1256		*p = '\0';
1257		ret = safedirpath(fname, uid, gid, user,
1258				  sfflags|SFF_SAFEDIRPATH, 0, 0);
1259		if (ret == 0)
1260		{
1261			/* in safe directory: relax chown & link rules */
1262			safedir = TRUE;
1263			sfflags |= SFF_NOPATHCHECK;
1264		}
1265		else
1266		{
1267			if (bitnset((forwarding ?
1268				     DBS_FORWARDFILEINUNSAFEDIRPATH :
1269				     DBS_INCLUDEFILEINUNSAFEDIRPATH),
1270				    DontBlameSendmail))
1271				sfflags |= SFF_NOPATHCHECK;
1272			else if (bitnset((forwarding ?
1273					  DBS_FORWARDFILEINGROUPWRITABLEDIRPATH :
1274					  DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH),
1275					 DontBlameSendmail) &&
1276				 ret == E_SM_GWDIR)
1277			{
1278				setbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1279					DontBlameSendmail);
1280				ret = safedirpath(fname, uid, gid, user,
1281						  sfflags|SFF_SAFEDIRPATH,
1282						  0, 0);
1283				clrbitn(DBS_GROUPWRITABLEDIRPATHSAFE,
1284					DontBlameSendmail);
1285				if (ret == 0)
1286					sfflags |= SFF_NOPATHCHECK;
1287				else
1288					sfflags |= SFF_SAFEDIRPATH;
1289			}
1290			else
1291				sfflags |= SFF_SAFEDIRPATH;
1292			if (ret > E_PSEUDOBASE &&
1293			    !bitnset((forwarding ?
1294				      DBS_FORWARDFILEINUNSAFEDIRPATHSAFE :
1295				      DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE),
1296				     DontBlameSendmail))
1297			{
1298				if (LogLevel >= 12)
1299					sm_syslog(LOG_INFO, e->e_id,
1300						  "%s: unsafe directory path, marked unsafe",
1301						  shortenstring(fname, MAXSHORTSTR));
1302				ctladdr->q_flags |= QUNSAFEADDR;
1303			}
1304		}
1305		*p = '/';
1306	}
1307
1308	/* allow links only in unwritable directories */
1309	if (!safedir &&
1310	    !bitnset((forwarding ?
1311		      DBS_LINKEDFORWARDFILEINWRITABLEDIR :
1312		      DBS_LINKEDINCLUDEFILEINWRITABLEDIR),
1313		     DontBlameSendmail))
1314		sfflags |= SFF_NOLINK;
1315
1316	rval = safefile(fname, uid, gid, user, sfflags, S_IREAD, &st);
1317	if (rval != 0)
1318	{
1319		/* don't use this :include: file */
1320		if (tTd(27, 4))
1321			dprintf("include: not safe (uid=%d): %s\n",
1322				(int) uid, errstring(rval));
1323	}
1324	else if ((fp = fopen(fname, "r")) == NULL)
1325	{
1326		rval = errno;
1327		if (tTd(27, 4))
1328			dprintf("include: open: %s\n", errstring(rval));
1329	}
1330	else if (filechanged(fname, fileno(fp), &st))
1331	{
1332		rval = E_SM_FILECHANGE;
1333		if (tTd(27, 4))
1334			dprintf("include: file changed after open\n");
1335	}
1336	if (ev != NULL)
1337		clrevent(ev);
1338
1339resetuid:
1340
1341#if HASSETREUID || USESETEUID
1342	if (saveduid == 0)
1343	{
1344		if (uid != 0)
1345		{
1346# if USESETEUID
1347			if (seteuid(0) < 0)
1348				syserr("!seteuid(0) failure (real=%d, eff=%d)",
1349					getuid(), geteuid());
1350# else /* USESETEUID */
1351			if (setreuid(-1, 0) < 0)
1352				syserr("!setreuid(-1, 0) failure (real=%d, eff=%d)",
1353					getuid(), geteuid());
1354			if (setreuid(RealUid, 0) < 0)
1355				syserr("!setreuid(%d, 0) failure (real=%d, eff=%d)",
1356					RealUid, getuid(), geteuid());
1357# endif /* USESETEUID */
1358		}
1359		if (setgid(savedgid) < 0)
1360			syserr("!setgid(%d) failure (real=%d eff=%d)",
1361			       savedgid, getgid(), getegid());
1362	}
1363#endif /* HASSETREUID || USESETEUID */
1364
1365	if (tTd(27, 9))
1366		dprintf("include: reset uid = %d/%d\n",
1367			(int) getuid(), (int) geteuid());
1368
1369	if (rval == E_SM_OPENTIMEOUT)
1370		usrerr("451 4.4.1 open timeout on %s", fname);
1371
1372	if (fp == NULL)
1373		return rval;
1374
1375	if (fstat(fileno(fp), &st) < 0)
1376	{
1377		rval = errno;
1378		syserr("Cannot fstat %s!", fname);
1379		(void) fclose(fp);
1380		return rval;
1381	}
1382
1383	/* if path was writable, check to avoid file giveaway tricks */
1384	safechown = chownsafe(fileno(fp), safedir);
1385	if (tTd(27, 6))
1386		dprintf("include: parent of %s is %s, chown is %ssafe\n",
1387			fname,
1388			safedir ? "safe" : "dangerous",
1389			safechown ? "" : "un");
1390
1391	/* if no controlling user or coming from an alias delivery */
1392	if (safechown &&
1393	    (ca == NULL ||
1394	     (ca->q_uid == DefUid && ca->q_gid == 0)))
1395	{
1396		ctladdr->q_uid = st.st_uid;
1397		ctladdr->q_gid = st.st_gid;
1398		ctladdr->q_flags |= QGOODUID;
1399	}
1400	if (ca != NULL && ca->q_uid == st.st_uid)
1401	{
1402		/* optimization -- avoid getpwuid if we already have info */
1403		ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL;
1404		ctladdr->q_ruser = ca->q_ruser;
1405	}
1406	else if (!forwarding)
1407	{
1408		register struct passwd *pw;
1409
1410		pw = sm_getpwuid(st.st_uid);
1411		if (pw == NULL)
1412		{
1413			ctladdr->q_uid = st.st_uid;
1414			ctladdr->q_flags |= QBOGUSSHELL;
1415		}
1416		else
1417		{
1418			char *sh;
1419
1420			ctladdr->q_ruser = newstr(pw->pw_name);
1421			if (safechown)
1422				sh = pw->pw_shell;
1423			else
1424				sh = "/SENDMAIL/ANY/SHELL/";
1425			if (!usershellok(pw->pw_name, sh))
1426			{
1427				if (LogLevel >= 12)
1428					sm_syslog(LOG_INFO, e->e_id,
1429						  "%s: user %s has bad shell %s, marked %s",
1430						  shortenstring(fname, MAXSHORTSTR),
1431						  pw->pw_name, sh,
1432						  safechown ? "bogus" : "unsafe");
1433				if (safechown)
1434					ctladdr->q_flags |= QBOGUSSHELL;
1435				else
1436					ctladdr->q_flags |= QUNSAFEADDR;
1437			}
1438		}
1439	}
1440
1441	if (bitset(EF_VRFYONLY, e->e_flags))
1442	{
1443		/* don't do any more now */
1444		ctladdr->q_state = QS_VERIFIED;
1445		e->e_nrcpts++;
1446		(void) fclose(fp);
1447		return rval;
1448	}
1449
1450	/*
1451	**  Check to see if some bad guy can write this file
1452	**
1453	**	Group write checking could be more clever, e.g.,
1454	**	guessing as to which groups are actually safe ("sys"
1455	**	may be; "user" probably is not).
1456	*/
1457
1458	mode = S_IWOTH;
1459	if (!bitnset((forwarding ?
1460		      DBS_GROUPWRITABLEFORWARDFILESAFE :
1461		      DBS_GROUPWRITABLEINCLUDEFILESAFE),
1462		     DontBlameSendmail))
1463		mode |= S_IWGRP;
1464
1465	if (bitset(mode, st.st_mode))
1466	{
1467		if (tTd(27, 6))
1468			dprintf("include: %s is %s writable, marked unsafe\n",
1469				shortenstring(fname, MAXSHORTSTR),
1470				bitset(S_IWOTH, st.st_mode) ? "world" : "group");
1471		if (LogLevel >= 12)
1472			sm_syslog(LOG_INFO, e->e_id,
1473				  "%s: %s writable %s file, marked unsafe",
1474				  shortenstring(fname, MAXSHORTSTR),
1475				  bitset(S_IWOTH, st.st_mode) ? "world" : "group",
1476				  forwarding ? "forward" : ":include:");
1477		ctladdr->q_flags |= QUNSAFEADDR;
1478	}
1479
1480	/* read the file -- each line is a comma-separated list. */
1481	FileName = fname;
1482	LineNumber = 0;
1483	ctladdr->q_flags &= ~QSELFREF;
1484	nincludes = 0;
1485	while (fgets(buf, sizeof buf, fp) != NULL && !maxreached)
1486	{
1487		fixcrlf(buf, TRUE);
1488		LineNumber++;
1489		if (buf[0] == '#' || buf[0] == '\0')
1490			continue;
1491
1492		/* <sp>#@# introduces a comment anywhere */
1493		/* for Japanese character sets */
1494		for (p = buf; (p = strchr(++p, '#')) != NULL; )
1495		{
1496			if (p[1] == '@' && p[2] == '#' &&
1497			    isascii(p[-1]) && isspace(p[-1]) &&
1498			    (p[3] == '\0' || (isascii(p[3]) && isspace(p[3]))))
1499			{
1500				p[-1] = '\0';
1501				break;
1502			}
1503		}
1504		if (buf[0] == '\0')
1505			continue;
1506
1507		e->e_to = NULL;
1508		message("%s to %s",
1509			forwarding ? "forwarding" : "sending", buf);
1510		if (forwarding && LogLevel > 10)
1511			sm_syslog(LOG_INFO, e->e_id,
1512				  "forward %.200s => %s",
1513				  oldto, shortenstring(buf, MAXSHORTSTR));
1514
1515		nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1516
1517		if (forwarding &&
1518		    MaxForwardEntries > 0 &&
1519		    nincludes >= MaxForwardEntries)
1520		{
1521			/* just stop reading and processing further entries */
1522			/* additional: (?)
1523			ctladdr->q_state = QS_DONTSEND;
1524			**/
1525			syserr("Attempt to forward to more then %d addresses (in %s)!",
1526				MaxForwardEntries,fname);
1527			maxreached = TRUE;
1528		}
1529	}
1530
1531	if (ferror(fp) && tTd(27, 3))
1532		dprintf("include: read error: %s\n", errstring(errno));
1533	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1534	{
1535		if (tTd(27, 5))
1536		{
1537			dprintf("include: QS_DONTSEND ");
1538			printaddr(ctladdr, FALSE);
1539		}
1540		ctladdr->q_state = QS_DONTSEND;
1541	}
1542
1543	(void) fclose(fp);
1544	FileName = oldfilename;
1545	LineNumber = oldlinenumber;
1546	e->e_to = oldto;
1547	return rval;
1548}
1549
1550static void
1551includetimeout()
1552{
1553	longjmp(CtxIncludeTimeout, 1);
1554}
1555/*
1556**  SENDTOARGV -- send to an argument vector.
1557**
1558**	Parameters:
1559**		argv -- argument vector to send to.
1560**		e -- the current envelope.
1561**
1562**	Returns:
1563**		none.
1564**
1565**	Side Effects:
1566**		puts all addresses on the argument vector onto the
1567**			send queue.
1568*/
1569
1570void
1571sendtoargv(argv, e)
1572	register char **argv;
1573	register ENVELOPE *e;
1574{
1575	register char *p;
1576
1577	while ((p = *argv++) != NULL)
1578	{
1579		(void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1580	}
1581}
1582/*
1583**  GETCTLADDR -- get controlling address from an address header.
1584**
1585**	If none, get one corresponding to the effective userid.
1586**
1587**	Parameters:
1588**		a -- the address to find the controller of.
1589**
1590**	Returns:
1591**		the controlling address.
1592**
1593**	Side Effects:
1594**		none.
1595*/
1596
1597ADDRESS *
1598getctladdr(a)
1599	register ADDRESS *a;
1600{
1601	while (a != NULL && !bitset(QGOODUID, a->q_flags))
1602		a = a->q_alias;
1603	return a;
1604}
1605/*
1606**  SELF_REFERENCE -- check to see if an address references itself
1607**
1608**	The check is done through a chain of aliases.  If it is part of
1609**	a loop, break the loop at the "best" address, that is, the one
1610**	that exists as a real user.
1611**
1612**	This is to handle the case of:
1613**		awc:		Andrew.Chang
1614**		Andrew.Chang:	awc@mail.server
1615**	which is a problem only on mail.server.
1616**
1617**	Parameters:
1618**		a -- the address to check.
1619**
1620**	Returns:
1621**		The address that should be retained.
1622*/
1623
1624static ADDRESS *
1625self_reference(a)
1626	ADDRESS *a;
1627{
1628	ADDRESS *b;		/* top entry in self ref loop */
1629	ADDRESS *c;		/* entry that point to a real mail box */
1630
1631	if (tTd(27, 1))
1632		dprintf("self_reference(%s)\n", a->q_paddr);
1633
1634	for (b = a->q_alias; b != NULL; b = b->q_alias)
1635	{
1636		if (sameaddr(a, b))
1637			break;
1638	}
1639
1640	if (b == NULL)
1641	{
1642		if (tTd(27, 1))
1643			dprintf("\t... no self ref\n");
1644		return NULL;
1645	}
1646
1647	/*
1648	**  Pick the first address that resolved to a real mail box
1649	**  i.e has a pw entry.  The returned value will be marked
1650	**  QSELFREF in recipient(), which in turn will disable alias()
1651	**  from marking it as QS_IS_DEAD(), which mean it will be used
1652	**  as a deliverable address.
1653	**
1654	**  The 2 key thing to note here are:
1655	**	1) we are in a recursive call sequence:
1656	**		alias->sentolist->recipient->alias
1657	**	2) normally, when we return back to alias(), the address
1658	**	   will be marked QS_EXPANDED, since alias() assumes the
1659	**	   expanded form will be used instead of the current address.
1660	**	   This behaviour is turned off if the address is marked
1661	**	   QSELFREF We set QSELFREF when we return to recipient().
1662	*/
1663
1664	c = a;
1665	while (c != NULL)
1666	{
1667		if (tTd(27, 10))
1668			dprintf("  %s", c->q_user);
1669		if (bitnset(M_HASPWENT, c->q_mailer->m_flags))
1670		{
1671			if (tTd(27, 2))
1672				dprintf("\t... getpwnam(%s)... ", c->q_user);
1673			if (sm_getpwnam(c->q_user) != NULL)
1674			{
1675				if (tTd(27, 2))
1676					dprintf("found\n");
1677
1678				/* ought to cache results here */
1679				if (sameaddr(b, c))
1680					return b;
1681				else
1682					return c;
1683			}
1684			if (tTd(27, 2))
1685				dprintf("failed\n");
1686		}
1687		else
1688		{
1689			/* if local delivery, compare usernames */
1690			if (bitnset(M_LOCALMAILER, c->q_mailer->m_flags) &&
1691			    b->q_mailer == c->q_mailer)
1692			{
1693				if (tTd(27, 2))
1694					dprintf("\t... local match (%s)\n",
1695						c->q_user);
1696				if (sameaddr(b, c))
1697					return b;
1698				else
1699					return c;
1700			}
1701		}
1702		if (tTd(27, 10))
1703			dprintf("\n");
1704		c = c->q_alias;
1705	}
1706
1707	if (tTd(27, 1))
1708		dprintf("\t... cannot break loop for \"%s\"\n", a->q_paddr);
1709
1710	return NULL;
1711}
1712