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