xref: /netbsd-src/lib/libc/gen/pwcache.c (revision 08c81a9c2dc8c7300e893321eb65c0925d60871c)
1 /*	$NetBSD: pwcache.c,v 1.22 2002/07/03 17:17:35 pooka Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992 Keith Muller.
5  * Copyright (c) 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Keith Muller of the University of California, San Diego.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the University of
22  *	California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39 
40 /*-
41  * Copyright (c) 2002 The NetBSD Foundation, Inc.
42  * All rights reserved.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. All advertising materials mentioning features or use of this software
53  *    must display the following acknowledgement:
54  *        This product includes software developed by the NetBSD
55  *        Foundation, Inc. and its contributors.
56  * 4. Neither the name of The NetBSD Foundation nor the names of its
57  *    contributors may be used to endorse or promote products derived
58  *    from this software without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
61  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
62  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
63  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
64  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
65  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
66  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
67  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
68  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
69  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
70  * POSSIBILITY OF SUCH DAMAGE.
71  */
72 
73 #include <sys/cdefs.h>
74 #if defined(LIBC_SCCS) && !defined(lint)
75 #if 0
76 static char sccsid[] = "@(#)cache.c	8.1 (Berkeley) 5/31/93";
77 #else
78 __RCSID("$NetBSD: pwcache.c,v 1.22 2002/07/03 17:17:35 pooka Exp $");
79 #endif
80 #endif /* LIBC_SCCS and not lint */
81 
82 #include "namespace.h"
83 
84 #include <sys/types.h>
85 #include <sys/param.h>
86 
87 #include <assert.h>
88 #include <grp.h>
89 #include <pwd.h>
90 #include <stdio.h>
91 #include <stdlib.h>
92 #include <string.h>
93 #include <unistd.h>
94 
95 #ifdef __weak_alias
96 __weak_alias(user_from_uid,_user_from_uid)
97 __weak_alias(group_from_gid,_group_from_gid)
98 __weak_alias(pwcache_userdb,_pwcache_userdb)
99 __weak_alias(pwcache_groupdb,_pwcache_groupdb)
100 #endif
101 
102 #if !HAVE_PWCACHE_USERDB
103 #include "pwcache.h"
104 
105 /*
106  * routines that control user, group, uid and gid caches (for the archive
107  * member print routine).
108  * IMPORTANT:
109  * these routines cache BOTH hits and misses, a major performance improvement
110  */
111 
112 /*
113  * function pointers to various name lookup routines.
114  * these may be changed as necessary.
115  */
116 static	int		(*_pwcache_setgroupent)(int)		= setgroupent;
117 static	void		(*_pwcache_endgrent)(void)		= endgrent;
118 static	struct group *	(*_pwcache_getgrnam)(const char *)	= getgrnam;
119 static	struct group *	(*_pwcache_getgrgid)(gid_t)		= getgrgid;
120 static	int		(*_pwcache_setpassent)(int)		= setpassent;
121 static	void		(*_pwcache_endpwent)(void)		= endpwent;
122 static	struct passwd *	(*_pwcache_getpwnam)(const char *)	= getpwnam;
123 static	struct passwd *	(*_pwcache_getpwuid)(uid_t)		= getpwuid;
124 
125 /*
126  * internal state
127  */
128 static	int	pwopn;		/* is password file open */
129 static	int	gropn;		/* is group file open */
130 static	UIDC	**uidtb;	/* uid to name cache */
131 static	GIDC	**gidtb;	/* gid to name cache */
132 static	UIDC	**usrtb;	/* user name to uid cache */
133 static	GIDC	**grptb;	/* group name to gid cache */
134 
135 static	int	uidtb_fail;	/* uidtb_start() failed ? */
136 static	int	gidtb_fail;	/* gidtb_start() failed ? */
137 static	int	usrtb_fail;	/* usrtb_start() failed ? */
138 static	int	grptb_fail;	/* grptb_start() failed ? */
139 
140 
141 static	u_int	st_hash(const char *, size_t, int);
142 static	int	uidtb_start(void);
143 static	int	gidtb_start(void);
144 static	int	usrtb_start(void);
145 static	int	grptb_start(void);
146 
147 
148 static u_int
149 st_hash(const char *name, size_t len, int tabsz)
150 {
151 	u_int key = 0;
152 
153 	_DIAGASSERT(name != NULL);
154 
155 	while (len--) {
156 		key += *name++;
157 		key = (key << 8) | (key >> 24);
158 	}
159 
160 	return (key % tabsz);
161 }
162 
163 /*
164  * uidtb_start
165  *	creates an an empty uidtb
166  * Return:
167  *	0 if ok, -1 otherwise
168  */
169 static int
170 uidtb_start(void)
171 {
172 
173 	if (uidtb != NULL)
174 		return (0);
175 	if (uidtb_fail)
176 		return (-1);
177 	if ((uidtb = (UIDC **)calloc(UID_SZ, sizeof(UIDC *))) == NULL) {
178 		++uidtb_fail;
179 		return (-1);
180 	}
181 	return (0);
182 }
183 
184 /*
185  * gidtb_start
186  *	creates an an empty gidtb
187  * Return:
188  *	0 if ok, -1 otherwise
189  */
190 static int
191 gidtb_start(void)
192 {
193 
194 	if (gidtb != NULL)
195 		return (0);
196 	if (gidtb_fail)
197 		return (-1);
198 	if ((gidtb = (GIDC **)calloc(GID_SZ, sizeof(GIDC *))) == NULL) {
199 		++gidtb_fail;
200 		return (-1);
201 	}
202 	return (0);
203 }
204 
205 /*
206  * usrtb_start
207  *	creates an an empty usrtb
208  * Return:
209  *	0 if ok, -1 otherwise
210  */
211 static int
212 usrtb_start(void)
213 {
214 
215 	if (usrtb != NULL)
216 		return (0);
217 	if (usrtb_fail)
218 		return (-1);
219 	if ((usrtb = (UIDC **)calloc(UNM_SZ, sizeof(UIDC *))) == NULL) {
220 		++usrtb_fail;
221 		return (-1);
222 	}
223 	return (0);
224 }
225 
226 /*
227  * grptb_start
228  *	creates an an empty grptb
229  * Return:
230  *	0 if ok, -1 otherwise
231  */
232 static int
233 grptb_start(void)
234 {
235 
236 	if (grptb != NULL)
237 		return (0);
238 	if (grptb_fail)
239 		return (-1);
240 	if ((grptb = (GIDC **)calloc(GNM_SZ, sizeof(GIDC *))) == NULL) {
241 		++grptb_fail;
242 		return (-1);
243 	}
244 	return (0);
245 }
246 
247 #if !HAVE_USER_FROM_UID
248 /*
249  * user_from_uid()
250  *	caches the name (if any) for the uid. If noname clear, we always
251  *	return the the stored name (if valid or invalid match).
252  *	We use a simple hash table.
253  * Return
254  *	Pointer to stored name (or a empty string)
255  */
256 
257 const char *
258 user_from_uid(uid_t uid, int noname)
259 {
260 	struct passwd *pw;
261 	UIDC *ptr, **pptr;
262 
263 	if ((uidtb == NULL) && (uidtb_start() < 0))
264 		return (NULL);
265 
266 	/*
267 	 * see if we have this uid cached
268 	 */
269 	pptr = uidtb + (uid % UID_SZ);
270 	ptr = *pptr;
271 
272 	if ((ptr != NULL) && (ptr->valid > 0) && (ptr->uid == uid)) {
273 		/*
274 		 * have an entry for this uid
275 		 */
276 		if (!noname || (ptr->valid == VALID))
277 			return (ptr->name);
278 		return (NULL);
279 	}
280 
281 	/*
282 	 * No entry for this uid, we will add it
283 	 */
284 	if (!pwopn) {
285 		if (_pwcache_setpassent != NULL)
286 			(*_pwcache_setpassent)(1);
287 		++pwopn;
288 	}
289 
290 	if (ptr == NULL)
291 		*pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
292 
293 	if ((pw = (*_pwcache_getpwuid)(uid)) == NULL) {
294 		/*
295 		 * no match for this uid in the local password file
296 		 * a string that is the uid in numberic format
297 		 */
298 		if (ptr == NULL)
299 			return (NULL);
300 		ptr->uid = uid;
301 		(void)snprintf(ptr->name, UNMLEN, "%lu", (long) uid);
302 		ptr->valid = INVALID;
303 		if (noname)
304 			return (NULL);
305 	} else {
306 		/*
307 		 * there is an entry for this uid in the password file
308 		 */
309 		if (ptr == NULL)
310 			return (pw->pw_name);
311 		ptr->uid = uid;
312 		(void)strlcpy(ptr->name, pw->pw_name, UNMLEN);
313 		ptr->valid = VALID;
314 	}
315 	return (ptr->name);
316 }
317 
318 /*
319  * group_from_gid()
320  *	caches the name (if any) for the gid. If noname clear, we always
321  *	return the the stored name (if valid or invalid match).
322  *	We use a simple hash table.
323  * Return
324  *	Pointer to stored name (or a empty string)
325  */
326 
327 const char *
328 group_from_gid(gid_t gid, int noname)
329 {
330 	struct group *gr;
331 	GIDC *ptr, **pptr;
332 
333 	if ((gidtb == NULL) && (gidtb_start() < 0))
334 		return (NULL);
335 
336 	/*
337 	 * see if we have this gid cached
338 	 */
339 	pptr = gidtb + (gid % GID_SZ);
340 	ptr = *pptr;
341 
342 	if ((ptr != NULL) && (ptr->valid > 0) && (ptr->gid == gid)) {
343 		/*
344 		 * have an entry for this gid
345 		 */
346 		if (!noname || (ptr->valid == VALID))
347 			return (ptr->name);
348 		return (NULL);
349 	}
350 
351 	/*
352 	 * No entry for this gid, we will add it
353 	 */
354 	if (!gropn) {
355 		if (_pwcache_setgroupent != NULL)
356 			(*_pwcache_setgroupent)(1);
357 		++gropn;
358 	}
359 
360 	if (ptr == NULL)
361 		*pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
362 
363 	if ((gr = (*_pwcache_getgrgid)(gid)) == NULL) {
364 		/*
365 		 * no match for this gid in the local group file, put in
366 		 * a string that is the gid in numberic format
367 		 */
368 		if (ptr == NULL)
369 			return (NULL);
370 		ptr->gid = gid;
371 		(void)snprintf(ptr->name, GNMLEN, "%lu", (long) gid);
372 		ptr->valid = INVALID;
373 		if (noname)
374 			return (NULL);
375 	} else {
376 		/*
377 		 * there is an entry for this group in the group file
378 		 */
379 		if (ptr == NULL)
380 			return (gr->gr_name);
381 		ptr->gid = gid;
382 		(void)strlcpy(ptr->name, gr->gr_name, GNMLEN);
383 		ptr->valid = VALID;
384 	}
385 	return (ptr->name);
386 }
387 #endif /* HAVE_USER_FROM_UID */
388 
389 /*
390  * uid_from_user()
391  *	caches the uid for a given user name. We use a simple hash table.
392  * Return
393  *	the uid (if any) for a user name, or a -1 if no match can be found
394  */
395 
396 int
397 uid_from_user(const char *name, uid_t *uid)
398 {
399 	struct passwd *pw;
400 	UIDC *ptr, **pptr;
401 	size_t namelen;
402 
403 	/*
404 	 * return -1 for mangled names
405 	 */
406 	if (name == NULL || ((namelen = strlen(name)) == 0))
407 		return (-1);
408 	if ((usrtb == NULL) && (usrtb_start() < 0))
409 		return (-1);
410 
411 	/*
412 	 * look up in hash table, if found and valid return the uid,
413 	 * if found and invalid, return a -1
414 	 */
415 	pptr = usrtb + st_hash(name, namelen, UNM_SZ);
416 	ptr = *pptr;
417 
418 	if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
419 		if (ptr->valid == INVALID)
420 			return (-1);
421 		*uid = ptr->uid;
422 		return (0);
423 	}
424 
425 	if (!pwopn) {
426 		if (_pwcache_setpassent != NULL)
427 			(*_pwcache_setpassent)(1);
428 		++pwopn;
429 	}
430 
431 	if (ptr == NULL)
432 		*pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
433 
434 	/*
435 	 * no match, look it up, if no match store it as an invalid entry,
436 	 * or store the matching uid
437 	 */
438 	if (ptr == NULL) {
439 		if ((pw = (*_pwcache_getpwnam)(name)) == NULL)
440 			return (-1);
441 		*uid = pw->pw_uid;
442 		return (0);
443 	}
444 	(void)strlcpy(ptr->name, name, UNMLEN);
445 	if ((pw = (*_pwcache_getpwnam)(name)) == NULL) {
446 		ptr->valid = INVALID;
447 		return (-1);
448 	}
449 	ptr->valid = VALID;
450 	*uid = ptr->uid = pw->pw_uid;
451 	return (0);
452 }
453 
454 /*
455  * gid_from_group()
456  *	caches the gid for a given group name. We use a simple hash table.
457  * Return
458  *	the gid (if any) for a group name, or a -1 if no match can be found
459  */
460 
461 int
462 gid_from_group(const char *name, gid_t *gid)
463 {
464 	struct group *gr;
465 	GIDC *ptr, **pptr;
466 	size_t namelen;
467 
468 	/*
469 	 * return -1 for mangled names
470 	 */
471 	if (name == NULL || ((namelen = strlen(name)) == 0))
472 		return (-1);
473 	if ((grptb == NULL) && (grptb_start() < 0))
474 		return (-1);
475 
476 	/*
477 	 * look up in hash table, if found and valid return the uid,
478 	 * if found and invalid, return a -1
479 	 */
480 	pptr = grptb + st_hash(name, namelen, GID_SZ);
481 	ptr = *pptr;
482 
483 	if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
484 		if (ptr->valid == INVALID)
485 			return (-1);
486 		*gid = ptr->gid;
487 		return (0);
488 	}
489 
490 	if (!gropn) {
491 		if (_pwcache_setgroupent != NULL)
492 			(*_pwcache_setgroupent)(1);
493 		++gropn;
494 	}
495 
496 	if (ptr == NULL)
497 		*pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
498 
499 	/*
500 	 * no match, look it up, if no match store it as an invalid entry,
501 	 * or store the matching gid
502 	 */
503 	if (ptr == NULL) {
504 		if ((gr = (*_pwcache_getgrnam)(name)) == NULL)
505 			return (-1);
506 		*gid = gr->gr_gid;
507 		return (0);
508 	}
509 
510 	(void)strlcpy(ptr->name, name, GNMLEN);
511 	if ((gr = (*_pwcache_getgrnam)(name)) == NULL) {
512 		ptr->valid = INVALID;
513 		return (-1);
514 	}
515 	ptr->valid = VALID;
516 	*gid = ptr->gid = gr->gr_gid;
517 	return (0);
518 }
519 
520 #define FLUSHTB(arr, len, fail)				\
521 	do {						\
522 		if (arr != NULL) {			\
523 			for (i = 0; i < len; i++)	\
524 				if (arr[i] != NULL)	\
525 					free(arr[i]);	\
526 			arr = NULL;			\
527 		}					\
528 		fail = 0;				\
529 	} while (/* CONSTCOND */0);
530 
531 int
532 pwcache_userdb(
533 	int		(*a_setpassent)(int),
534 	void		(*a_endpwent)(void),
535 	struct passwd *	(*a_getpwnam)(const char *),
536 	struct passwd *	(*a_getpwuid)(uid_t))
537 {
538 	int i;
539 
540 		/* a_setpassent and a_endpwent may be NULL */
541 	if (a_getpwnam == NULL || a_getpwuid == NULL)
542 		return (-1);
543 
544 	if (_pwcache_endpwent != NULL)
545 		(*_pwcache_endpwent)();
546 	FLUSHTB(uidtb, UID_SZ, uidtb_fail);
547 	FLUSHTB(usrtb, UNM_SZ, usrtb_fail);
548 	pwopn = 0;
549 	_pwcache_setpassent = a_setpassent;
550 	_pwcache_endpwent = a_endpwent;
551 	_pwcache_getpwnam = a_getpwnam;
552 	_pwcache_getpwuid = a_getpwuid;
553 
554 	return (0);
555 }
556 
557 int
558 pwcache_groupdb(
559 	int		(*a_setgroupent)(int),
560 	void		(*a_endgrent)(void),
561 	struct group *	(*a_getgrnam)(const char *),
562 	struct group *	(*a_getgrgid)(gid_t))
563 {
564 	int i;
565 
566 		/* a_setgroupent and a_endgrent may be NULL */
567 	if (a_getgrnam == NULL || a_getgrgid == NULL)
568 		return (-1);
569 
570 	if (_pwcache_endgrent != NULL)
571 		(*_pwcache_endgrent)();
572 	FLUSHTB(gidtb, GID_SZ, gidtb_fail);
573 	FLUSHTB(grptb, GNM_SZ, grptb_fail);
574 	gropn = 0;
575 	_pwcache_setgroupent = a_setgroupent;
576 	_pwcache_endgrent = a_endgrent;
577 	_pwcache_getgrnam = a_getgrnam;
578 	_pwcache_getgrgid = a_getgrgid;
579 
580 	return (0);
581 }
582 
583 
584 #ifdef TEST_PWCACHE
585 
586 struct passwd *
587 test_getpwnam(const char *name)
588 {
589 	static struct passwd foo;
590 
591 	memset(&foo, 0, sizeof(foo));
592 	if (strcmp(name, "toor") == 0) {
593 		foo.pw_uid = 666;
594 		return &foo;
595 	}
596 	return (getpwnam(name));
597 }
598 
599 int
600 main(int argc, char *argv[])
601 {
602 	uid_t	u;
603 	int	r, i;
604 
605 	printf("pass 1 (default userdb)\n");
606 	for (i = 1; i < argc; i++) {
607 		printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
608 		    i, pwopn, usrtb_fail, usrtb);
609 		r = uid_from_user(argv[i], &u);
610 		if (r == -1)
611 			printf("  uid_from_user %s: failed\n", argv[i]);
612 		else
613 			printf("  uid_from_user %s: %d\n", argv[i], u);
614 	}
615 	printf("pass 1 finish: pwopn %d usrtb_fail %d usrtb %p\n",
616 		    pwopn, usrtb_fail, usrtb);
617 
618 	puts("");
619 	printf("pass 2 (replacement userdb)\n");
620 	printf("pwcache_userdb returned %d\n",
621 	    pwcache_userdb(setpassent, test_getpwnam, getpwuid));
622 	printf("pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb);
623 
624 	for (i = 1; i < argc; i++) {
625 		printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
626 		    i, pwopn, usrtb_fail, usrtb);
627 		u = -1;
628 		r = uid_from_user(argv[i], &u);
629 		if (r == -1)
630 			printf("  uid_from_user %s: failed\n", argv[i]);
631 		else
632 			printf("  uid_from_user %s: %d\n", argv[i], u);
633 	}
634 	printf("pass 2 finish: pwopn %d usrtb_fail %d usrtb %p\n",
635 		    pwopn, usrtb_fail, usrtb);
636 
637 	puts("");
638 	printf("pass 3 (null pointers)\n");
639 	printf("pwcache_userdb returned %d\n",
640 	    pwcache_userdb(NULL, NULL, NULL));
641 
642 	return (0);
643 }
644 #endif	/* TEST_PWCACHE */
645 #endif	/* !HAVE_PWCACHE_USERDB */
646