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.8 (Berkeley) 07/19/93";
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 **		e -- the envelope in which to add these recipients.
31 **
32 **	Returns:
33 **		The number of addresses actually on the list.
34 **
35 **	Side Effects:
36 **		none.
37 */
38 
39 # define MAXRCRSN	10
40 
41 sendtolist(list, ctladdr, sendq, e)
42 	char *list;
43 	ADDRESS *ctladdr;
44 	ADDRESS **sendq;
45 	register ENVELOPE *e;
46 {
47 	register char *p;
48 	register ADDRESS *al;	/* list of addresses to send to */
49 	bool firstone;		/* set on first address sent */
50 	char delimiter;		/* the address delimiter */
51 	int naddrs;
52 	char *oldto = e->e_to;
53 
54 	if (tTd(25, 1))
55 	{
56 		printf("sendto: %s\n   ctladdr=", list);
57 		printaddr(ctladdr, FALSE);
58 	}
59 
60 	/* heuristic to determine old versus new style addresses */
61 	if (ctladdr == NULL &&
62 	    (strchr(list, ',') != NULL || strchr(list, ';') != NULL ||
63 	     strchr(list, '<') != NULL || strchr(list, '(') != NULL))
64 		e->e_flags &= ~EF_OLDSTYLE;
65 	delimiter = ' ';
66 	if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL)
67 		delimiter = ',';
68 
69 	firstone = TRUE;
70 	al = NULL;
71 	naddrs = 0;
72 
73 	for (p = list; *p != '\0'; )
74 	{
75 		auto char *delimptr;
76 		register ADDRESS *a;
77 
78 		/* parse the address */
79 		while ((isascii(*p) && isspace(*p)) || *p == ',')
80 			p++;
81 		a = parseaddr(p, (ADDRESS *) NULL, 1, delimiter, &delimptr, e);
82 		p = delimptr;
83 		if (a == NULL)
84 			continue;
85 		a->q_next = al;
86 		a->q_alias = ctladdr;
87 
88 		/* see if this should be marked as a primary address */
89 		if (ctladdr == NULL ||
90 		    (firstone && *p == '\0' && bitset(QPRIMARY, ctladdr->q_flags)))
91 			a->q_flags |= QPRIMARY;
92 
93 		if (ctladdr != NULL && sameaddr(ctladdr, a))
94 			ctladdr->q_flags |= QSELFREF;
95 		al = a;
96 		firstone = FALSE;
97 	}
98 
99 	/* arrange to send to everyone on the local send list */
100 	while (al != NULL)
101 	{
102 		register ADDRESS *a = al;
103 
104 		al = a->q_next;
105 		a = recipient(a, sendq, e);
106 
107 		/* arrange to inherit full name */
108 		if (a->q_fullname == NULL && ctladdr != NULL)
109 			a->q_fullname = ctladdr->q_fullname;
110 		naddrs++;
111 	}
112 
113 	e->e_to = oldto;
114 	return (naddrs);
115 }
116 /*
117 **  RECIPIENT -- Designate a message recipient
118 **
119 **	Saves the named person for future mailing.
120 **
121 **	Parameters:
122 **		a -- the (preparsed) address header for the recipient.
123 **		sendq -- a pointer to the head of a queue to put the
124 **			recipient in.  Duplicate supression is done
125 **			in this queue.
126 **		e -- the current envelope.
127 **
128 **	Returns:
129 **		The actual address in the queue.  This will be "a" if
130 **		the address is not a duplicate, else the original address.
131 **
132 **	Side Effects:
133 **		none.
134 */
135 
136 ADDRESS *
137 recipient(a, sendq, e)
138 	register ADDRESS *a;
139 	register ADDRESS **sendq;
140 	register ENVELOPE *e;
141 {
142 	register ADDRESS *q;
143 	ADDRESS **pq;
144 	register struct mailer *m;
145 	register char *p;
146 	bool quoted = FALSE;		/* set if the addr has a quote bit */
147 	int findusercount = 0;
148 	char buf[MAXNAME];		/* unquoted image of the user name */
149 	extern int safefile();
150 
151 	e->e_to = a->q_paddr;
152 	m = a->q_mailer;
153 	errno = 0;
154 	if (tTd(26, 1))
155 	{
156 		printf("\nrecipient: ");
157 		printaddr(a, FALSE);
158 	}
159 
160 	/* break aliasing loops */
161 	if (AliasLevel > MAXRCRSN)
162 	{
163 		usrerr("554 aliasing/forwarding loop broken");
164 		return (a);
165 	}
166 
167 	/*
168 	**  Finish setting up address structure.
169 	*/
170 
171 	/* set the queue timeout */
172 	a->q_timeout = TimeOuts.to_q_return;
173 
174 	/* get unquoted user for file, program or user.name check */
175 	(void) strcpy(buf, a->q_user);
176 	for (p = buf; *p != '\0' && !quoted; p++)
177 	{
178 		if (*p == '\\')
179 			quoted = TRUE;
180 	}
181 	stripquotes(buf);
182 
183 	/* check for direct mailing to restricted mailers */
184 	if (a->q_alias == NULL && m == ProgMailer &&
185 	    !bitset(EF_QUEUERUN, e->e_flags))
186 	{
187 		a->q_flags |= QBADADDR;
188 		usrerr("550 Cannot mail directly to programs");
189 	}
190 
191 	/*
192 	**  Look up this person in the recipient list.
193 	**	If they are there already, return, otherwise continue.
194 	**	If the list is empty, just add it.  Notice the cute
195 	**	hack to make from addresses suppress things correctly:
196 	**	the QDONTSEND bit will be set in the send list.
197 	**	[Please note: the emphasis is on "hack."]
198 	*/
199 
200 	for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next)
201 	{
202 		if (sameaddr(q, a))
203 		{
204 			if (tTd(26, 1))
205 			{
206 				printf("%s in sendq: ", a->q_paddr);
207 				printaddr(q, FALSE);
208 			}
209 			if (!bitset(QPRIMARY, q->q_flags))
210 			{
211 				if (!bitset(QDONTSEND, a->q_flags))
212 					message("duplicate suppressed");
213 				q->q_flags |= a->q_flags;
214 			}
215 			a = q;
216 			goto testselfdestruct;
217 		}
218 	}
219 
220 	/* add address on list */
221 	*pq = a;
222 	a->q_next = NULL;
223 
224 	/*
225 	**  Alias the name and handle special mailer types.
226 	*/
227 
228   trylocaluser:
229 	if (tTd(29, 7))
230 		printf("at trylocaluser %s\n", a->q_user);
231 
232 	if (bitset(QDONTSEND|QBADADDR|QVERIFIED, a->q_flags))
233 		goto testselfdestruct;
234 
235 	if (m == InclMailer)
236 	{
237 		a->q_flags |= QDONTSEND;
238 		if (a->q_alias == NULL && !bitset(EF_QUEUERUN, e->e_flags))
239 		{
240 			a->q_flags |= QBADADDR;
241 			usrerr("550 Cannot mail directly to :include:s");
242 		}
243 		else
244 		{
245 			int ret;
246 
247 			message("including file %s", a->q_user);
248 			ret = include(a->q_user, FALSE, a, sendq, e);
249 			if (transienterror(ret))
250 			{
251 #ifdef LOG
252 				if (LogLevel > 2)
253 					syslog(LOG_ERR, "%s: include %s: transient error: %e",
254 						e->e_id, a->q_user, errstring(ret));
255 #endif
256 				a->q_flags |= QQUEUEUP;
257 				usrerr("451 Cannot open %s: %s",
258 					a->q_user, errstring(ret));
259 			}
260 			else if (ret != 0)
261 			{
262 				a->q_flags |= QBADADDR;
263 				usrerr("550 Cannot open %s: %s",
264 					a->q_user, errstring(ret));
265 			}
266 		}
267 	}
268 	else if (m == FileMailer)
269 	{
270 		struct stat stb;
271 		extern bool writable();
272 
273 		p = strrchr(buf, '/');
274 		/* check if writable or creatable */
275 		if (a->q_alias == NULL && !bitset(EF_QUEUERUN, e->e_flags))
276 		{
277 			a->q_flags |= QBADADDR;
278 			usrerr("550 Cannot mail directly to files");
279 		}
280 		else if ((stat(buf, &stb) >= 0) ? (!writable(&stb)) :
281 		    (*p = '\0', safefile(buf, RealUid, TRUE, S_IWRITE|S_IEXEC) != 0))
282 		{
283 			a->q_flags |= QBADADDR;
284 			giveresponse(EX_CANTCREAT, m, NULL, e);
285 		}
286 	}
287 
288 	if (m != LocalMailer)
289 	{
290 		if (!bitset(QDONTSEND, a->q_flags))
291 			e->e_nrcpts++;
292 		goto testselfdestruct;
293 	}
294 
295 	/* try aliasing */
296 	alias(a, sendq, e);
297 
298 # ifdef USERDB
299 	/* if not aliased, look it up in the user database */
300 	if (!bitset(QDONTSEND|QNOTREMOTE|QVERIFIED, a->q_flags))
301 	{
302 		extern int udbexpand();
303 		extern int errno;
304 
305 		if (udbexpand(a, sendq, e) == EX_TEMPFAIL)
306 		{
307 			a->q_flags |= QQUEUEUP;
308 			if (e->e_message == NULL)
309 				e->e_message = newstr("Deferred: user database error");
310 # ifdef LOG
311 			if (LogLevel > 8)
312 				syslog(LOG_INFO, "%s: deferred: udbexpand: %s",
313 					e->e_id, errstring(errno));
314 # endif
315 			message("queued (user database error): %s",
316 				errstring(errno));
317 			e->e_nrcpts++;
318 			goto testselfdestruct;
319 		}
320 	}
321 # endif
322 
323 	/* if it was an alias or a UDB expansion, just return now */
324 	if (bitset(QDONTSEND|QQUEUEUP|QVERIFIED, a->q_flags))
325 		goto testselfdestruct;
326 
327 	/*
328 	**  If we have a level two config file, then pass the name through
329 	**  Ruleset 5 before sending it off.  Ruleset 5 has the right
330 	**  to send rewrite it to another mailer.  This gives us a hook
331 	**  after local aliasing has been done.
332 	*/
333 
334 	if (tTd(29, 5))
335 	{
336 		printf("recipient: testing local?  cl=%d, rr5=%x\n\t",
337 			ConfigLevel, RewriteRules[5]);
338 		printaddr(a, FALSE);
339 	}
340 	if (!bitset(QNOTREMOTE, a->q_flags) && ConfigLevel >= 2 &&
341 	    RewriteRules[5] != NULL)
342 	{
343 		maplocaluser(a, sendq, e);
344 	}
345 
346 	/*
347 	**  If it didn't get rewritten to another mailer, go ahead
348 	**  and deliver it.
349 	*/
350 
351 	if (!bitset(QDONTSEND|QQUEUEUP, a->q_flags))
352 	{
353 		auto bool fuzzy;
354 		register struct passwd *pw;
355 		extern struct passwd *finduser();
356 
357 		/* warning -- finduser may trash buf */
358 		pw = finduser(buf, &fuzzy);
359 		if (pw == NULL)
360 		{
361 			a->q_flags |= QBADADDR;
362 			giveresponse(EX_NOUSER, m, NULL, e);
363 		}
364 		else
365 		{
366 			char nbuf[MAXNAME];
367 
368 			if (fuzzy)
369 			{
370 				/* name was a fuzzy match */
371 				a->q_user = newstr(pw->pw_name);
372 				if (findusercount++ > 3)
373 				{
374 					a->q_flags |= QBADADDR;
375 					usrerr("554 aliasing/forwarding loop for %s broken",
376 						pw->pw_name);
377 					return (a);
378 				}
379 
380 				/* see if it aliases */
381 				(void) strcpy(buf, pw->pw_name);
382 				goto trylocaluser;
383 			}
384 			a->q_home = newstr(pw->pw_dir);
385 			a->q_uid = pw->pw_uid;
386 			a->q_gid = pw->pw_gid;
387 			a->q_ruser = newstr(pw->pw_name);
388 			a->q_flags |= QGOODUID;
389 			buildfname(pw->pw_gecos, pw->pw_name, nbuf);
390 			if (nbuf[0] != '\0')
391 				a->q_fullname = newstr(nbuf);
392 			if (!quoted)
393 				forward(a, sendq, e);
394 		}
395 	}
396 	if (!bitset(QDONTSEND, a->q_flags))
397 		e->e_nrcpts++;
398 
399   testselfdestruct:
400 	if (a->q_alias == NULL && a != &e->e_from)
401 	{
402 		q = a->q_next;
403 		while (q != NULL && bitset(QDONTSEND|QBADADDR, q->q_flags))
404 			q = q->q_next;
405 		if (bitset(QDONTSEND, a->q_flags) && q == NULL)
406 		{
407 			a->q_flags |= QBADADDR;
408 			usrerr("554 aliasing/forwarding loop broken");
409 		}
410 	}
411 	return (a);
412 }
413 /*
414 **  FINDUSER -- find the password entry for a user.
415 **
416 **	This looks a lot like getpwnam, except that it may want to
417 **	do some fancier pattern matching in /etc/passwd.
418 **
419 **	This routine contains most of the time of many sendmail runs.
420 **	It deserves to be optimized.
421 **
422 **	Parameters:
423 **		name -- the name to match against.
424 **		fuzzyp -- an outarg that is set to TRUE if this entry
425 **			was found using the fuzzy matching algorithm;
426 **			set to FALSE otherwise.
427 **
428 **	Returns:
429 **		A pointer to a pw struct.
430 **		NULL if name is unknown or ambiguous.
431 **
432 **	Side Effects:
433 **		may modify name.
434 */
435 
436 struct passwd *
437 finduser(name, fuzzyp)
438 	char *name;
439 	bool *fuzzyp;
440 {
441 	register struct passwd *pw;
442 	register char *p;
443 	extern struct passwd *getpwent();
444 	extern struct passwd *getpwnam();
445 
446 	if (tTd(29, 4))
447 		printf("finduser(%s): ", name);
448 
449 	*fuzzyp = FALSE;
450 
451 	/* look up this login name using fast path */
452 	if ((pw = getpwnam(name)) != NULL)
453 	{
454 		if (tTd(29, 4))
455 			printf("found (non-fuzzy)\n");
456 		return (pw);
457 	}
458 
459 #ifdef MATCHGECOS
460 	/* see if fuzzy matching allowed */
461 	if (!MatchGecos)
462 	{
463 		if (tTd(29, 4))
464 			printf("not found (fuzzy disabled)\n");
465 		return NULL;
466 	}
467 
468 	/* search for a matching full name instead */
469 	for (p = name; *p != '\0'; p++)
470 	{
471 		if (*p == (SpaceSub & 0177) || *p == '_')
472 			*p = ' ';
473 	}
474 	(void) setpwent();
475 	while ((pw = getpwent()) != NULL)
476 	{
477 		char buf[MAXNAME];
478 
479 		buildfname(pw->pw_gecos, pw->pw_name, buf);
480 		if (strchr(buf, ' ') != NULL && !strcasecmp(buf, name))
481 		{
482 			if (tTd(29, 4))
483 				printf("fuzzy matches %s\n", pw->pw_name);
484 			message("sending to login name %s", pw->pw_name);
485 			*fuzzyp = TRUE;
486 			return (pw);
487 		}
488 	}
489 	if (tTd(29, 4))
490 		printf("no fuzzy match found\n");
491 #else
492 	if (tTd(29, 4))
493 		printf("not found (fuzzy disabled)\n");
494 #endif
495 	return (NULL);
496 }
497 /*
498 **  WRITABLE -- predicate returning if the file is writable.
499 **
500 **	This routine must duplicate the algorithm in sys/fio.c.
501 **	Unfortunately, we cannot use the access call since we
502 **	won't necessarily be the real uid when we try to
503 **	actually open the file.
504 **
505 **	Notice that ANY file with ANY execute bit is automatically
506 **	not writable.  This is also enforced by mailfile.
507 **
508 **	Parameters:
509 **		s -- pointer to a stat struct for the file.
510 **
511 **	Returns:
512 **		TRUE -- if we will be able to write this file.
513 **		FALSE -- if we cannot write this file.
514 **
515 **	Side Effects:
516 **		none.
517 */
518 
519 bool
520 writable(s)
521 	register struct stat *s;
522 {
523 	uid_t euid;
524 	gid_t egid;
525 	int bits;
526 
527 	if (bitset(0111, s->st_mode))
528 		return (FALSE);
529 	euid = RealUid;
530 	egid = RealGid;
531 	if (geteuid() == 0)
532 	{
533 		if (bitset(S_ISUID, s->st_mode))
534 			euid = s->st_uid;
535 		if (bitset(S_ISGID, s->st_mode))
536 			egid = s->st_gid;
537 	}
538 
539 	if (euid == 0)
540 		return (TRUE);
541 	bits = S_IWRITE;
542 	if (euid != s->st_uid)
543 	{
544 		bits >>= 3;
545 		if (egid != s->st_gid)
546 			bits >>= 3;
547 	}
548 	return ((s->st_mode & bits) != 0);
549 }
550 /*
551 **  INCLUDE -- handle :include: specification.
552 **
553 **	Parameters:
554 **		fname -- filename to include.
555 **		forwarding -- if TRUE, we are reading a .forward file.
556 **			if FALSE, it's a :include: file.
557 **		ctladdr -- address template to use to fill in these
558 **			addresses -- effective user/group id are
559 **			the important things.
560 **		sendq -- a pointer to the head of the send queue
561 **			to put these addresses in.
562 **
563 **	Returns:
564 **		open error status
565 **
566 **	Side Effects:
567 **		reads the :include: file and sends to everyone
568 **		listed in that file.
569 */
570 
571 static jmp_buf	CtxIncludeTimeout;
572 static int	includetimeout();
573 
574 int
575 include(fname, forwarding, ctladdr, sendq, e)
576 	char *fname;
577 	bool forwarding;
578 	ADDRESS *ctladdr;
579 	ADDRESS **sendq;
580 	ENVELOPE *e;
581 {
582 	register FILE *fp;
583 	char *oldto = e->e_to;
584 	char *oldfilename = FileName;
585 	int oldlinenumber = LineNumber;
586 	register EVENT *ev = NULL;
587 	int nincludes;
588 	int ret;
589 	ADDRESS *ca;
590 	uid_t uid;
591 	char buf[MAXLINE];
592 
593 	if (tTd(27, 2))
594 		printf("include(%s)\n", fname);
595 	if (tTd(27, 4))
596 		printf("   ruid=%d euid=%d\n", getuid(), geteuid());
597 	if (tTd(27, 14))
598 	{
599 		printf("ctladdr ");
600 		printaddr(ctladdr, FALSE);
601 	}
602 
603 	/*
604 	**  If home directory is remote mounted but server is down,
605 	**  this can hang or give errors; use a timeout to avoid this
606 	*/
607 
608 	ca = getctladdr(ctladdr);
609 	if (ca == NULL)
610 		uid = 0;
611 	else
612 		uid = ca->q_uid;
613 
614 	if (setjmp(CtxIncludeTimeout) != 0)
615 	{
616 		ctladdr->q_flags |= QQUEUEUP;
617 		errno = 0;
618 		usrerr("451 open timeout on %s", fname);
619 		return ETIMEDOUT;
620 	}
621 	ev = setevent((time_t) 60, includetimeout, 0);
622 
623 	/* the input file must be marked safe */
624 	if ((ret = safefile(fname, uid, forwarding, S_IREAD)) != 0)
625 	{
626 		/* don't use this .forward file */
627 		clrevent(ev);
628 		if (tTd(27, 4))
629 			printf("include: not safe (uid=%d): %s\n",
630 				uid, errstring(ret));
631 		return ret;
632 	}
633 
634 	fp = fopen(fname, "r");
635 	if (fp == NULL)
636 	{
637 		int ret = errno;
638 
639 		clrevent(ev);
640 		if (tTd(27, 4))
641 			printf("include: open: %s\n", errstring(ret));
642 		return ret;
643 	}
644 
645 	if (ca == NULL)
646 	{
647 		struct stat st;
648 
649 		if (fstat(fileno(fp), &st) < 0)
650 		{
651 			int ret = errno;
652 
653 			clrevent(ev);
654 			syserr("Cannot fstat %s!", fname);
655 			return ret;
656 		}
657 		ctladdr->q_uid = st.st_uid;
658 		ctladdr->q_gid = st.st_gid;
659 		ctladdr->q_flags |= QGOODUID;
660 	}
661 
662 	clrevent(ev);
663 
664 	if (bitset(EF_VRFYONLY, e->e_flags))
665 	{
666 		/* don't do any more now */
667 		ctladdr->q_flags |= QVERIFIED;
668 		e->e_nrcpts++;
669 		xfclose(fp, "include", fname);
670 		return 0;
671 	}
672 
673 	/* read the file -- each line is a comma-separated list. */
674 	FileName = fname;
675 	LineNumber = 0;
676 	ctladdr->q_flags &= ~QSELFREF;
677 	nincludes = 0;
678 	while (fgets(buf, sizeof buf, fp) != NULL)
679 	{
680 		register char *p = strchr(buf, '\n');
681 
682 		LineNumber++;
683 		if (p != NULL)
684 			*p = '\0';
685 		if (buf[0] == '#' || buf[0] == '\0')
686 			continue;
687 		e->e_to = NULL;
688 		message("%s to %s",
689 			forwarding ? "forwarding" : "sending", buf);
690 #ifdef LOG
691 		if (forwarding && LogLevel > 9)
692 			syslog(LOG_INFO, "%s: forward %s => %s",
693 				e->e_id, oldto, buf);
694 #endif
695 
696 		AliasLevel++;
697 		nincludes += sendtolist(buf, ctladdr, sendq, e);
698 		AliasLevel--;
699 	}
700 
701 	if (ferror(fp) && tTd(27, 3))
702 		printf("include: read error: %s\n", errstring(errno));
703 	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
704 	{
705 		if (tTd(27, 5))
706 		{
707 			printf("include: QDONTSEND ");
708 			printaddr(ctladdr, FALSE);
709 		}
710 		ctladdr->q_flags |= QDONTSEND;
711 	}
712 
713 	(void) xfclose(fp, "include", fname);
714 	FileName = oldfilename;
715 	LineNumber = oldlinenumber;
716 	e->e_to = oldto;
717 	return 0;
718 }
719 
720 static
721 includetimeout()
722 {
723 	longjmp(CtxIncludeTimeout, 1);
724 }
725 /*
726 **  SENDTOARGV -- send to an argument vector.
727 **
728 **	Parameters:
729 **		argv -- argument vector to send to.
730 **		e -- the current envelope.
731 **
732 **	Returns:
733 **		none.
734 **
735 **	Side Effects:
736 **		puts all addresses on the argument vector onto the
737 **			send queue.
738 */
739 
740 sendtoargv(argv, e)
741 	register char **argv;
742 	register ENVELOPE *e;
743 {
744 	register char *p;
745 
746 	while ((p = *argv++) != NULL)
747 	{
748 		(void) sendtolist(p, (ADDRESS *) NULL, &e->e_sendqueue, e);
749 	}
750 }
751 /*
752 **  GETCTLADDR -- get controlling address from an address header.
753 **
754 **	If none, get one corresponding to the effective userid.
755 **
756 **	Parameters:
757 **		a -- the address to find the controller of.
758 **
759 **	Returns:
760 **		the controlling address.
761 **
762 **	Side Effects:
763 **		none.
764 */
765 
766 ADDRESS *
767 getctladdr(a)
768 	register ADDRESS *a;
769 {
770 	while (a != NULL && !bitset(QGOODUID, a->q_flags))
771 		a = a->q_alias;
772 	return (a);
773 }
774