xref: /netbsd/lib/libc/gen/pwcache.c (revision bf9ec67e)
1 /*	$NetBSD: pwcache.c,v 1.21 2002/02/26 22:29:40 tv 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.21 2002/02/26 22:29:40 tv 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 /*
248  * user_from_uid()
249  *	caches the name (if any) for the uid. If noname clear, we always
250  *	return the the stored name (if valid or invalid match).
251  *	We use a simple hash table.
252  * Return
253  *	Pointer to stored name (or a empty string)
254  */
255 
256 const char *
257 user_from_uid(uid_t uid, int noname)
258 {
259 	struct passwd *pw;
260 	UIDC *ptr, **pptr;
261 
262 	if ((uidtb == NULL) && (uidtb_start() < 0))
263 		return (NULL);
264 
265 	/*
266 	 * see if we have this uid cached
267 	 */
268 	pptr = uidtb + (uid % UID_SZ);
269 	ptr = *pptr;
270 
271 	if ((ptr != NULL) && (ptr->valid > 0) && (ptr->uid == uid)) {
272 		/*
273 		 * have an entry for this uid
274 		 */
275 		if (!noname || (ptr->valid == VALID))
276 			return (ptr->name);
277 		return (NULL);
278 	}
279 
280 	/*
281 	 * No entry for this uid, we will add it
282 	 */
283 	if (!pwopn) {
284 		if (_pwcache_setpassent != NULL)
285 			(*_pwcache_setpassent)(1);
286 		++pwopn;
287 	}
288 
289 	if (ptr == NULL)
290 		*pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
291 
292 	if ((pw = (*_pwcache_getpwuid)(uid)) == NULL) {
293 		/*
294 		 * no match for this uid in the local password file
295 		 * a string that is the uid in numberic format
296 		 */
297 		if (ptr == NULL)
298 			return (NULL);
299 		ptr->uid = uid;
300 		(void)snprintf(ptr->name, UNMLEN, "%lu", (long) uid);
301 		ptr->valid = INVALID;
302 		if (noname)
303 			return (NULL);
304 	} else {
305 		/*
306 		 * there is an entry for this uid in the password file
307 		 */
308 		if (ptr == NULL)
309 			return (pw->pw_name);
310 		ptr->uid = uid;
311 		(void)strlcpy(ptr->name, pw->pw_name, UNMLEN);
312 		ptr->valid = VALID;
313 	}
314 	return (ptr->name);
315 }
316 
317 /*
318  * group_from_gid()
319  *	caches the name (if any) for the gid. If noname clear, we always
320  *	return the the stored name (if valid or invalid match).
321  *	We use a simple hash table.
322  * Return
323  *	Pointer to stored name (or a empty string)
324  */
325 
326 const char *
327 group_from_gid(gid_t gid, int noname)
328 {
329 	struct group *gr;
330 	GIDC *ptr, **pptr;
331 
332 	if ((gidtb == NULL) && (gidtb_start() < 0))
333 		return (NULL);
334 
335 	/*
336 	 * see if we have this gid cached
337 	 */
338 	pptr = gidtb + (gid % GID_SZ);
339 	ptr = *pptr;
340 
341 	if ((ptr != NULL) && (ptr->valid > 0) && (ptr->gid == gid)) {
342 		/*
343 		 * have an entry for this gid
344 		 */
345 		if (!noname || (ptr->valid == VALID))
346 			return (ptr->name);
347 		return (NULL);
348 	}
349 
350 	/*
351 	 * No entry for this gid, we will add it
352 	 */
353 	if (!gropn) {
354 		if (_pwcache_setgroupent != NULL)
355 			(*_pwcache_setgroupent)(1);
356 		++gropn;
357 	}
358 
359 	if (ptr == NULL)
360 		*pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
361 
362 	if ((gr = (*_pwcache_getgrgid)(gid)) == NULL) {
363 		/*
364 		 * no match for this gid in the local group file, put in
365 		 * a string that is the gid in numberic format
366 		 */
367 		if (ptr == NULL)
368 			return (NULL);
369 		ptr->gid = gid;
370 		(void)snprintf(ptr->name, GNMLEN, "%lu", (long) gid);
371 		ptr->valid = INVALID;
372 		if (noname)
373 			return (NULL);
374 	} else {
375 		/*
376 		 * there is an entry for this group in the group file
377 		 */
378 		if (ptr == NULL)
379 			return (gr->gr_name);
380 		ptr->gid = gid;
381 		(void)strlcpy(ptr->name, gr->gr_name, GNMLEN);
382 		ptr->valid = VALID;
383 	}
384 	return (ptr->name);
385 }
386 
387 /*
388  * uid_from_user()
389  *	caches the uid for a given user name. We use a simple hash table.
390  * Return
391  *	the uid (if any) for a user name, or a -1 if no match can be found
392  */
393 
394 int
395 uid_from_user(const char *name, uid_t *uid)
396 {
397 	struct passwd *pw;
398 	UIDC *ptr, **pptr;
399 	size_t namelen;
400 
401 	/*
402 	 * return -1 for mangled names
403 	 */
404 	if (name == NULL || ((namelen = strlen(name)) == 0))
405 		return (-1);
406 	if ((usrtb == NULL) && (usrtb_start() < 0))
407 		return (-1);
408 
409 	/*
410 	 * look up in hash table, if found and valid return the uid,
411 	 * if found and invalid, return a -1
412 	 */
413 	pptr = usrtb + st_hash(name, namelen, UNM_SZ);
414 	ptr = *pptr;
415 
416 	if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
417 		if (ptr->valid == INVALID)
418 			return (-1);
419 		*uid = ptr->uid;
420 		return (0);
421 	}
422 
423 	if (!pwopn) {
424 		if (_pwcache_setpassent != NULL)
425 			(*_pwcache_setpassent)(1);
426 		++pwopn;
427 	}
428 
429 	if (ptr == NULL)
430 		*pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
431 
432 	/*
433 	 * no match, look it up, if no match store it as an invalid entry,
434 	 * or store the matching uid
435 	 */
436 	if (ptr == NULL) {
437 		if ((pw = (*_pwcache_getpwnam)(name)) == NULL)
438 			return (-1);
439 		*uid = pw->pw_uid;
440 		return (0);
441 	}
442 	(void)strlcpy(ptr->name, name, UNMLEN);
443 	if ((pw = (*_pwcache_getpwnam)(name)) == NULL) {
444 		ptr->valid = INVALID;
445 		return (-1);
446 	}
447 	ptr->valid = VALID;
448 	*uid = ptr->uid = pw->pw_uid;
449 	return (0);
450 }
451 
452 /*
453  * gid_from_group()
454  *	caches the gid for a given group name. We use a simple hash table.
455  * Return
456  *	the gid (if any) for a group name, or a -1 if no match can be found
457  */
458 
459 int
460 gid_from_group(const char *name, gid_t *gid)
461 {
462 	struct group *gr;
463 	GIDC *ptr, **pptr;
464 	size_t namelen;
465 
466 	/*
467 	 * return -1 for mangled names
468 	 */
469 	if (name == NULL || ((namelen = strlen(name)) == 0))
470 		return (-1);
471 	if ((grptb == NULL) && (grptb_start() < 0))
472 		return (-1);
473 
474 	/*
475 	 * look up in hash table, if found and valid return the uid,
476 	 * if found and invalid, return a -1
477 	 */
478 	pptr = grptb + st_hash(name, namelen, GID_SZ);
479 	ptr = *pptr;
480 
481 	if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
482 		if (ptr->valid == INVALID)
483 			return (-1);
484 		*gid = ptr->gid;
485 		return (0);
486 	}
487 
488 	if (!gropn) {
489 		if (_pwcache_setgroupent != NULL)
490 			(*_pwcache_setgroupent)(1);
491 		++gropn;
492 	}
493 
494 	if (ptr == NULL)
495 		*pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
496 
497 	/*
498 	 * no match, look it up, if no match store it as an invalid entry,
499 	 * or store the matching gid
500 	 */
501 	if (ptr == NULL) {
502 		if ((gr = (*_pwcache_getgrnam)(name)) == NULL)
503 			return (-1);
504 		*gid = gr->gr_gid;
505 		return (0);
506 	}
507 
508 	(void)strlcpy(ptr->name, name, GNMLEN);
509 	if ((gr = (*_pwcache_getgrnam)(name)) == NULL) {
510 		ptr->valid = INVALID;
511 		return (-1);
512 	}
513 	ptr->valid = VALID;
514 	*gid = ptr->gid = gr->gr_gid;
515 	return (0);
516 }
517 
518 #define FLUSHTB(arr, len, fail)				\
519 	do {						\
520 		if (arr != NULL) {			\
521 			for (i = 0; i < len; i++)	\
522 				if (arr[i] != NULL)	\
523 					free(arr[i]);	\
524 			arr = NULL;			\
525 		}					\
526 		fail = 0;				\
527 	} while (/* CONSTCOND */0);
528 
529 int
530 pwcache_userdb(
531 	int		(*a_setpassent)(int),
532 	void		(*a_endpwent)(void),
533 	struct passwd *	(*a_getpwnam)(const char *),
534 	struct passwd *	(*a_getpwuid)(uid_t))
535 {
536 	int i;
537 
538 		/* a_setpassent and a_endpwent may be NULL */
539 	if (a_getpwnam == NULL || a_getpwuid == NULL)
540 		return (-1);
541 
542 	if (_pwcache_endpwent != NULL)
543 		(*_pwcache_endpwent)();
544 	FLUSHTB(uidtb, UID_SZ, uidtb_fail);
545 	FLUSHTB(usrtb, UNM_SZ, usrtb_fail);
546 	pwopn = 0;
547 	_pwcache_setpassent = a_setpassent;
548 	_pwcache_endpwent = a_endpwent;
549 	_pwcache_getpwnam = a_getpwnam;
550 	_pwcache_getpwuid = a_getpwuid;
551 
552 	return (0);
553 }
554 
555 int
556 pwcache_groupdb(
557 	int		(*a_setgroupent)(int),
558 	void		(*a_endgrent)(void),
559 	struct group *	(*a_getgrnam)(const char *),
560 	struct group *	(*a_getgrgid)(gid_t))
561 {
562 	int i;
563 
564 		/* a_setgroupent and a_endgrent may be NULL */
565 	if (a_getgrnam == NULL || a_getgrgid == NULL)
566 		return (-1);
567 
568 	if (_pwcache_endgrent != NULL)
569 		(*_pwcache_endgrent)();
570 	FLUSHTB(gidtb, GID_SZ, gidtb_fail);
571 	FLUSHTB(grptb, GNM_SZ, grptb_fail);
572 	gropn = 0;
573 	_pwcache_setgroupent = a_setgroupent;
574 	_pwcache_endgrent = a_endgrent;
575 	_pwcache_getgrnam = a_getgrnam;
576 	_pwcache_getgrgid = a_getgrgid;
577 
578 	return (0);
579 }
580 
581 
582 #ifdef TEST_PWCACHE
583 
584 struct passwd *
585 test_getpwnam(const char *name)
586 {
587 	static struct passwd foo;
588 
589 	memset(&foo, 0, sizeof(foo));
590 	if (strcmp(name, "toor") == 0) {
591 		foo.pw_uid = 666;
592 		return &foo;
593 	}
594 	return (getpwnam(name));
595 }
596 
597 int
598 main(int argc, char *argv[])
599 {
600 	uid_t	u;
601 	int	r, i;
602 
603 	printf("pass 1 (default userdb)\n");
604 	for (i = 1; i < argc; i++) {
605 		printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
606 		    i, pwopn, usrtb_fail, usrtb);
607 		r = uid_from_user(argv[i], &u);
608 		if (r == -1)
609 			printf("  uid_from_user %s: failed\n", argv[i]);
610 		else
611 			printf("  uid_from_user %s: %d\n", argv[i], u);
612 	}
613 	printf("pass 1 finish: pwopn %d usrtb_fail %d usrtb %p\n",
614 		    pwopn, usrtb_fail, usrtb);
615 
616 	puts("");
617 	printf("pass 2 (replacement userdb)\n");
618 	printf("pwcache_userdb returned %d\n",
619 	    pwcache_userdb(setpassent, test_getpwnam, getpwuid));
620 	printf("pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb);
621 
622 	for (i = 1; i < argc; i++) {
623 		printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
624 		    i, pwopn, usrtb_fail, usrtb);
625 		u = -1;
626 		r = uid_from_user(argv[i], &u);
627 		if (r == -1)
628 			printf("  uid_from_user %s: failed\n", argv[i]);
629 		else
630 			printf("  uid_from_user %s: %d\n", argv[i], u);
631 	}
632 	printf("pass 2 finish: pwopn %d usrtb_fail %d usrtb %p\n",
633 		    pwopn, usrtb_fail, usrtb);
634 
635 	puts("");
636 	printf("pass 3 (null pointers)\n");
637 	printf("pwcache_userdb returned %d\n",
638 	    pwcache_userdb(NULL, NULL, NULL));
639 
640 	return (0);
641 }
642 #endif	/* TEST_PWCACHE */
643 #endif	/* !HAVE_PWCACHE_USERDB */
644