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.21 (Berkeley) 03/01/93";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 # include <sys/stat.h>
15 # include <fcntl.h>
16 # include <pwd.h>
17 
18 /*
19 **  SENDTOLIST -- Designate a send list.
20 **
21 **	The parameter is a comma-separated list of people to send to.
22 **	This routine arranges to send to all of them.
23 **
24 **	Parameters:
25 **		list -- the send list.
26 **		ctladdr -- the address template for the person to
27 **			send to -- effective uid/gid are important.
28 **			This is typically the alias that caused this
29 **			expansion.
30 **		sendq -- a pointer to the head of a queue to put
31 **			these people into.
32 **		e -- the envelope in which to add these recipients.
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 		auto char *delimptr;
77 		register ADDRESS *a;
78 
79 		/* parse the address */
80 		while ((isascii(*p) && isspace(*p)) || *p == ',')
81 			p++;
82 		a = parseaddr(p, (ADDRESS *) NULL, 1, delimiter, &delimptr, e);
83 		p = delimptr;
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 int 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 (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 			int err;
252 
253 			message("including file %s", a->q_user);
254 			err = include(a->q_user, FALSE, a, sendq, e);
255 			if (transienterror(err))
256 				a->q_flags |= QQUEUEUP|QDONTSEND;
257 		}
258 	}
259 	else if (m == FileMailer)
260 	{
261 		struct stat stb;
262 		extern bool writable();
263 
264 		p = strrchr(buf, '/');
265 		/* check if writable or creatable */
266 		if (a->q_alias == NULL && !QueueRun)
267 		{
268 			a->q_flags |= QDONTSEND|QBADADDR;
269 			usrerr("550 Cannot mail directly to files");
270 		}
271 		else if ((stat(buf, &stb) >= 0) ? (!writable(&stb)) :
272 		    (*p = '\0', safefile(buf, getruid(), S_IWRITE|S_IEXEC) != 0))
273 		{
274 			a->q_flags |= QBADADDR;
275 			giveresponse(EX_CANTCREAT, m, e);
276 		}
277 	}
278 
279 	if (m != LocalMailer)
280 	{
281 		if (!bitset(QDONTSEND, a->q_flags))
282 			e->e_nrcpts++;
283 		return (a);
284 	}
285 
286 	/* try aliasing */
287 	alias(a, sendq, e);
288 
289 # ifdef USERDB
290 	/* if not aliased, look it up in the user database */
291 	if (!bitset(QDONTSEND|QNOTREMOTE, a->q_flags))
292 	{
293 		extern int udbexpand();
294 
295 		if (udbexpand(a, sendq, e) == EX_TEMPFAIL)
296 		{
297 			a->q_flags |= QQUEUEUP|QDONTSEND;
298 			if (e->e_message == NULL)
299 				e->e_message = newstr("Deferred: user database error");
300 # ifdef LOG
301 			if (LogLevel > 8)
302 				syslog(LOG_INFO, "%s: deferred: udbexpand",
303 					e->e_id);
304 # endif
305 			message("queued (user database error)");
306 			e->e_nrcpts++;
307 			return (a);
308 		}
309 	}
310 # endif
311 
312 	/* if it was an alias or a UDB expansion, just return now */
313 	if (bitset(QDONTSEND|QQUEUEUP|QVERIFIED, a->q_flags))
314 		return (a);
315 
316 	/*
317 	**  If we have a level two config file, then pass the name through
318 	**  Ruleset 5 before sending it off.  Ruleset 5 has the right
319 	**  to send rewrite it to another mailer.  This gives us a hook
320 	**  after local aliasing has been done.
321 	*/
322 
323 	if (tTd(29, 5))
324 	{
325 		printf("recipient: testing local?  cl=%d, rr5=%x\n\t",
326 			ConfigLevel, RewriteRules[5]);
327 		printaddr(a, FALSE);
328 	}
329 	if (!bitset(QNOTREMOTE, a->q_flags) && ConfigLevel >= 2 &&
330 	    RewriteRules[5] != NULL)
331 	{
332 		maplocaluser(a, sendq, e);
333 	}
334 
335 	/*
336 	**  If it didn't get rewritten to another mailer, go ahead
337 	**  and deliver it.
338 	*/
339 
340 	if (!bitset(QDONTSEND|QQUEUEUP, a->q_flags))
341 	{
342 		auto bool fuzzy;
343 		register struct passwd *pw;
344 		extern struct passwd *finduser();
345 
346 		/* warning -- finduser may trash buf */
347 		pw = finduser(buf, &fuzzy);
348 		if (pw == NULL)
349 		{
350 			a->q_flags |= QBADADDR;
351 			giveresponse(EX_NOUSER, m, e);
352 		}
353 		else
354 		{
355 			char nbuf[MAXNAME];
356 
357 			if (fuzzy)
358 			{
359 				/* name was a fuzzy match */
360 				a->q_user = newstr(pw->pw_name);
361 				if (findusercount++ > 3)
362 				{
363 					usrerr("554 aliasing/forwarding loop for %s broken",
364 						pw->pw_name);
365 					return (a);
366 				}
367 
368 				/* see if it aliases */
369 				(void) strcpy(buf, pw->pw_name);
370 				goto trylocaluser;
371 			}
372 			a->q_home = newstr(pw->pw_dir);
373 			a->q_uid = pw->pw_uid;
374 			a->q_gid = pw->pw_gid;
375 			a->q_flags |= QGOODUID;
376 			buildfname(pw->pw_gecos, pw->pw_name, nbuf);
377 			if (nbuf[0] != '\0')
378 				a->q_fullname = newstr(nbuf);
379 			if (!quoted)
380 				forward(a, sendq, e);
381 		}
382 	}
383 	if (!bitset(QDONTSEND, a->q_flags))
384 		e->e_nrcpts++;
385 	return (a);
386 }
387 /*
388 **  FINDUSER -- find the password entry for a user.
389 **
390 **	This looks a lot like getpwnam, except that it may want to
391 **	do some fancier pattern matching in /etc/passwd.
392 **
393 **	This routine contains most of the time of many sendmail runs.
394 **	It deserves to be optimized.
395 **
396 **	Parameters:
397 **		name -- the name to match against.
398 **		fuzzyp -- an outarg that is set to TRUE if this entry
399 **			was found using the fuzzy matching algorithm;
400 **			set to FALSE otherwise.
401 **
402 **	Returns:
403 **		A pointer to a pw struct.
404 **		NULL if name is unknown or ambiguous.
405 **
406 **	Side Effects:
407 **		may modify name.
408 */
409 
410 struct passwd *
411 finduser(name, fuzzyp)
412 	char *name;
413 	bool *fuzzyp;
414 {
415 	register struct passwd *pw;
416 	register char *p;
417 	extern struct passwd *getpwent();
418 	extern struct passwd *getpwnam();
419 
420 	if (tTd(29, 4))
421 		printf("finduser(%s): ", name);
422 
423 	/* map upper => lower case */
424 	for (p = name; *p != '\0'; p++)
425 	{
426 		if (isascii(*p) && isupper(*p))
427 			*p = tolower(*p);
428 	}
429 	*fuzzyp = FALSE;
430 
431 	/* look up this login name using fast path */
432 	if ((pw = getpwnam(name)) != NULL)
433 	{
434 		if (tTd(29, 4))
435 			printf("found (non-fuzzy)\n");
436 		return (pw);
437 	}
438 
439 #ifdef MATCHGECOS
440 	/* see if fuzzy matching allowed */
441 	if (!MatchGecos)
442 	{
443 		if (tTd(29, 4))
444 			printf("not found (fuzzy disabled)\n");
445 		return NULL;
446 	}
447 
448 	/* search for a matching full name instead */
449 	for (p = name; *p != '\0'; p++)
450 	{
451 		if (*p == (SpaceSub & 0177) || *p == '_')
452 			*p = ' ';
453 	}
454 	(void) setpwent();
455 	while ((pw = getpwent()) != NULL)
456 	{
457 		char buf[MAXNAME];
458 
459 		buildfname(pw->pw_gecos, pw->pw_name, buf);
460 		if (strchr(buf, ' ') != NULL && !strcasecmp(buf, name))
461 		{
462 			if (tTd(29, 4))
463 				printf("fuzzy matches %s\n", pw->pw_name);
464 			message("sending to login name %s", pw->pw_name);
465 			*fuzzyp = TRUE;
466 			return (pw);
467 		}
468 	}
469 #endif
470 	if (tTd(29, 4))
471 		printf("no fuzzy match found\n");
472 	return (NULL);
473 }
474 /*
475 **  WRITABLE -- predicate returning if the file is writable.
476 **
477 **	This routine must duplicate the algorithm in sys/fio.c.
478 **	Unfortunately, we cannot use the access call since we
479 **	won't necessarily be the real uid when we try to
480 **	actually open the file.
481 **
482 **	Notice that ANY file with ANY execute bit is automatically
483 **	not writable.  This is also enforced by mailfile.
484 **
485 **	Parameters:
486 **		s -- pointer to a stat struct for the file.
487 **
488 **	Returns:
489 **		TRUE -- if we will be able to write this file.
490 **		FALSE -- if we cannot write this file.
491 **
492 **	Side Effects:
493 **		none.
494 */
495 
496 bool
497 writable(s)
498 	register struct stat *s;
499 {
500 	uid_t euid;
501 	gid_t egid;
502 	int bits;
503 
504 	if (bitset(0111, s->st_mode))
505 		return (FALSE);
506 	euid = getruid();
507 	egid = getrgid();
508 	if (geteuid() == 0)
509 	{
510 		if (bitset(S_ISUID, s->st_mode))
511 			euid = s->st_uid;
512 		if (bitset(S_ISGID, s->st_mode))
513 			egid = s->st_gid;
514 	}
515 
516 	if (euid == 0)
517 		return (TRUE);
518 	bits = S_IWRITE;
519 	if (euid != s->st_uid)
520 	{
521 		bits >>= 3;
522 		if (egid != s->st_gid)
523 			bits >>= 3;
524 	}
525 	return ((s->st_mode & bits) != 0);
526 }
527 /*
528 **  INCLUDE -- handle :include: specification.
529 **
530 **	Parameters:
531 **		fname -- filename to include.
532 **		forwarding -- if TRUE, we are reading a .forward file.
533 **			if FALSE, it's a :include: file.
534 **		ctladdr -- address template to use to fill in these
535 **			addresses -- effective user/group id are
536 **			the important things.
537 **		sendq -- a pointer to the head of the send queue
538 **			to put these addresses in.
539 **
540 **	Returns:
541 **		open error status
542 **
543 **	Side Effects:
544 **		reads the :include: file and sends to everyone
545 **		listed in that file.
546 */
547 
548 static jmp_buf	CtxIncludeTimeout;
549 
550 int
551 include(fname, forwarding, ctladdr, sendq, e)
552 	char *fname;
553 	bool forwarding;
554 	ADDRESS *ctladdr;
555 	ADDRESS **sendq;
556 	ENVELOPE *e;
557 {
558 	register FILE *fp;
559 	char *oldto = e->e_to;
560 	char *oldfilename = FileName;
561 	int oldlinenumber = LineNumber;
562 	register EVENT *ev = NULL;
563 	int nincludes;
564 	int ret;
565 	char buf[MAXLINE];
566 	static int includetimeout();
567 
568 	if (tTd(27, 2))
569 		printf("include(%s)\n", fname);
570 
571 	/*
572 	**  If home directory is remote mounted but server is down,
573 	**  this can hang or give errors; use a timeout to avoid this
574 	*/
575 
576 	if (setjmp(CtxIncludeTimeout) != 0)
577 	{
578 		ctladdr->q_flags |= QQUEUEUP|QDONTSEND;
579 		errno = 0;
580 		usrerr("451 open timeout on %s", fname);
581 		return ETIMEDOUT;
582 	}
583 	ev = setevent((time_t) 60, includetimeout, 0);
584 
585 	/* if forwarding, the input file must be marked safe */
586 	if (forwarding && (ret = safefile(fname, ctladdr->q_uid, S_IREAD)) != 0)
587 	{
588 		/* don't use this .forward file */
589 		clrevent(ev);
590 		if (tTd(27, 4))
591 			printf("include: not safe (uid=%d): %s\n",
592 				ctladdr->q_uid, errstring(ret));
593 		return ret;
594 	}
595 
596 	fp = fopen(fname, "r");
597 	if (fp == NULL)
598 	{
599 		int ret = errno;
600 
601 		clrevent(ev);
602 		usrerr("550 Cannot open %s", fname);
603 		return ret;
604 	}
605 
606 	if (getctladdr(ctladdr) == NULL)
607 	{
608 		struct stat st;
609 
610 		if (fstat(fileno(fp), &st) < 0)
611 		{
612 			int ret = errno;
613 
614 			clrevent(ev);
615 			syserr("Cannot fstat %s!", fname);
616 			return ret;
617 		}
618 		ctladdr->q_uid = st.st_uid;
619 		ctladdr->q_gid = st.st_gid;
620 		ctladdr->q_flags |= QGOODUID;
621 	}
622 
623 	clrevent(ev);
624 
625 	if (bitset(EF_VRFYONLY, e->e_flags))
626 	{
627 		/* don't do any more now */
628 		fclose(fp);
629 		return 0;
630 	}
631 
632 	/* read the file -- each line is a comma-separated list. */
633 	FileName = fname;
634 	LineNumber = 0;
635 	ctladdr->q_flags &= ~QSELFREF;
636 	nincludes = 0;
637 	while (fgets(buf, sizeof buf, fp) != NULL)
638 	{
639 		register char *p = strchr(buf, '\n');
640 
641 		LineNumber++;
642 		if (p != NULL)
643 			*p = '\0';
644 		if (buf[0] == '#' || buf[0] == '\0')
645 			continue;
646 		e->e_to = NULL;
647 		message("%s to %s",
648 			forwarding ? "forwarding" : "sending", buf);
649 #ifdef LOG
650 		if (forwarding && LogLevel > 9)
651 			syslog(LOG_INFO, "%s: forward %s => %s",
652 				e->e_id, oldto, buf);
653 #endif
654 
655 		AliasLevel++;
656 		nincludes += sendtolist(buf, ctladdr, sendq, e);
657 		AliasLevel--;
658 	}
659 	if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags))
660 	{
661 		if (tTd(27, 5))
662 		{
663 			printf("include: QDONTSEND ");
664 			printaddr(ctladdr, FALSE);
665 		}
666 		ctladdr->q_flags |= QDONTSEND;
667 	}
668 
669 	(void) fclose(fp);
670 	FileName = oldfilename;
671 	LineNumber = oldlinenumber;
672 	return 0;
673 }
674 
675 static
676 includetimeout()
677 {
678 	longjmp(CtxIncludeTimeout, 1);
679 }
680 /*
681 **  SENDTOARGV -- send to an argument vector.
682 **
683 **	Parameters:
684 **		argv -- argument vector to send to.
685 **		e -- the current envelope.
686 **
687 **	Returns:
688 **		none.
689 **
690 **	Side Effects:
691 **		puts all addresses on the argument vector onto the
692 **			send queue.
693 */
694 
695 sendtoargv(argv, e)
696 	register char **argv;
697 	register ENVELOPE *e;
698 {
699 	register char *p;
700 
701 	while ((p = *argv++) != NULL)
702 	{
703 		if (argv[0] != NULL && argv[1] != NULL && !strcasecmp(argv[0], "at"))
704 		{
705 			char nbuf[MAXNAME];
706 
707 			if (strlen(p) + strlen(argv[1]) + 2 > sizeof nbuf)
708 				usrerr("554 address overflow");
709 			else
710 			{
711 				(void) strcpy(nbuf, p);
712 				(void) strcat(nbuf, "@");
713 				(void) strcat(nbuf, argv[1]);
714 				p = newstr(nbuf);
715 				argv += 2;
716 			}
717 		}
718 		(void) sendtolist(p, (ADDRESS *) NULL, &e->e_sendqueue, e);
719 	}
720 }
721 /*
722 **  GETCTLADDR -- get controlling address from an address header.
723 **
724 **	If none, get one corresponding to the effective userid.
725 **
726 **	Parameters:
727 **		a -- the address to find the controller of.
728 **
729 **	Returns:
730 **		the controlling address.
731 **
732 **	Side Effects:
733 **		none.
734 */
735 
736 ADDRESS *
737 getctladdr(a)
738 	register ADDRESS *a;
739 {
740 	while (a != NULL && !bitset(QGOODUID, a->q_flags))
741 		a = a->q_alias;
742 	return (a);
743 }
744