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