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.77 (Berkeley) 04/12/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, %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 #ifdef RUN_AS_REAL_UID
704 	else
705 	{
706 		extern char RealUserName[];
707 
708 		euid = RealUid;
709 		egid = RealGid;
710 		uname = RealUserName;
711 	}
712 #else
713 	else if (FileMailer != NULL)
714 	{
715 		euid = FileMailer->m_uid;
716 		egid = FileMailer->m_gid;
717 	}
718 	else
719 	{
720 		euid = egid = 0;
721 	}
722 #endif
723 	if (euid == 0)
724 	{
725 		euid = DefUid;
726 		uname = DefUser;
727 	}
728 	if (egid == 0)
729 		egid = DefGid;
730 	if (geteuid() == 0)
731 		flags |= SFF_SETUIDOK;
732 
733 	errno = safefile(filename, euid, egid, uname, flags, S_IWRITE, NULL);
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 void	includetimeout();
774 
775 int
776 include(fname, forwarding, ctladdr, sendq, aliaslevel, e)
777 	char *fname;
778 	bool forwarding;
779 	ADDRESS *ctladdr;
780 	ADDRESS **sendq;
781 	int aliaslevel;
782 	ENVELOPE *e;
783 {
784 	FILE *fp = NULL;
785 	char *oldto = e->e_to;
786 	char *oldfilename = FileName;
787 	int oldlinenumber = LineNumber;
788 	register EVENT *ev = NULL;
789 	int nincludes;
790 	register ADDRESS *ca;
791 	uid_t saveduid, uid;
792 	gid_t savedgid, gid;
793 	char *uname;
794 	int rval = 0;
795 	int sfflags = SFF_REGONLY;
796 	struct stat st;
797 	char buf[MAXLINE];
798 #ifdef _POSIX_CHOWN_RESTRICTED
799 # if _POSIX_CHOWN_RESTRICTED == -1
800 #  define safechown	FALSE
801 # else
802 #  define safechown	TRUE
803 # endif
804 #else
805 # ifdef _PC_CHOWN_RESTRICTED
806 	bool safechown;
807 # else
808 #  ifdef BSD
809 #   define safechown	TRUE
810 #  else
811 #   define safechown	FALSE
812 #  endif
813 # endif
814 #endif
815 	extern bool chownsafe();
816 
817 	if (tTd(27, 2))
818 		printf("include(%s)\n", fname);
819 	if (tTd(27, 4))
820 		printf("   ruid=%d euid=%d\n", getuid(), geteuid());
821 	if (tTd(27, 14))
822 	{
823 		printf("ctladdr ");
824 		printaddr(ctladdr, FALSE);
825 	}
826 
827 	if (tTd(27, 9))
828 		printf("include: old uid = %d/%d\n", getuid(), geteuid());
829 
830 	if (forwarding)
831 		sfflags |= SFF_MUSTOWN;
832 
833 	ca = getctladdr(ctladdr);
834 	if (ca == NULL)
835 	{
836 		uid = DefUid;
837 		gid = DefGid;
838 		uname = DefUser;
839 	}
840 	else
841 	{
842 		uid = ca->q_uid;
843 		gid = ca->q_gid;
844 		uname = ca->q_user;
845 	}
846 #ifdef HASSETREUID
847 	saveduid = geteuid();
848 	savedgid = getegid();
849 	if (saveduid == 0)
850 	{
851 		initgroups(uname, gid);
852 		if (uid != 0)
853 		{
854 			if (setreuid(0, uid) < 0)
855 				syserr("setreuid(0, %d) failure (real=%d, eff=%d)",
856 					uid, getuid(), geteuid());
857 			else
858 				sfflags |= SFF_NOPATHCHECK;
859 		}
860 	}
861 #endif
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, NULL);
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 = sm_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 
1019 		/* <sp>#@# introduces a comment anywhere */
1020 		/* for Japanese character sets */
1021 		for (p = buf; (p = strchr(++p, '#')) != NULL; )
1022 		{
1023 			if (p[1] == '@' && p[2] == '#' &&
1024 			    isascii(p[-1]) && isspace(p[-1]) &&
1025 			    isascii(p[3]) && isspace(p[3]))
1026 			{
1027 				p[-1] = '\0';
1028 				break;
1029 			}
1030 		}
1031 		if (buf[0] == '\0')
1032 			continue;
1033 
1034 		e->e_to = NULL;
1035 		message("%s to %s",
1036 			forwarding ? "forwarding" : "sending", buf);
1037 #ifdef LOG
1038 		if (forwarding && LogLevel > 9)
1039 			syslog(LOG_INFO, "%s: forward %s => %s",
1040 				e->e_id == NULL ? "NOQUEUE" : e->e_id,
1041 				oldto, buf);
1042 #endif
1043 
1044 		nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e);
1045 	}
1046 
1047 	if (ferror(fp) && tTd(27, 3))
1048 		printf("include: read error: %s\n", errstring(errno));
1049 	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
1050 	{
1051 		if (tTd(27, 5))
1052 		{
1053 			printf("include: QDONTSEND ");
1054 			printaddr(ctladdr, FALSE);
1055 		}
1056 		ctladdr->q_flags |= QDONTSEND;
1057 	}
1058 
1059 	(void) xfclose(fp, "include", fname);
1060 	FileName = oldfilename;
1061 	LineNumber = oldlinenumber;
1062 	e->e_to = oldto;
1063 	return rval;
1064 }
1065 
1066 static void
1067 includetimeout()
1068 {
1069 	longjmp(CtxIncludeTimeout, 1);
1070 }
1071 /*
1072 **  SENDTOARGV -- send to an argument vector.
1073 **
1074 **	Parameters:
1075 **		argv -- argument vector to send to.
1076 **		e -- the current envelope.
1077 **
1078 **	Returns:
1079 **		none.
1080 **
1081 **	Side Effects:
1082 **		puts all addresses on the argument vector onto the
1083 **			send queue.
1084 */
1085 
1086 sendtoargv(argv, e)
1087 	register char **argv;
1088 	register ENVELOPE *e;
1089 {
1090 	register char *p;
1091 
1092 	while ((p = *argv++) != NULL)
1093 	{
1094 		(void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e);
1095 	}
1096 }
1097 /*
1098 **  GETCTLADDR -- get controlling address from an address header.
1099 **
1100 **	If none, get one corresponding to the effective userid.
1101 **
1102 **	Parameters:
1103 **		a -- the address to find the controller of.
1104 **
1105 **	Returns:
1106 **		the controlling address.
1107 **
1108 **	Side Effects:
1109 **		none.
1110 */
1111 
1112 ADDRESS *
1113 getctladdr(a)
1114 	register ADDRESS *a;
1115 {
1116 	while (a != NULL && !bitset(QGOODUID, a->q_flags))
1117 		a = a->q_alias;
1118 	return (a);
1119 }
1120