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