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