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