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