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