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