1 /*
2  * Copyright (c) 1983, 1995 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.79 (Berkeley) 04/21/95";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 
15 /*
16 **  SENDTOLIST -- Designate a send list.
17 **
18 **	The parameter is a comma-separated list of people to send to.
19 **	This routine arranges to send to all of them.
20 **
21 **	Parameters:
22 **		list -- the send list.
23 **		ctladdr -- the address template for the person to
24 **			send to -- effective uid/gid are important.
25 **			This is typically the alias that caused this
26 **			expansion.
27 **		sendq -- a pointer to the head of a queue to put
28 **			these people into.
29 **		aliaslevel -- the current alias nesting depth -- to
30 **			diagnose loops.
31 **		e -- the envelope in which to add these recipients.
32 **
33 **	Returns:
34 **		The number of addresses actually on the list.
35 **
36 **	Side Effects:
37 **		none.
38 */
39 
40 #define MAXRCRSN	10	/* maximum levels of alias recursion */
41 
42 /* q_flags bits inherited from ctladdr */
43 #define QINHERITEDBITS	(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY)
44 
45 int
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 	int i;
59 	char *oldto = e->e_to;
60 	char *bufp;
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 	/* make sure we have enough space to copy the string */
89 	i = strlen(list) + 1;
90 	if (i <= sizeof buf)
91 		bufp = buf;
92 	else
93 		bufp = xalloc(i);
94 	strcpy(bufp, denlstring(list, FALSE, TRUE));
95 
96 	for (p = bufp; *p != '\0'; )
97 	{
98 		auto char *delimptr;
99 		register ADDRESS *a;
100 
101 		/* parse the address */
102 		while ((isascii(*p) && isspace(*p)) || *p == ',')
103 			p++;
104 		a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter, &delimptr, e);
105 		p = delimptr;
106 		if (a == NULL)
107 			continue;
108 		a->q_next = al;
109 		a->q_alias = ctladdr;
110 
111 		/* arrange to inherit attributes from parent */
112 		if (ctladdr != NULL)
113 		{
114 			/* self reference test */
115 			if (sameaddr(ctladdr, a))
116 				ctladdr->q_flags |= QSELFREF;
117 
118 			/* full name */
119 			if (a->q_fullname == NULL)
120 				a->q_fullname = ctladdr->q_fullname;
121 
122 			/* various flag bits */
123 			a->q_flags &= ~QINHERITEDBITS;
124 			a->q_flags |= ctladdr->q_flags & QINHERITEDBITS;
125 
126 			/* original recipient information */
127 			a->q_orcpt = ctladdr->q_orcpt;
128 		}
129 
130 		al = a;
131 		firstone = FALSE;
132 	}
133 
134 	/* arrange to send to everyone on the local send list */
135 	while (al != NULL)
136 	{
137 		register ADDRESS *a = al;
138 
139 		al = a->q_next;
140 		a = recipient(a, sendq, aliaslevel, e);
141 		naddrs++;
142 	}
143 
144 	e->e_to = oldto;
145 	if (bufp != buf)
146 		free(bufp);
147 	return (naddrs);
148 }
149 /*
150 **  RECIPIENT -- Designate a message recipient
151 **
152 **	Saves the named person for future mailing.
153 **
154 **	Parameters:
155 **		a -- the (preparsed) address header for the recipient.
156 **		sendq -- a pointer to the head of a queue to put the
157 **			recipient in.  Duplicate supression is done
158 **			in this queue.
159 **		aliaslevel -- the current alias nesting depth.
160 **		e -- the current envelope.
161 **
162 **	Returns:
163 **		The actual address in the queue.  This will be "a" if
164 **		the address is not a duplicate, else the original address.
165 **
166 **	Side Effects:
167 **		none.
168 */
169 
170 ADDRESS *
171 recipient(a, sendq, aliaslevel, e)
172 	register ADDRESS *a;
173 	register ADDRESS **sendq;
174 	int aliaslevel;
175 	register ENVELOPE *e;
176 {
177 	register ADDRESS *q;
178 	ADDRESS **pq;
179 	register struct mailer *m;
180 	register char *p;
181 	bool quoted = FALSE;		/* set if the addr has a quote bit */
182 	int findusercount = 0;
183 	bool initialdontsend = bitset(QDONTSEND, a->q_flags);
184 	int i;
185 	char *buf;
186 	char buf0[MAXNAME + 1];		/* unquoted image of the user name */
187 	extern int safefile();
188 
189 	e->e_to = a->q_paddr;
190 	m = a->q_mailer;
191 	errno = 0;
192 	if (aliaslevel == 0)
193 		a->q_flags |= QPRIMARY;
194 	if (tTd(26, 1))
195 	{
196 		printf("\nrecipient (%d): ", aliaslevel);
197 		printaddr(a, FALSE);
198 	}
199 
200 	/* if this is primary, add it to the original recipient list */
201 	if (a->q_alias == NULL)
202 	{
203 		if (e->e_origrcpt == NULL)
204 			e->e_origrcpt = a->q_paddr;
205 		else if (e->e_origrcpt != a->q_paddr)
206 			e->e_origrcpt = "";
207 	}
208 
209 	/* break aliasing loops */
210 	if (aliaslevel > MAXRCRSN)
211 	{
212 		usrerr("554 aliasing/forwarding loop broken (%d aliases deep; %d max",
213 			aliaslevel, MAXRCRSN);
214 		return (a);
215 	}
216 
217 	/*
218 	**  Finish setting up address structure.
219 	*/
220 
221 	/* get unquoted user for file, program or user.name check */
222 	i = strlen(a->q_user);
223 	if (i >= sizeof buf0)
224 		buf = xalloc(i + 1);
225 	else
226 		buf = buf0;
227 	(void) strcpy(buf, a->q_user);
228 	for (p = buf; *p != '\0' && !quoted; p++)
229 	{
230 		if (*p == '\\')
231 			quoted = TRUE;
232 	}
233 	stripquotes(buf);
234 
235 	/* check for direct mailing to restricted mailers */
236 	if (m == ProgMailer)
237 	{
238 		if (a->q_alias == NULL)
239 		{
240 			a->q_flags |= QBADADDR;
241 			usrerr("550 Cannot mail directly to programs");
242 		}
243 		else if (bitset(QBOGUSSHELL, a->q_alias->q_flags))
244 		{
245 			a->q_flags |= QBADADDR;
246 			usrerr("550 User %s@%s doesn't have a valid shell for mailing to programs",
247 				a->q_alias->q_ruser, MyHostName);
248 		}
249 		else if (bitset(QUNSAFEADDR, a->q_alias->q_flags))
250 		{
251 			a->q_flags |= QBADADDR;
252 			usrerr("550 Address %s is unsafe for mailing to programs",
253 				a->q_alias->q_paddr);
254 		}
255 	}
256 
257 	/*
258 	**  Look up this person in the recipient list.
259 	**	If they are there already, return, otherwise continue.
260 	**	If the list is empty, just add it.  Notice the cute
261 	**	hack to make from addresses suppress things correctly:
262 	**	the QDONTSEND bit will be set in the send list.
263 	**	[Please note: the emphasis is on "hack."]
264 	*/
265 
266 	for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
267 	{
268 		if (sameaddr(q, a))
269 		{
270 			if (tTd(26, 1))
271 			{
272 				printf("%s in sendq: ", a->q_paddr);
273 				printaddr(q, FALSE);
274 			}
275 			if (!bitset(QPRIMARY, q->q_flags))
276 			{
277 				if (!bitset(QDONTSEND, a->q_flags))
278 					message("duplicate suppressed");
279 				q->q_flags |= a->q_flags;
280 			}
281 			else if (bitset(QSELFREF, q->q_flags))
282 				q->q_flags |= a->q_flags & ~QDONTSEND;
283 			a = q;
284 			goto done;
285 		}
286 	}
287 
288 	/* add address on list */
289 	*pq = a;
290 	a->q_next = NULL;
291 
292 	/*
293 	**  Alias the name and handle special mailer types.
294 	*/
295 
296   trylocaluser:
297 	if (tTd(29, 7))
298 		printf("at trylocaluser %s\n", a->q_user);
299 
300 	if (bitset(QDONTSEND|QBADADDR|QVERIFIED, a->q_flags))
301 		goto testselfdestruct;
302 
303 	if (m == InclMailer)
304 	{
305 		a->q_flags |= QDONTSEND;
306 		if (a->q_alias == NULL)
307 		{
308 			a->q_flags |= QBADADDR;
309 			usrerr("550 Cannot mail directly to :include:s");
310 		}
311 		else
312 		{
313 			int ret;
314 
315 			message("including file %s", a->q_user);
316 			ret = include(a->q_user, FALSE, a, sendq, aliaslevel, e);
317 			if (transienterror(ret))
318 			{
319 #ifdef LOG
320 				if (LogLevel > 2)
321 					syslog(LOG_ERR, "%s: include %s: transient error: %s",
322 						e->e_id == NULL ? "NOQUEUE" : e->e_id,
323 						a->q_user, errstring(ret));
324 #endif
325 				a->q_flags |= QQUEUEUP;
326 				a->q_flags &= ~QDONTSEND;
327 				usrerr("451 Cannot open %s: %s",
328 					a->q_user, errstring(ret));
329 			}
330 			else if (ret != 0)
331 			{
332 				a->q_flags |= QBADADDR;
333 				usrerr("550 Cannot open %s: %s",
334 					a->q_user, errstring(ret));
335 			}
336 		}
337 	}
338 	else if (m == FileMailer)
339 	{
340 		extern bool writable();
341 
342 		/* check if writable or creatable */
343 		if (a->q_alias == NULL)
344 		{
345 			a->q_flags |= QBADADDR;
346 			usrerr("550 Cannot mail directly to files");
347 		}
348 		else if (bitset(QBOGUSSHELL, a->q_alias->q_flags))
349 		{
350 			a->q_flags |= QBADADDR;
351 			usrerr("550 User %s@%s doesn't have a valid shell for mailing to files",
352 				a->q_alias->q_ruser, MyHostName);
353 		}
354 		else if (bitset(QUNSAFEADDR, a->q_alias->q_flags))
355 		{
356 			a->q_flags |= QBADADDR;
357 			usrerr("550 Address %s is unsafe for mailing to files",
358 				a->q_alias->q_paddr);
359 		}
360 		else if (!writable(buf, getctladdr(a), SFF_CREAT))
361 		{
362 			a->q_flags |= QBADADDR;
363 			giveresponse(EX_CANTCREAT, m, NULL, a->q_alias,
364 				     (time_t) 0, e);
365 		}
366 	}
367 
368 	/* try aliasing */
369 	if (!bitset(QDONTSEND, a->q_flags) && bitnset(M_ALIASABLE, m->m_flags))
370 		alias(a, sendq, aliaslevel, e);
371 
372 # ifdef USERDB
373 	/* if not aliased, look it up in the user database */
374 	if (!bitset(QDONTSEND|QNOTREMOTE|QVERIFIED, a->q_flags) &&
375 	    bitnset(M_CHECKUDB, m->m_flags))
376 	{
377 		extern int udbexpand();
378 
379 		if (udbexpand(a, sendq, aliaslevel, e) == EX_TEMPFAIL)
380 		{
381 			a->q_flags |= QQUEUEUP;
382 			if (e->e_message == NULL)
383 				e->e_message = newstr("Deferred: user database error");
384 # ifdef LOG
385 			if (LogLevel > 8)
386 				syslog(LOG_INFO, "%s: deferred: udbexpand: %s",
387 					e->e_id == NULL ? "NOQUEUE" : e->e_id,
388 					errstring(errno));
389 # endif
390 			message("queued (user database error): %s",
391 				errstring(errno));
392 			e->e_nrcpts++;
393 			goto testselfdestruct;
394 		}
395 	}
396 # endif
397 
398 	/*
399 	**  If we have a level two config file, then pass the name through
400 	**  Ruleset 5 before sending it off.  Ruleset 5 has the right
401 	**  to send rewrite it to another mailer.  This gives us a hook
402 	**  after local aliasing has been done.
403 	*/
404 
405 	if (tTd(29, 5))
406 	{
407 		printf("recipient: testing local?  cl=%d, rr5=%x\n\t",
408 			ConfigLevel, RewriteRules[5]);
409 		printaddr(a, FALSE);
410 	}
411 	if (!bitset(QNOTREMOTE|QDONTSEND|QQUEUEUP|QVERIFIED, a->q_flags) &&
412 	    ConfigLevel >= 2 && RewriteRules[5] != NULL &&
413 	    bitnset(M_TRYRULESET5, m->m_flags))
414 	{
415 		maplocaluser(a, sendq, aliaslevel + 1, e);
416 	}
417 
418 	/*
419 	**  If it didn't get rewritten to another mailer, go ahead
420 	**  and deliver it.
421 	*/
422 
423 	if (!bitset(QDONTSEND|QQUEUEUP|QVERIFIED, a->q_flags) &&
424 	    bitnset(M_HASPWENT, m->m_flags))
425 	{
426 		auto bool fuzzy;
427 		register struct passwd *pw;
428 		extern struct passwd *finduser();
429 
430 		/* warning -- finduser may trash buf */
431 		pw = finduser(buf, &fuzzy);
432 		if (pw == NULL)
433 		{
434 			a->q_flags |= QBADADDR;
435 			giveresponse(EX_NOUSER, m, NULL, a->q_alias,
436 				     (time_t) 0, e);
437 		}
438 		else
439 		{
440 			char nbuf[MAXNAME + 1];
441 
442 			if (fuzzy)
443 			{
444 				/* name was a fuzzy match */
445 				a->q_user = newstr(pw->pw_name);
446 				if (findusercount++ > 3)
447 				{
448 					a->q_flags |= QBADADDR;
449 					usrerr("554 aliasing/forwarding loop for %s broken",
450 						pw->pw_name);
451 					goto done;
452 				}
453 
454 				/* see if it aliases */
455 				(void) strcpy(buf, pw->pw_name);
456 				goto trylocaluser;
457 			}
458 			if (strcmp(pw->pw_dir, "/") == 0)
459 				a->q_home = "";
460 			else
461 				a->q_home = newstr(pw->pw_dir);
462 			a->q_uid = pw->pw_uid;
463 			a->q_gid = pw->pw_gid;
464 			a->q_ruser = newstr(pw->pw_name);
465 			a->q_flags |= QGOODUID;
466 			buildfname(pw->pw_gecos, pw->pw_name, nbuf);
467 			if (nbuf[0] != '\0')
468 				a->q_fullname = newstr(nbuf);
469 			if (pw->pw_shell != NULL && pw->pw_shell[0] != '\0' &&
470 			    !usershellok(pw->pw_shell))
471 			{
472 				a->q_flags |= QBOGUSSHELL;
473 			}
474 			if (!quoted)
475 				forward(a, sendq, aliaslevel, e);
476 		}
477 	}
478 	if (!bitset(QDONTSEND, a->q_flags))
479 		e->e_nrcpts++;
480 
481   testselfdestruct:
482 	a->q_flags |= QTHISPASS;
483 	if (tTd(26, 8))
484 	{
485 		printf("testselfdestruct: ");
486 		printaddr(a, FALSE);
487 		if (tTd(26, 10))
488 		{
489 			printf("SENDQ:\n");
490 			printaddr(*sendq, TRUE);
491 			printf("----\n");
492 		}
493 	}
494 	if (a->q_alias == NULL && a != &e->e_from &&
495 	    bitset(QDONTSEND, a->q_flags))
496 	{
497 		for (q = *sendq; q != NULL; q = q->q_next)
498 		{
499 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags) &&
500 			    bitset(QTHISPASS, q->q_flags))
501 				break;
502 		}
503 		if (q == NULL)
504 		{
505 			a->q_flags |= QBADADDR;
506 			usrerr("554 aliasing/forwarding loop broken");
507 		}
508 	}
509 
510   done:
511 	a->q_flags |= QTHISPASS;
512 	if (buf != buf0)
513 		free(buf);
514 
515 	/*
516 	**  If we are at the top level, check to see if this has
517 	**  expanded to exactly one address.  If so, it can inherit
518 	**  the primaryness of the address.
519 	**
520 	**  While we're at it, clear the QTHISPASS bits.
521 	*/
522 
523 	if (aliaslevel == 0)
524 	{
525 		int nrcpts = 0;
526 		ADDRESS *only;
527 
528 		for (q = *sendq; q != NULL; q = q->q_next)
529 		{
530 			if (bitset(QTHISPASS, q->q_flags) &&
531 			    !bitset(QDONTSEND|QBADADDR, q->q_flags))
532 			{
533 				nrcpts++;
534 				only = q;
535 			}
536 			q->q_flags &= ~QTHISPASS;
537 		}
538 		if (nrcpts == 1)
539 			only->q_flags |= QPRIMARY;
540 		else if (!initialdontsend)
541 		{
542 			/* arrange for return receipt */
543 			e->e_flags |= EF_SENDRECEIPT;
544 			a->q_flags |= QEXPLODED;
545 			if (e->e_xfp != NULL)
546 				fprintf(e->e_xfp,
547 					"%s... expanded to multiple addresses\n",
548 					a->q_paddr);
549 		}
550 	}
551 
552 	return (a);
553 }
554 /*
555 **  FINDUSER -- find the password entry for a user.
556 **
557 **	This looks a lot like getpwnam, except that it may want to
558 **	do some fancier pattern matching in /etc/passwd.
559 **
560 **	This routine contains most of the time of many sendmail runs.
561 **	It deserves to be optimized.
562 **
563 **	Parameters:
564 **		name -- the name to match against.
565 **		fuzzyp -- an outarg that is set to TRUE if this entry
566 **			was found using the fuzzy matching algorithm;
567 **			set to FALSE otherwise.
568 **
569 **	Returns:
570 **		A pointer to a pw struct.
571 **		NULL if name is unknown or ambiguous.
572 **
573 **	Side Effects:
574 **		may modify name.
575 */
576 
577 struct passwd *
578 finduser(name, fuzzyp)
579 	char *name;
580 	bool *fuzzyp;
581 {
582 	register struct passwd *pw;
583 	register char *p;
584 
585 	if (tTd(29, 4))
586 		printf("finduser(%s): ", name);
587 
588 	*fuzzyp = FALSE;
589 
590 #ifdef HESIOD
591 	/* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */
592 	for (p = name; *p != '\0'; p++)
593 		if (!isascii(*p) || !isdigit(*p))
594 			break;
595 	if (*p == '\0')
596 	{
597 		if (tTd(29, 4))
598 			printf("failed (numeric input)\n");
599 		return NULL;
600 	}
601 #endif
602 
603 	/* look up this login name using fast path */
604 	if ((pw = sm_getpwnam(name)) != NULL)
605 	{
606 		if (tTd(29, 4))
607 			printf("found (non-fuzzy)\n");
608 		return (pw);
609 	}
610 
611 #ifdef MATCHGECOS
612 	/* see if fuzzy matching allowed */
613 	if (!MatchGecos)
614 	{
615 		if (tTd(29, 4))
616 			printf("not found (fuzzy disabled)\n");
617 		return NULL;
618 	}
619 
620 	/* search for a matching full name instead */
621 	for (p = name; *p != '\0'; p++)
622 	{
623 		if (*p == (SpaceSub & 0177) || *p == '_')
624 			*p = ' ';
625 	}
626 	(void) setpwent();
627 	while ((pw = getpwent()) != NULL)
628 	{
629 		char buf[MAXNAME + 1];
630 
631 		buildfname(pw->pw_gecos, pw->pw_name, buf);
632 		if (strchr(buf, ' ') != NULL && !strcasecmp(buf, name))
633 		{
634 			if (tTd(29, 4))
635 				printf("fuzzy matches %s\n", pw->pw_name);
636 			message("sending to login name %s", pw->pw_name);
637 			*fuzzyp = TRUE;
638 			return (pw);
639 		}
640 	}
641 	if (tTd(29, 4))
642 		printf("no fuzzy match found\n");
643 #else
644 	if (tTd(29, 4))
645 		printf("not found (fuzzy disabled)\n");
646 #endif
647 	return (NULL);
648 }
649 /*
650 **  WRITABLE -- predicate returning if the file is writable.
651 **
652 **	This routine must duplicate the algorithm in sys/fio.c.
653 **	Unfortunately, we cannot use the access call since we
654 **	won't necessarily be the real uid when we try to
655 **	actually open the file.
656 **
657 **	Notice that ANY file with ANY execute bit is automatically
658 **	not writable.  This is also enforced by mailfile.
659 **
660 **	Parameters:
661 **		filename -- the file name to check.
662 **		ctladdr -- the controlling address for this file.
663 **		flags -- SFF_* flags to control the function.
664 **
665 **	Returns:
666 **		TRUE -- if we will be able to write this file.
667 **		FALSE -- if we cannot write this file.
668 **
669 **	Side Effects:
670 **		none.
671 */
672 
673 bool
674 writable(filename, ctladdr, flags)
675 	char *filename;
676 	ADDRESS *ctladdr;
677 	int flags;
678 {
679 	uid_t euid;
680 	gid_t egid;
681 	int bits;
682 	register char *p;
683 	char *uname;
684 
685 	if (tTd(29, 5))
686 		printf("writable(%s, 0x%x)\n", filename, flags);
687 
688 #ifdef SUID_ROOT_FILES_OK
689 	/* really ought to be passed down -- and not a good idea */
690 	flags |= SFF_ROOTOK;
691 #endif
692 
693 	/*
694 	**  File does exist -- check that it is writable.
695 	*/
696 
697 	if (ctladdr != NULL && geteuid() == 0)
698 	{
699 		euid = ctladdr->q_uid;
700 		egid = ctladdr->q_gid;
701 		uname = ctladdr->q_user;
702 	}
703 	else if (bitset(SFF_RUNASREALUID, flags))
704 	{
705 		extern char RealUserName[];
706 
707 		euid = RealUid;
708 		egid = RealGid;
709 		uname = RealUserName;
710 	}
711 	else if (FileMailer != NULL)
712 	{
713 		euid = FileMailer->m_uid;
714 		egid = FileMailer->m_gid;
715 	}
716 	else
717 	{
718 		euid = egid = 0;
719 	}
720 	if (euid == 0)
721 	{
722 		euid = DefUid;
723 		uname = DefUser;
724 	}
725 	if (egid == 0)
726 		egid = DefGid;
727 	if (geteuid() == 0)
728 		flags |= SFF_SETUIDOK;
729 
730 	errno = safefile(filename, euid, egid, uname, flags, S_IWRITE, NULL);
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 void	includetimeout();
771 
772 int
773 include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
774 	char *fname;
775 	bool forwarding;
776 	ADDRESS *ctladdr;
777 	ADDRESS **sendq;
778 	int aliaslevel;
779 	ENVELOPE *e;
780 {
781 	FILE *fp = NULL;
782 	char *oldto = e->e_to;
783 	char *oldfilename = FileName;
784 	int oldlinenumber = LineNumber;
785 	register EVENT *ev = NULL;
786 	int nincludes;
787 	register ADDRESS *ca;
788 	uid_t saveduid, uid;
789 	gid_t savedgid, gid;
790 	char *uname;
791 	int rval = 0;
792 	int sfflags = SFF_REGONLY;
793 	struct stat st;
794 	char buf[MAXLINE];
795 #ifdef _POSIX_CHOWN_RESTRICTED
796 # if _POSIX_CHOWN_RESTRICTED == -1
797 #  define safechown	FALSE
798 # else
799 #  define safechown	TRUE
800 # endif
801 #else
802 # ifdef _PC_CHOWN_RESTRICTED
803 	bool safechown;
804 # else
805 #  ifdef BSD
806 #   define safechown	TRUE
807 #  else
808 #   define safechown	FALSE
809 #  endif
810 # endif
811 #endif
812 	extern bool chownsafe();
813 
814 	if (tTd(27, 2))
815 		printf("include(%s)\n", fname);
816 	if (tTd(27, 4))
817 		printf("   ruid=%d euid=%d\n", getuid(), geteuid());
818 	if (tTd(27, 14))
819 	{
820 		printf("ctladdr ");
821 		printaddr(ctladdr, FALSE);
822 	}
823 
824 	if (tTd(27, 9))
825 		printf("include: old uid = %d/%d\n", getuid(), geteuid());
826 
827 	if (forwarding)
828 		sfflags |= SFF_MUSTOWN;
829 
830 	ca = getctladdr(ctladdr);
831 	if (ca == NULL)
832 	{
833 		uid = DefUid;
834 		gid = DefGid;
835 		uname = DefUser;
836 	}
837 	else
838 	{
839 		uid = ca->q_uid;
840 		gid = ca->q_gid;
841 		uname = ca->q_user;
842 	}
843 #ifdef HASSETREUID
844 	saveduid = geteuid();
845 	savedgid = getegid();
846 	if (saveduid == 0)
847 	{
848 		initgroups(uname, gid);
849 		if (uid != 0)
850 		{
851 			if (setreuid(0, uid) < 0)
852 				syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
853 					uid, getuid(), geteuid());
854 			else
855 				sfflags |= SFF_NOPATHCHECK;
856 		}
857 	}
858 #endif
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, NULL);
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 = sm_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 
1016 		/* <sp>#@# introduces a comment anywhere */
1017 		/* for Japanese character sets */
1018 		for (p = buf; (p = strchr(++p, '#')) != NULL; )
1019 		{
1020 			if (p[1] == '@' && p[2] == '#' &&
1021 			    isascii(p[-1]) && isspace(p[-1]) &&
1022 			    isascii(p[3]) && isspace(p[3]))
1023 			{
1024 				p[-1] = '\0';
1025 				break;
1026 			}
1027 		}
1028 		if (buf[0] == '\0')
1029 			continue;
1030 
1031 		e->e_to = NULL;
1032 		message("%s to %s",
1033 			forwarding ? "forwarding" : "sending", buf);
1034 #ifdef LOG
1035 		if (forwarding && LogLevel > 9)
1036 			syslog(LOG_INFO, "%s: forward %s => %s",
1037 				e->e_id == NULL ? "NOQUEUE" : e->e_id,
1038 				oldto, buf);
1039 #endif
1040 
1041 		nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1042 	}
1043 
1044 	if (ferror(fp) && tTd(27, 3))
1045 		printf("include: read error: %s\n", errstring(errno));
1046 	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1047 	{
1048 		if (tTd(27, 5))
1049 		{
1050 			printf("include: QDONTSEND ");
1051 			printaddr(ctladdr, FALSE);
1052 		}
1053 		ctladdr->q_flags |= QDONTSEND;
1054 	}
1055 
1056 	(void) xfclose(fp, "include", fname);
1057 	FileName = oldfilename;
1058 	LineNumber = oldlinenumber;
1059 	e->e_to = oldto;
1060 	return rval;
1061 }
1062 
1063 static void
1064 includetimeout()
1065 {
1066 	longjmp(CtxIncludeTimeout, 1);
1067 }
1068 /*
1069 **  SENDTOARGV -- send to an argument vector.
1070 **
1071 **	Parameters:
1072 **		argv -- argument vector to send to.
1073 **		e -- the current envelope.
1074 **
1075 **	Returns:
1076 **		none.
1077 **
1078 **	Side Effects:
1079 **		puts all addresses on the argument vector onto the
1080 **			send queue.
1081 */
1082 
1083 sendtoargv(argv, e)
1084 	register char **argv;
1085 	register ENVELOPE *e;
1086 {
1087 	register char *p;
1088 
1089 	while ((p = *argv++) != NULL)
1090 	{
1091 		(void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1092 	}
1093 }
1094 /*
1095 **  GETCTLADDR -- get controlling address from an address header.
1096 **
1097 **	If none, get one corresponding to the effective userid.
1098 **
1099 **	Parameters:
1100 **		a -- the address to find the controller of.
1101 **
1102 **	Returns:
1103 **		the controlling address.
1104 **
1105 **	Side Effects:
1106 **		none.
1107 */
1108 
1109 ADDRESS *
1110 getctladdr(a)
1111 	register ADDRESS *a;
1112 {
1113 	while (a != NULL && !bitset(QGOODUID, a->q_flags))
1114 		a = a->q_alias;
1115 	return (a);
1116 }
1117