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