1 /*
2  * Copyright (c) 1983, 1995 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)recipient.c	8.84 (Berkeley) 05/18/95";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 
15 /*
16 **  SENDTOLIST -- Designate a send list.
17 **
18 **	The parameter is a comma-separated list of people to send to.
19 **	This routine arranges to send to all of them.
20 **
21 **	Parameters:
22 **		list -- the send list.
23 **		ctladdr -- the address template for the person to
24 **			send to -- effective uid/gid are important.
25 **			This is typically the alias that caused this
26 **			expansion.
27 **		sendq -- a pointer to the head of a queue to put
28 **			these people into.
29 **		aliaslevel -- the current alias nesting depth -- to
30 **			diagnose loops.
31 **		e -- the envelope in which to add these recipients.
32 **
33 **	Returns:
34 **		The number of addresses actually on the list.
35 **
36 **	Side Effects:
37 **		none.
38 */
39 
40 #define MAXRCRSN	10	/* maximum levels of alias recursion */
41 
42 /* q_flags bits inherited from ctladdr */
43 #define QINHERITEDBITS	(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY)
44 
45 int
46 sendtolist(list, ctladdr, sendq, aliaslevel, e)
47 	char *list;
48 	ADDRESS *ctladdr;
49 	ADDRESS **sendq;
50 	int aliaslevel;
51 	register ENVELOPE *e;
52 {
53 	register char *p;
54 	register ADDRESS *al;	/* list of addresses to send to */
55 	bool firstone;		/* set on first address sent */
56 	char delimiter;		/* the address delimiter */
57 	int naddrs;
58 	int i;
59 	char *oldto = e->e_to;
60 	char *bufp;
61 	char buf[MAXNAME + 1];
62 
63 	if (list == NULL)
64 	{
65 		syserr("sendtolist: null list");
66 		return 0;
67 	}
68 
69 	if (tTd(25, 1))
70 	{
71 		printf("sendto: %s\n   ctladdr=", list);
72 		printaddr(ctladdr, FALSE);
73 	}
74 
75 	/* heuristic to determine old versus new style addresses */
76 	if (ctladdr == NULL &&
77 	    (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
78 	     strchr(list, '<') != NULL || strchr(list, '(') != NULL))
79 		e->e_flags &= ~EF_OLDSTYLE;
80 	delimiter = ' ';
81 	if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
82 		delimiter = ',';
83 
84 	firstone = TRUE;
85 	al = NULL;
86 	naddrs = 0;
87 
88 	/* make sure we have enough space to copy the string */
89 	i = strlen(list) + 1;
90 	if (i <= sizeof buf)
91 		bufp = buf;
92 	else
93 		bufp = xalloc(i);
94 	strcpy(bufp, denlstring(list, FALSE, TRUE));
95 
96 	for (p = bufp; *p != '\0'; )
97 	{
98 		auto char *delimptr;
99 		register ADDRESS *a;
100 
101 		/* parse the address */
102 		while ((isascii(*p) && isspace(*p)) || *p == ',')
103 			p++;
104 		a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter, &delimptr, e);
105 		p = delimptr;
106 		if (a == NULL)
107 			continue;
108 		a->q_next = al;
109 		a->q_alias = ctladdr;
110 
111 		/* arrange to inherit attributes from parent */
112 		if (ctladdr != NULL)
113 		{
114 			ADDRESS *b;
115 			extern ADDRESS *self_reference();
116 
117 #if 0
118 			/* self reference test */
119 			if (sameaddr(ctladdr, a))
120 				ctladdr->q_flags |= QSELFREF;
121 #endif
122 
123 			/* check for address loops */
124 			b = self_reference(a, e);
125 			if (b != NULL)
126 			{
127 				b->q_flags |= QSELFREF;
128 				if (a != b)
129 				{
130 					a->q_flags |= QDONTSEND;
131 					continue;
132 				}
133 			}
134 
135 			/* full name */
136 			if (a->q_fullname == NULL)
137 				a->q_fullname = ctladdr->q_fullname;
138 
139 			/* various flag bits */
140 			a->q_flags &= ~QINHERITEDBITS;
141 			a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
142 
143 			/* original recipient information */
144 			a->q_orcpt = ctladdr->q_orcpt;
145 		}
146 
147 		al = a;
148 		firstone = FALSE;
149 	}
150 
151 	/* arrange to send to everyone on the local send list */
152 	while (al != NULL)
153 	{
154 		register ADDRESS *a = al;
155 
156 		al = a->q_next;
157 		a = recipient(a, sendq, aliaslevel, e);
158 		naddrs++;
159 	}
160 
161 	e->e_to = oldto;
162 	if (bufp != buf)
163 		free(bufp);
164 	return (naddrs);
165 }
166 /*
167 **  RECIPIENT -- Designate a message recipient
168 **
169 **	Saves the named person for future mailing.
170 **
171 **	Parameters:
172 **		a -- the (preparsed) address header for the recipient.
173 **		sendq -- a pointer to the head of a queue to put the
174 **			recipient in.  Duplicate supression is done
175 **			in this queue.
176 **		aliaslevel -- the current alias nesting depth.
177 **		e -- the current envelope.
178 **
179 **	Returns:
180 **		The actual address in the queue.  This will be "a" if
181 **		the address is not a duplicate, else the original address.
182 **
183 **	Side Effects:
184 **		none.
185 */
186 
187 ADDRESS *
188 recipient(a, sendq, aliaslevel, e)
189 	register ADDRESS *a;
190 	register ADDRESS **sendq;
191 	int aliaslevel;
192 	register ENVELOPE *e;
193 {
194 	register ADDRESS *q;
195 	ADDRESS **pq;
196 	register struct mailer *m;
197 	register char *p;
198 	bool quoted = FALSE;		/* set if the addr has a quote bit */
199 	int findusercount = 0;
200 	bool initialdontsend = bitset(QDONTSEND, a->q_flags);
201 	int i;
202 	char *buf;
203 	char buf0[MAXNAME + 1];		/* unquoted image of the user name */
204 	extern int safefile();
205 
206 	e->e_to = a->q_paddr;
207 	m = a->q_mailer;
208 	errno = 0;
209 	if (aliaslevel == 0)
210 		a->q_flags |= QPRIMARY;
211 	if (tTd(26, 1))
212 	{
213 		printf("\nrecipient (%d): ", aliaslevel);
214 		printaddr(a, FALSE);
215 	}
216 
217 	/* if this is primary, add it to the original recipient list */
218 	if (a->q_alias == NULL)
219 	{
220 		if (e->e_origrcpt == NULL)
221 			e->e_origrcpt = a->q_paddr;
222 		else if (e->e_origrcpt != a->q_paddr)
223 			e->e_origrcpt = "";
224 	}
225 
226 	/* break aliasing loops */
227 	if (aliaslevel > MAXRCRSN)
228 	{
229 		a->q_status = "5.4.6";
230 		usrerr("554 aliasing/forwarding loop broken (%d aliases deep; %d max",
231 			aliaslevel, MAXRCRSN);
232 		return (a);
233 	}
234 
235 	/*
236 	**  Finish setting up address structure.
237 	*/
238 
239 	/* get unquoted user for file, program or user.name check */
240 	i = strlen(a->q_user);
241 	if (i >= sizeof buf0)
242 		buf = xalloc(i + 1);
243 	else
244 		buf = buf0;
245 	(void) strcpy(buf, a->q_user);
246 	for (p = buf; *p != '\0' && !quoted; p++)
247 	{
248 		if (*p == '\\')
249 			quoted = TRUE;
250 	}
251 	stripquotes(buf);
252 
253 	/* check for direct mailing to restricted mailers */
254 	if (m == ProgMailer)
255 	{
256 		if (a->q_alias == NULL)
257 		{
258 			a->q_flags |= QBADADDR;
259 			a->q_status = "5.7.1";
260 			usrerr("550 Cannot mail directly to programs");
261 		}
262 		else if (bitset(QBOGUSSHELL, a->q_alias->q_flags))
263 		{
264 			a->q_flags |= QBADADDR;
265 			a->q_status = "5.7.1";
266 			usrerr("550 User %s@%s doesn't have a valid shell for mailing to programs",
267 				a->q_alias->q_ruser, MyHostName);
268 		}
269 		else if (bitset(QUNSAFEADDR, a->q_alias->q_flags))
270 		{
271 			a->q_flags |= QBADADDR;
272 			a->q_status = "5.7.1";
273 			usrerr("550 Address %s is unsafe for mailing to programs",
274 				a->q_alias->q_paddr);
275 		}
276 	}
277 
278 	/*
279 	**  Look up this person in the recipient list.
280 	**	If they are there already, return, otherwise continue.
281 	**	If the list is empty, just add it.  Notice the cute
282 	**	hack to make from addresses suppress things correctly:
283 	**	the QDONTSEND bit will be set in the send list.
284 	**	[Please note: the emphasis is on "hack."]
285 	*/
286 
287 	for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
288 	{
289 		if (sameaddr(q, a))
290 		{
291 			if (tTd(26, 1))
292 			{
293 				printf("%s in sendq: ", a->q_paddr);
294 				printaddr(q, FALSE);
295 			}
296 			if (!bitset(QPRIMARY, q->q_flags))
297 			{
298 				if (!bitset(QDONTSEND, a->q_flags))
299 					message("duplicate suppressed");
300 				q->q_flags |= a->q_flags;
301 			}
302 			else if (bitset(QSELFREF, q->q_flags))
303 				q->q_flags |= a->q_flags & ~QDONTSEND;
304 			a = q;
305 			goto done;
306 		}
307 	}
308 
309 	/* add address on list */
310 	*pq = a;
311 	a->q_next = NULL;
312 
313 	/*
314 	**  Alias the name and handle special mailer types.
315 	*/
316 
317   trylocaluser:
318 	if (tTd(29, 7))
319 		printf("at trylocaluser %s\n", a->q_user);
320 
321 	if (bitset(QDONTSEND|QBADADDR|QVERIFIED, a->q_flags))
322 		goto testselfdestruct;
323 
324 	if (m == InclMailer)
325 	{
326 		a->q_flags |= QDONTSEND;
327 		if (a->q_alias == NULL)
328 		{
329 			a->q_flags |= QBADADDR;
330 			a->q_status = "5.7.1";
331 			usrerr("550 Cannot mail directly to :include:s");
332 		}
333 		else
334 		{
335 			int ret;
336 
337 			message("including file %s", a->q_user);
338 			ret = include(a->q_user, FALSE, a, sendq, aliaslevel, e);
339 			if (transienterror(ret))
340 			{
341 #ifdef LOG
342 				if (LogLevel > 2)
343 					syslog(LOG_ERR, "%s: include %s: transient error: %s",
344 						e->e_id == NULL ? "NOQUEUE" : e->e_id,
345 						a->q_user, errstring(ret));
346 #endif
347 				a->q_flags |= QQUEUEUP;
348 				a->q_flags &= ~QDONTSEND;
349 				usrerr("451 Cannot open %s: %s",
350 					a->q_user, errstring(ret));
351 			}
352 			else if (ret != 0)
353 			{
354 				a->q_flags |= QBADADDR;
355 				a->q_status = "5.2.4";
356 				usrerr("550 Cannot open %s: %s",
357 					a->q_user, errstring(ret));
358 			}
359 		}
360 	}
361 	else if (m == FileMailer)
362 	{
363 		extern bool writable();
364 
365 		/* check if writable or creatable */
366 		if (a->q_alias == NULL)
367 		{
368 			a->q_flags |= QBADADDR;
369 			a->q_status = "5.7.1";
370 			usrerr("550 Cannot mail directly to files");
371 		}
372 		else if (bitset(QBOGUSSHELL, a->q_alias->q_flags))
373 		{
374 			a->q_flags |= QBADADDR;
375 			a->q_status = "5.7.1";
376 			usrerr("550 User %s@%s doesn't have a valid shell for mailing to files",
377 				a->q_alias->q_ruser, MyHostName);
378 		}
379 		else if (bitset(QUNSAFEADDR, a->q_alias->q_flags))
380 		{
381 			a->q_flags |= QBADADDR;
382 			a->q_status = "5.7.1";
383 			usrerr("550 Address %s is unsafe for mailing to files",
384 				a->q_alias->q_paddr);
385 		}
386 		else if (!writable(buf, getctladdr(a), SFF_CREAT))
387 		{
388 			a->q_flags |= QBADADDR;
389 			giveresponse(EX_CANTCREAT, m, NULL, a->q_alias,
390 				     (time_t) 0, e);
391 		}
392 	}
393 
394 	/* try aliasing */
395 	if (!bitset(QDONTSEND, a->q_flags) && bitnset(M_ALIASABLE, m->m_flags))
396 		alias(a, sendq, aliaslevel, e);
397 
398 # ifdef USERDB
399 	/* if not aliased, look it up in the user database */
400 	if (!bitset(QDONTSEND|QNOTREMOTE|QVERIFIED, a->q_flags) &&
401 	    bitnset(M_CHECKUDB, m->m_flags))
402 	{
403 		extern int udbexpand();
404 
405 		if (udbexpand(a, sendq, aliaslevel, e) == EX_TEMPFAIL)
406 		{
407 			a->q_flags |= QQUEUEUP;
408 			if (e->e_message == NULL)
409 				e->e_message = newstr("Deferred: user database error");
410 # ifdef LOG
411 			if (LogLevel > 8)
412 				syslog(LOG_INFO, "%s: deferred: udbexpand: %s",
413 					e->e_id == NULL ? "NOQUEUE" : e->e_id,
414 					errstring(errno));
415 # endif
416 			message("queued (user database error): %s",
417 				errstring(errno));
418 			e->e_nrcpts++;
419 			goto testselfdestruct;
420 		}
421 	}
422 # endif
423 
424 	/*
425 	**  If we have a level two config file, then pass the name through
426 	**  Ruleset 5 before sending it off.  Ruleset 5 has the right
427 	**  to send rewrite it to another mailer.  This gives us a hook
428 	**  after local aliasing has been done.
429 	*/
430 
431 	if (tTd(29, 5))
432 	{
433 		printf("recipient: testing local?  cl=%d, rr5=%x\n\t",
434 			ConfigLevel, RewriteRules[5]);
435 		printaddr(a, FALSE);
436 	}
437 	if (!bitset(QNOTREMOTE|QDONTSEND|QQUEUEUP|QVERIFIED, a->q_flags) &&
438 	    ConfigLevel >= 2 && RewriteRules[5] != NULL &&
439 	    bitnset(M_TRYRULESET5, m->m_flags))
440 	{
441 		maplocaluser(a, sendq, aliaslevel + 1, e);
442 	}
443 
444 	/*
445 	**  If it didn't get rewritten to another mailer, go ahead
446 	**  and deliver it.
447 	*/
448 
449 	if (!bitset(QDONTSEND|QQUEUEUP|QVERIFIED, a->q_flags) &&
450 	    bitnset(M_HASPWENT, m->m_flags))
451 	{
452 		auto bool fuzzy;
453 		register struct passwd *pw;
454 		extern struct passwd *finduser();
455 
456 		/* warning -- finduser may trash buf */
457 		pw = finduser(buf, &fuzzy);
458 		if (pw == NULL)
459 		{
460 			a->q_flags |= QBADADDR;
461 			a->q_status = "5.1.1";
462 			giveresponse(EX_NOUSER, m, NULL, a->q_alias,
463 				     (time_t) 0, e);
464 		}
465 		else
466 		{
467 			char nbuf[MAXNAME + 1];
468 
469 			if (fuzzy)
470 			{
471 				/* name was a fuzzy match */
472 				a->q_user = newstr(pw->pw_name);
473 				if (findusercount++ > 3)
474 				{
475 					a->q_flags |= QBADADDR;
476 					a->q_status = "5.4.6";
477 					usrerr("554 aliasing/forwarding loop for %s broken",
478 						pw->pw_name);
479 					goto done;
480 				}
481 
482 				/* see if it aliases */
483 				(void) strcpy(buf, pw->pw_name);
484 				goto trylocaluser;
485 			}
486 			if (strcmp(pw->pw_dir, "/") == 0)
487 				a->q_home = "";
488 			else
489 				a->q_home = newstr(pw->pw_dir);
490 			a->q_uid = pw->pw_uid;
491 			a->q_gid = pw->pw_gid;
492 			a->q_ruser = newstr(pw->pw_name);
493 			a->q_flags |= QGOODUID;
494 			buildfname(pw->pw_gecos, pw->pw_name, nbuf);
495 			if (nbuf[0] != '\0')
496 				a->q_fullname = newstr(nbuf);
497 			if (pw->pw_shell != NULL && pw->pw_shell[0] != '\0' &&
498 			    !usershellok(pw->pw_shell))
499 			{
500 				a->q_flags |= QBOGUSSHELL;
501 			}
502 			if (!quoted)
503 				forward(a, sendq, aliaslevel, e);
504 		}
505 	}
506 	if (!bitset(QDONTSEND, a->q_flags))
507 		e->e_nrcpts++;
508 
509   testselfdestruct:
510 	a->q_flags |= QTHISPASS;
511 	if (tTd(26, 8))
512 	{
513 		printf("testselfdestruct: ");
514 		printaddr(a, FALSE);
515 		if (tTd(26, 10))
516 		{
517 			printf("SENDQ:\n");
518 			printaddr(*sendq, TRUE);
519 			printf("----\n");
520 		}
521 	}
522 	if (a->q_alias == NULL && a != &e->e_from &&
523 	    bitset(QDONTSEND, a->q_flags))
524 	{
525 		for (q = *sendq; q != NULL; q = q->q_next)
526 		{
527 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags) &&
528 			    bitset(QTHISPASS, q->q_flags))
529 				break;
530 		}
531 		if (q == NULL)
532 		{
533 			a->q_flags |= QBADADDR;
534 			a->q_status = "5.4.6";
535 			usrerr("554 aliasing/forwarding loop broken");
536 		}
537 	}
538 
539   done:
540 	a->q_flags |= QTHISPASS;
541 	if (buf != buf0)
542 		free(buf);
543 
544 	/*
545 	**  If we are at the top level, check to see if this has
546 	**  expanded to exactly one address.  If so, it can inherit
547 	**  the primaryness of the address.
548 	**
549 	**  While we're at it, clear the QTHISPASS bits.
550 	*/
551 
552 	if (aliaslevel == 0)
553 	{
554 		int nrcpts = 0;
555 		ADDRESS *only;
556 
557 		for (q = *sendq; q != NULL; q = q->q_next)
558 		{
559 			if (bitset(QTHISPASS, q->q_flags) &&
560 			    !bitset(QDONTSEND|QBADADDR, q->q_flags))
561 			{
562 				nrcpts++;
563 				only = q;
564 			}
565 			q->q_flags &= ~QTHISPASS;
566 		}
567 		if (nrcpts == 1)
568 		{
569 			/* check to see if this actually got a new owner */
570 			q = only;
571 			while ((q = q->q_alias) != NULL)
572 			{
573 				if (q->q_owner != NULL)
574 					break;
575 			}
576 			if (q == NULL)
577 				only->q_flags |= QPRIMARY;
578 		}
579 		else if (!initialdontsend && nrcpts > 0)
580 		{
581 			/* arrange for return receipt */
582 			e->e_flags |= EF_SENDRECEIPT;
583 			a->q_flags |= QEXPANDED;
584 			if (e->e_xfp != NULL)
585 				fprintf(e->e_xfp,
586 					"%s... expanded to multiple addresses\n",
587 					a->q_paddr);
588 		}
589 	}
590 
591 	return (a);
592 }
593 /*
594 **  FINDUSER -- find the password entry for a user.
595 **
596 **	This looks a lot like getpwnam, except that it may want to
597 **	do some fancier pattern matching in /etc/passwd.
598 **
599 **	This routine contains most of the time of many sendmail runs.
600 **	It deserves to be optimized.
601 **
602 **	Parameters:
603 **		name -- the name to match against.
604 **		fuzzyp -- an outarg that is set to TRUE if this entry
605 **			was found using the fuzzy matching algorithm;
606 **			set to FALSE otherwise.
607 **
608 **	Returns:
609 **		A pointer to a pw struct.
610 **		NULL if name is unknown or ambiguous.
611 **
612 **	Side Effects:
613 **		may modify name.
614 */
615 
616 struct passwd *
617 finduser(name, fuzzyp)
618 	char *name;
619 	bool *fuzzyp;
620 {
621 	register struct passwd *pw;
622 	register char *p;
623 
624 	if (tTd(29, 4))
625 		printf("finduser(%s): ", name);
626 
627 	*fuzzyp = FALSE;
628 
629 #ifdef HESIOD
630 	/* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
631 	for (p = name; *p != '\0'; p++)
632 		if (!isascii(*p) || !isdigit(*p))
633 			break;
634 	if (*p == '\0')
635 	{
636 		if (tTd(29, 4))
637 			printf("failed (numeric input)\n");
638 		return NULL;
639 	}
640 #endif
641 
642 	/* look up this login name using fast path */
643 	if ((pw = sm_getpwnam(name)) != NULL)
644 	{
645 		if (tTd(29, 4))
646 			printf("found (non-fuzzy)\n");
647 		return (pw);
648 	}
649 
650 #ifdef MATCHGECOS
651 	/* see if fuzzy matching allowed */
652 	if (!MatchGecos)
653 	{
654 		if (tTd(29, 4))
655 			printf("not found (fuzzy disabled)\n");
656 		return NULL;
657 	}
658 
659 	/* search for a matching full name instead */
660 	for (p = name; *p != '\0'; p++)
661 	{
662 		if (*p == (SpaceSub & 0177) || *p == '_')
663 			*p = ' ';
664 	}
665 	(void) setpwent();
666 	while ((pw = getpwent()) != NULL)
667 	{
668 		char buf[MAXNAME + 1];
669 
670 		buildfname(pw->pw_gecos, pw->pw_name, buf);
671 		if (strchr(buf, ' ') != NULL && !strcasecmp(buf, name))
672 		{
673 			if (tTd(29, 4))
674 				printf("fuzzy matches %s\n", pw->pw_name);
675 			message("sending to login name %s", pw->pw_name);
676 			*fuzzyp = TRUE;
677 			return (pw);
678 		}
679 	}
680 	if (tTd(29, 4))
681 		printf("no fuzzy match found\n");
682 #else
683 	if (tTd(29, 4))
684 		printf("not found (fuzzy disabled)\n");
685 #endif
686 	return (NULL);
687 }
688 /*
689 **  WRITABLE -- predicate returning if the file is writable.
690 **
691 **	This routine must duplicate the algorithm in sys/fio.c.
692 **	Unfortunately, we cannot use the access call since we
693 **	won't necessarily be the real uid when we try to
694 **	actually open the file.
695 **
696 **	Notice that ANY file with ANY execute bit is automatically
697 **	not writable.  This is also enforced by mailfile.
698 **
699 **	Parameters:
700 **		filename -- the file name to check.
701 **		ctladdr -- the controlling address for this file.
702 **		flags -- SFF_* flags to control the function.
703 **
704 **	Returns:
705 **		TRUE -- if we will be able to write this file.
706 **		FALSE -- if we cannot write this file.
707 **
708 **	Side Effects:
709 **		none.
710 */
711 
712 bool
713 writable(filename, ctladdr, flags)
714 	char *filename;
715 	ADDRESS *ctladdr;
716 	int flags;
717 {
718 	uid_t euid;
719 	gid_t egid;
720 	int bits;
721 	register char *p;
722 	char *uname;
723 
724 	if (tTd(29, 5))
725 		printf("writable(%s, 0x%x)\n", filename, flags);
726 
727 #ifdef SUID_ROOT_FILES_OK
728 	/* really ought to be passed down -- and not a good idea */
729 	flags |= SFF_ROOTOK;
730 #endif
731 
732 	/*
733 	**  File does exist -- check that it is writable.
734 	*/
735 
736 	if (ctladdr != NULL && geteuid() == 0)
737 	{
738 		euid = ctladdr->q_uid;
739 		egid = ctladdr->q_gid;
740 		uname = ctladdr->q_user;
741 	}
742 	else if (bitset(SFF_RUNASREALUID, flags))
743 	{
744 		extern char RealUserName[];
745 
746 		euid = RealUid;
747 		egid = RealGid;
748 		uname = RealUserName;
749 	}
750 	else if (FileMailer != NULL)
751 	{
752 		euid = FileMailer->m_uid;
753 		egid = FileMailer->m_gid;
754 	}
755 	else
756 	{
757 		euid = egid = 0;
758 	}
759 	if (euid == 0)
760 	{
761 		euid = DefUid;
762 		uname = DefUser;
763 	}
764 	if (egid == 0)
765 		egid = DefGid;
766 	if (geteuid() == 0)
767 		flags |= SFF_SETUIDOK;
768 
769 	errno = safefile(filename, euid, egid, uname, flags, S_IWRITE, NULL);
770 	return errno == 0;
771 }
772 /*
773 **  INCLUDE -- handle :include: specification.
774 **
775 **	Parameters:
776 **		fname -- filename to include.
777 **		forwarding -- if TRUE, we are reading a .forward file.
778 **			if FALSE, it's a :include: file.
779 **		ctladdr -- address template to use to fill in these
780 **			addresses -- effective user/group id are
781 **			the important things.
782 **		sendq -- a pointer to the head of the send queue
783 **			to put these addresses in.
784 **		aliaslevel -- the alias nesting depth.
785 **		e -- the current envelope.
786 **
787 **	Returns:
788 **		open error status
789 **
790 **	Side Effects:
791 **		reads the :include: file and sends to everyone
792 **		listed in that file.
793 **
794 **	Security Note:
795 **		If you have restricted chown (that is, you can't
796 **		give a file away), it is reasonable to allow programs
797 **		and files called from this :include: file to be to be
798 **		run as the owner of the :include: file.  This is bogus
799 **		if there is any chance of someone giving away a file.
800 **		We assume that pre-POSIX systems can give away files.
801 **
802 **		There is an additional restriction that if you
803 **		forward to a :include: file, it will not take on
804 **		the ownership of the :include: file.  This may not
805 **		be necessary, but shouldn't hurt.
806 */
807 
808 static jmp_buf	CtxIncludeTimeout;
809 static void	includetimeout();
810 
811 int
812 include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
813 	char *fname;
814 	bool forwarding;
815 	ADDRESS *ctladdr;
816 	ADDRESS **sendq;
817 	int aliaslevel;
818 	ENVELOPE *e;
819 {
820 	FILE *fp = NULL;
821 	char *oldto = e->e_to;
822 	char *oldfilename = FileName;
823 	int oldlinenumber = LineNumber;
824 	register EVENT *ev = NULL;
825 	int nincludes;
826 	register ADDRESS *ca;
827 	uid_t saveduid, uid;
828 	gid_t savedgid, gid;
829 	char *uname;
830 	int rval = 0;
831 	int sfflags = SFF_REGONLY;
832 	struct stat st;
833 	char buf[MAXLINE];
834 #ifdef _POSIX_CHOWN_RESTRICTED
835 # if _POSIX_CHOWN_RESTRICTED == -1
836 #  define safechown	FALSE
837 # else
838 #  define safechown	TRUE
839 # endif
840 #else
841 # ifdef _PC_CHOWN_RESTRICTED
842 	bool safechown;
843 # else
844 #  ifdef BSD
845 #   define safechown	TRUE
846 #  else
847 #   define safechown	FALSE
848 #  endif
849 # endif
850 #endif
851 	extern bool chownsafe();
852 
853 	if (tTd(27, 2))
854 		printf("include(%s)\n", fname);
855 	if (tTd(27, 4))
856 		printf("   ruid=%d euid=%d\n", getuid(), geteuid());
857 	if (tTd(27, 14))
858 	{
859 		printf("ctladdr ");
860 		printaddr(ctladdr, FALSE);
861 	}
862 
863 	if (tTd(27, 9))
864 		printf("include: old uid = %d/%d\n", getuid(), geteuid());
865 
866 	if (forwarding)
867 		sfflags |= SFF_MUSTOWN|SFF_ROOTOK|SFF_NOSLINK;
868 
869 	ca = getctladdr(ctladdr);
870 	if (ca == NULL)
871 	{
872 		uid = DefUid;
873 		gid = DefGid;
874 		uname = DefUser;
875 	}
876 	else
877 	{
878 		uid = ca->q_uid;
879 		gid = ca->q_gid;
880 		uname = ca->q_user;
881 	}
882 #ifdef HASSETREUID
883 	saveduid = geteuid();
884 	savedgid = getegid();
885 	if (saveduid == 0)
886 	{
887 		initgroups(uname, gid);
888 		if (uid != 0)
889 		{
890 			if (setreuid(0, uid) < 0)
891 				syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
892 					uid, getuid(), geteuid());
893 			else
894 				sfflags |= SFF_NOPATHCHECK;
895 		}
896 	}
897 #endif
898 
899 	if (tTd(27, 9))
900 		printf("include: new uid = %d/%d\n", getuid(), geteuid());
901 
902 	/*
903 	**  If home directory is remote mounted but server is down,
904 	**  this can hang or give errors; use a timeout to avoid this
905 	*/
906 
907 	if (setjmp(CtxIncludeTimeout) != 0)
908 	{
909 		ctladdr->q_flags |= QQUEUEUP;
910 		errno = 0;
911 
912 		/* return pseudo-error code */
913 		rval = EOPENTIMEOUT;
914 		goto resetuid;
915 	}
916 	if (TimeOuts.to_fileopen > 0)
917 		ev = setevent(TimeOuts.to_fileopen, includetimeout, 0);
918 	else
919 		ev = NULL;
920 
921 	/* the input file must be marked safe */
922 	rval = safefile(fname, uid, gid, uname, sfflags, S_IREAD, NULL);
923 	if (rval != 0)
924 	{
925 		/* don't use this :include: file */
926 		if (tTd(27, 4))
927 			printf("include: not safe (uid=%d): %s\n",
928 				uid, errstring(rval));
929 	}
930 	else
931 	{
932 		fp = fopen(fname, "r");
933 		if (fp == NULL)
934 		{
935 			rval = errno;
936 			if (tTd(27, 4))
937 				printf("include: open: %s\n", errstring(rval));
938 		}
939 	}
940 	if (ev != NULL)
941 		clrevent(ev);
942 
943 resetuid:
944 
945 #ifdef HASSETREUID
946 	if (saveduid == 0)
947 	{
948 		if (uid != 0)
949 		{
950 			if (setreuid(-1, 0) < 0)
951 				syserr("setreuid(-1, 0) failure (real=%d, eff=%d)",
952 					getuid(), geteuid());
953 			if (setreuid(RealUid, 0) < 0)
954 				syserr("setreuid(%d, 0) failure (real=%d, eff=%d)",
955 					RealUid, getuid(), geteuid());
956 		}
957 		setgid(savedgid);
958 	}
959 #endif
960 
961 	if (tTd(27, 9))
962 		printf("include: reset uid = %d/%d\n", getuid(), geteuid());
963 
964 	if (rval == EOPENTIMEOUT)
965 		usrerr("451 open timeout on %s", fname);
966 
967 	if (fp == NULL)
968 		return rval;
969 
970 	if (fstat(fileno(fp), &st) < 0)
971 	{
972 		rval = errno;
973 		syserr("Cannot fstat %s!", fname);
974 		return rval;
975 	}
976 
977 #ifndef safechown
978 	safechown = chownsafe(fileno(fp));
979 #endif
980 	if (ca == NULL && safechown)
981 	{
982 		ctladdr->q_uid = st.st_uid;
983 		ctladdr->q_gid = st.st_gid;
984 		ctladdr->q_flags |= QGOODUID;
985 	}
986 	if (ca != NULL && ca->q_uid == st.st_uid)
987 	{
988 		/* optimization -- avoid getpwuid if we already have info */
989 		ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL;
990 		ctladdr->q_ruser = ca->q_ruser;
991 	}
992 	else
993 	{
994 		register struct passwd *pw;
995 
996 		pw = sm_getpwuid(st.st_uid);
997 		if (pw == NULL)
998 			ctladdr->q_flags |= QBOGUSSHELL;
999 		else
1000 		{
1001 			char *sh;
1002 
1003 			ctladdr->q_ruser = newstr(pw->pw_name);
1004 			if (safechown)
1005 				sh = pw->pw_shell;
1006 			else
1007 				sh = "/SENDMAIL/ANY/SHELL/";
1008 			if (!usershellok(sh))
1009 			{
1010 				if (safechown)
1011 					ctladdr->q_flags |= QBOGUSSHELL;
1012 				else
1013 					ctladdr->q_flags |= QUNSAFEADDR;
1014 			}
1015 		}
1016 	}
1017 
1018 	if (bitset(EF_VRFYONLY, e->e_flags))
1019 	{
1020 		/* don't do any more now */
1021 		ctladdr->q_flags |= QVERIFIED;
1022 		e->e_nrcpts++;
1023 		xfclose(fp, "include", fname);
1024 		return rval;
1025 	}
1026 
1027 	/*
1028 	** Check to see if some bad guy can write this file
1029 	**
1030 	**	This should really do something clever with group
1031 	**	permissions; currently we just view world writable
1032 	**	as unsafe.  Also, we don't check for writable
1033 	**	directories in the path.  We've got to leave
1034 	**	something for the local sysad to do.
1035 	*/
1036 
1037 	if (bitset(S_IWOTH, st.st_mode))
1038 		ctladdr->q_flags |= QUNSAFEADDR;
1039 
1040 	/* read the file -- each line is a comma-separated list. */
1041 	FileName = fname;
1042 	LineNumber = 0;
1043 	ctladdr->q_flags &= ~QSELFREF;
1044 	nincludes = 0;
1045 	while (fgets(buf, sizeof buf, fp) != NULL)
1046 	{
1047 		register char *p = strchr(buf, '\n');
1048 
1049 		LineNumber++;
1050 		if (p != NULL)
1051 			*p = '\0';
1052 		if (buf[0] == '#' || buf[0] == '\0')
1053 			continue;
1054 
1055 		/* <sp>#@# introduces a comment anywhere */
1056 		/* for Japanese character sets */
1057 		for (p = buf; (p = strchr(++p, '#')) != NULL; )
1058 		{
1059 			if (p[1] == '@' && p[2] == '#' &&
1060 			    isascii(p[-1]) && isspace(p[-1]) &&
1061 			    isascii(p[3]) && isspace(p[3]))
1062 			{
1063 				p[-1] = '\0';
1064 				break;
1065 			}
1066 		}
1067 		if (buf[0] == '\0')
1068 			continue;
1069 
1070 		e->e_to = NULL;
1071 		message("%s to %s",
1072 			forwarding ? "forwarding" : "sending", buf);
1073 #ifdef LOG
1074 		if (forwarding && LogLevel > 9)
1075 			syslog(LOG_INFO, "%s: forward %s => %s",
1076 				e->e_id == NULL ? "NOQUEUE" : e->e_id,
1077 				oldto, buf);
1078 #endif
1079 
1080 		nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1081 	}
1082 
1083 	if (ferror(fp) && tTd(27, 3))
1084 		printf("include: read error: %s\n", errstring(errno));
1085 	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1086 	{
1087 		if (tTd(27, 5))
1088 		{
1089 			printf("include: QDONTSEND ");
1090 			printaddr(ctladdr, FALSE);
1091 		}
1092 		ctladdr->q_flags |= QDONTSEND;
1093 	}
1094 
1095 	(void) xfclose(fp, "include", fname);
1096 	FileName = oldfilename;
1097 	LineNumber = oldlinenumber;
1098 	e->e_to = oldto;
1099 	return rval;
1100 }
1101 
1102 static void
1103 includetimeout()
1104 {
1105 	longjmp(CtxIncludeTimeout, 1);
1106 }
1107 /*
1108 **  SENDTOARGV -- send to an argument vector.
1109 **
1110 **	Parameters:
1111 **		argv -- argument vector to send to.
1112 **		e -- the current envelope.
1113 **
1114 **	Returns:
1115 **		none.
1116 **
1117 **	Side Effects:
1118 **		puts all addresses on the argument vector onto the
1119 **			send queue.
1120 */
1121 
1122 sendtoargv(argv, e)
1123 	register char **argv;
1124 	register ENVELOPE *e;
1125 {
1126 	register char *p;
1127 
1128 	while ((p = *argv++) != NULL)
1129 	{
1130 		(void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1131 	}
1132 }
1133 /*
1134 **  GETCTLADDR -- get controlling address from an address header.
1135 **
1136 **	If none, get one corresponding to the effective userid.
1137 **
1138 **	Parameters:
1139 **		a -- the address to find the controller of.
1140 **
1141 **	Returns:
1142 **		the controlling address.
1143 **
1144 **	Side Effects:
1145 **		none.
1146 */
1147 
1148 ADDRESS *
1149 getctladdr(a)
1150 	register ADDRESS *a;
1151 {
1152 	while (a != NULL && !bitset(QGOODUID, a->q_flags))
1153 		a = a->q_alias;
1154 	return (a);
1155 }
1156 /*
1157 **  SELF_REFERENCE -- check to see if an address references itself
1158 **
1159 **	The check is done through a chain of aliases.  If it is part of
1160 **	a loop, break the loop at the "best" address, that is, the one
1161 **	that exists as a real user.
1162 **
1163 **	This is to handle the case of:
1164 **		Andrew.Chang:	awc
1165 **		awc:		Andrew.Chang@mail.server.
1166 **	which is a problem only on mail.server.
1167 **
1168 **	Parameters:
1169 **		a -- the address to check.
1170 **		e -- the current envelope.
1171 **
1172 **	Returns:
1173 **		The address that should be retained.
1174 */
1175 
1176 ADDRESS *
1177 self_reference(a, e)
1178 	ADDRESS *a;
1179 	ENVELOPE *e;
1180 {
1181 	ADDRESS *b;		/* top entry in self ref loop */
1182 	ADDRESS *c;		/* entry that point to a real mail box */
1183 
1184 	if (tTd(27, 1))
1185 		printf("self_reference(%s)\n", a->q_paddr);
1186 
1187 	for (b = a->q_alias; b != NULL; b = b->q_alias)
1188 	{
1189 		if (sameaddr(a, b))
1190 			break;
1191 	}
1192 
1193 	if (b == NULL)
1194 	{
1195 		if (tTd(27, 1))
1196 			printf("\t... no self ref\n");
1197 		return NULL;
1198 	}
1199 
1200 	/*
1201 	**  Pick the first address that resolved to a real mail box
1202 	**  i.e has a pw entry.  The returned value will be marked
1203 	**  QSELFREF in recipient(), which in turn will disable alias()
1204 	**  from marking it QDONTSEND, which mean it will be used
1205 	**  as a deliverable address.
1206 	**
1207 	**  The 2 key thing to note here are:
1208 	**	1) we are in a recursive call sequence:
1209 	**		alias->sentolist->recipient->alias
1210 	**	2) normally, when we return back to alias(), the address
1211 	**	   will be marked QDONTSEND, since alias() assumes the
1212 	**	   expanded form will be used instead of the current address.
1213 	**	   This behaviour is turned off if the address is marked
1214 	**	   QSELFREF We set QSELFREF when we return to recipient().
1215 	*/
1216 
1217 	c = a;
1218 	while (c != NULL)
1219 	{
1220 		if (bitnset(M_HASPWENT, c->q_mailer->m_flags))
1221 		{
1222 			if (tTd(27, 2))
1223 				printf("\t... getpwnam(%s)... ", c->q_user);
1224 			if (sm_getpwnam(c->q_user) != NULL)
1225 			{
1226 				if (tTd(27, 2))
1227 					printf("found\n");
1228 
1229 				/* ought to cache results here */
1230 				return c;
1231 			}
1232 			if (tTd(27, 2))
1233 				printf("failed\n");
1234 		}
1235 		c = c->q_alias;
1236 	}
1237 
1238 	if (tTd(27, 1))
1239 		printf("\t... cannot break loop for \"%s\"\n", a->q_paddr);
1240 
1241 	return NULL;
1242 }
1243