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