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