xref: /netbsd-src/lib/libc/gen/pwcache.c (revision 0dd5877adce57db949b16ae963e5a6831cccdfb6)
1 /*	$NetBSD: pwcache.c,v 1.20 2002/01/29 10:20:30 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 #if HAVE_CONFIG_H
74 #include "config.h"
75 #endif
76 
77 #include <sys/cdefs.h>
78 #if defined(LIBC_SCCS) && !defined(lint)
79 #if 0
80 static char sccsid[] = "@(#)cache.c	8.1 (Berkeley) 5/31/93";
81 #else
82 __RCSID("$NetBSD: pwcache.c,v 1.20 2002/01/29 10:20:30 tv Exp $");
83 #endif
84 #endif /* LIBC_SCCS and not lint */
85 
86 #include "namespace.h"
87 
88 #include <sys/types.h>
89 #include <sys/param.h>
90 
91 #include <assert.h>
92 #include <grp.h>
93 #include <pwd.h>
94 #include <stdio.h>
95 #include <stdlib.h>
96 #include <string.h>
97 #include <unistd.h>
98 
99 #ifdef __weak_alias
100 __weak_alias(user_from_uid,_user_from_uid)
101 __weak_alias(group_from_gid,_group_from_gid)
102 __weak_alias(pwcache_userdb,_pwcache_userdb)
103 __weak_alias(pwcache_groupdb,_pwcache_groupdb)
104 #endif
105 
106 #if !HAVE_PWCACHE_USERDB
107 #include "pwcache.h"
108 
109 /*
110  * routines that control user, group, uid and gid caches (for the archive
111  * member print routine).
112  * IMPORTANT:
113  * these routines cache BOTH hits and misses, a major performance improvement
114  */
115 
116 /*
117  * function pointers to various name lookup routines.
118  * these may be changed as necessary.
119  */
120 static	int		(*_pwcache_setgroupent)(int)		= setgroupent;
121 static	void		(*_pwcache_endgrent)(void)		= endgrent;
122 static	struct group *	(*_pwcache_getgrnam)(const char *)	= getgrnam;
123 static	struct group *	(*_pwcache_getgrgid)(gid_t)		= getgrgid;
124 static	int		(*_pwcache_setpassent)(int)		= setpassent;
125 static	void		(*_pwcache_endpwent)(void)		= endpwent;
126 static	struct passwd *	(*_pwcache_getpwnam)(const char *)	= getpwnam;
127 static	struct passwd *	(*_pwcache_getpwuid)(uid_t)		= getpwuid;
128 
129 /*
130  * internal state
131  */
132 static	int	pwopn;		/* is password file open */
133 static	int	gropn;		/* is group file open */
134 static	UIDC	**uidtb;	/* uid to name cache */
135 static	GIDC	**gidtb;	/* gid to name cache */
136 static	UIDC	**usrtb;	/* user name to uid cache */
137 static	GIDC	**grptb;	/* group name to gid cache */
138 
139 static	int	uidtb_fail;	/* uidtb_start() failed ? */
140 static	int	gidtb_fail;	/* gidtb_start() failed ? */
141 static	int	usrtb_fail;	/* usrtb_start() failed ? */
142 static	int	grptb_fail;	/* grptb_start() failed ? */
143 
144 
145 static	u_int	st_hash(const char *, size_t, int);
146 static	int	uidtb_start(void);
147 static	int	gidtb_start(void);
148 static	int	usrtb_start(void);
149 static	int	grptb_start(void);
150 
151 
152 static u_int
153 st_hash(const char *name, size_t len, int tabsz)
154 {
155 	u_int key = 0;
156 
157 	_DIAGASSERT(name != NULL);
158 
159 	while (len--) {
160 		key += *name++;
161 		key = (key << 8) | (key >> 24);
162 	}
163 
164 	return (key % tabsz);
165 }
166 
167 /*
168  * uidtb_start
169  *	creates an an empty uidtb
170  * Return:
171  *	0 if ok, -1 otherwise
172  */
173 static int
174 uidtb_start(void)
175 {
176 
177 	if (uidtb != NULL)
178 		return (0);
179 	if (uidtb_fail)
180 		return (-1);
181 	if ((uidtb = (UIDC **)calloc(UID_SZ, sizeof(UIDC *))) == NULL) {
182 		++uidtb_fail;
183 		return (-1);
184 	}
185 	return (0);
186 }
187 
188 /*
189  * gidtb_start
190  *	creates an an empty gidtb
191  * Return:
192  *	0 if ok, -1 otherwise
193  */
194 static int
195 gidtb_start(void)
196 {
197 
198 	if (gidtb != NULL)
199 		return (0);
200 	if (gidtb_fail)
201 		return (-1);
202 	if ((gidtb = (GIDC **)calloc(GID_SZ, sizeof(GIDC *))) == NULL) {
203 		++gidtb_fail;
204 		return (-1);
205 	}
206 	return (0);
207 }
208 
209 /*
210  * usrtb_start
211  *	creates an an empty usrtb
212  * Return:
213  *	0 if ok, -1 otherwise
214  */
215 static int
216 usrtb_start(void)
217 {
218 
219 	if (usrtb != NULL)
220 		return (0);
221 	if (usrtb_fail)
222 		return (-1);
223 	if ((usrtb = (UIDC **)calloc(UNM_SZ, sizeof(UIDC *))) == NULL) {
224 		++usrtb_fail;
225 		return (-1);
226 	}
227 	return (0);
228 }
229 
230 /*
231  * grptb_start
232  *	creates an an empty grptb
233  * Return:
234  *	0 if ok, -1 otherwise
235  */
236 static int
237 grptb_start(void)
238 {
239 
240 	if (grptb != NULL)
241 		return (0);
242 	if (grptb_fail)
243 		return (-1);
244 	if ((grptb = (GIDC **)calloc(GNM_SZ, sizeof(GIDC *))) == NULL) {
245 		++grptb_fail;
246 		return (-1);
247 	}
248 	return (0);
249 }
250 
251 /*
252  * user_from_uid()
253  *	caches the name (if any) for the uid. If noname clear, we always
254  *	return the the stored name (if valid or invalid match).
255  *	We use a simple hash table.
256  * Return
257  *	Pointer to stored name (or a empty string)
258  */
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 numberic 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 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 
330 const char *
331 group_from_gid(gid_t gid, int noname)
332 {
333 	struct group *gr;
334 	GIDC *ptr, **pptr;
335 
336 	if ((gidtb == NULL) && (gidtb_start() < 0))
337 		return (NULL);
338 
339 	/*
340 	 * see if we have this gid cached
341 	 */
342 	pptr = gidtb + (gid % GID_SZ);
343 	ptr = *pptr;
344 
345 	if ((ptr != NULL) && (ptr->valid > 0) && (ptr->gid == gid)) {
346 		/*
347 		 * have an entry for this gid
348 		 */
349 		if (!noname || (ptr->valid == VALID))
350 			return (ptr->name);
351 		return (NULL);
352 	}
353 
354 	/*
355 	 * No entry for this gid, we will add it
356 	 */
357 	if (!gropn) {
358 		if (_pwcache_setgroupent != NULL)
359 			(*_pwcache_setgroupent)(1);
360 		++gropn;
361 	}
362 
363 	if (ptr == NULL)
364 		*pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
365 
366 	if ((gr = (*_pwcache_getgrgid)(gid)) == NULL) {
367 		/*
368 		 * no match for this gid in the local group file, put in
369 		 * a string that is the gid in numberic format
370 		 */
371 		if (ptr == NULL)
372 			return (NULL);
373 		ptr->gid = gid;
374 		(void)snprintf(ptr->name, GNMLEN, "%lu", (long) gid);
375 		ptr->valid = INVALID;
376 		if (noname)
377 			return (NULL);
378 	} else {
379 		/*
380 		 * there is an entry for this group in the group file
381 		 */
382 		if (ptr == NULL)
383 			return (gr->gr_name);
384 		ptr->gid = gid;
385 		(void)strlcpy(ptr->name, gr->gr_name, GNMLEN);
386 		ptr->valid = VALID;
387 	}
388 	return (ptr->name);
389 }
390 
391 /*
392  * uid_from_user()
393  *	caches the uid for a given user name. We use a simple hash table.
394  * Return
395  *	the uid (if any) for a user name, or a -1 if no match can be found
396  */
397 
398 int
399 uid_from_user(const char *name, uid_t *uid)
400 {
401 	struct passwd *pw;
402 	UIDC *ptr, **pptr;
403 	size_t namelen;
404 
405 	/*
406 	 * return -1 for mangled names
407 	 */
408 	if (name == NULL || ((namelen = strlen(name)) == 0))
409 		return (-1);
410 	if ((usrtb == NULL) && (usrtb_start() < 0))
411 		return (-1);
412 
413 	/*
414 	 * look up in hash table, if found and valid return the uid,
415 	 * if found and invalid, return a -1
416 	 */
417 	pptr = usrtb + st_hash(name, namelen, UNM_SZ);
418 	ptr = *pptr;
419 
420 	if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
421 		if (ptr->valid == INVALID)
422 			return (-1);
423 		*uid = ptr->uid;
424 		return (0);
425 	}
426 
427 	if (!pwopn) {
428 		if (_pwcache_setpassent != NULL)
429 			(*_pwcache_setpassent)(1);
430 		++pwopn;
431 	}
432 
433 	if (ptr == NULL)
434 		*pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
435 
436 	/*
437 	 * no match, look it up, if no match store it as an invalid entry,
438 	 * or store the matching uid
439 	 */
440 	if (ptr == NULL) {
441 		if ((pw = (*_pwcache_getpwnam)(name)) == NULL)
442 			return (-1);
443 		*uid = pw->pw_uid;
444 		return (0);
445 	}
446 	(void)strlcpy(ptr->name, name, UNMLEN);
447 	if ((pw = (*_pwcache_getpwnam)(name)) == NULL) {
448 		ptr->valid = INVALID;
449 		return (-1);
450 	}
451 	ptr->valid = VALID;
452 	*uid = ptr->uid = pw->pw_uid;
453 	return (0);
454 }
455 
456 /*
457  * gid_from_group()
458  *	caches the gid for a given group name. We use a simple hash table.
459  * Return
460  *	the gid (if any) for a group name, or a -1 if no match can be found
461  */
462 
463 int
464 gid_from_group(const char *name, gid_t *gid)
465 {
466 	struct group *gr;
467 	GIDC *ptr, **pptr;
468 	size_t namelen;
469 
470 	/*
471 	 * return -1 for mangled names
472 	 */
473 	if (name == NULL || ((namelen = strlen(name)) == 0))
474 		return (-1);
475 	if ((grptb == NULL) && (grptb_start() < 0))
476 		return (-1);
477 
478 	/*
479 	 * look up in hash table, if found and valid return the uid,
480 	 * if found and invalid, return a -1
481 	 */
482 	pptr = grptb + st_hash(name, namelen, GID_SZ);
483 	ptr = *pptr;
484 
485 	if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
486 		if (ptr->valid == INVALID)
487 			return (-1);
488 		*gid = ptr->gid;
489 		return (0);
490 	}
491 
492 	if (!gropn) {
493 		if (_pwcache_setgroupent != NULL)
494 			(*_pwcache_setgroupent)(1);
495 		++gropn;
496 	}
497 
498 	if (ptr == NULL)
499 		*pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
500 
501 	/*
502 	 * no match, look it up, if no match store it as an invalid entry,
503 	 * or store the matching gid
504 	 */
505 	if (ptr == NULL) {
506 		if ((gr = (*_pwcache_getgrnam)(name)) == NULL)
507 			return (-1);
508 		*gid = gr->gr_gid;
509 		return (0);
510 	}
511 
512 	(void)strlcpy(ptr->name, name, GNMLEN);
513 	if ((gr = (*_pwcache_getgrnam)(name)) == NULL) {
514 		ptr->valid = INVALID;
515 		return (-1);
516 	}
517 	ptr->valid = VALID;
518 	*gid = ptr->gid = gr->gr_gid;
519 	return (0);
520 }
521 
522 #define FLUSHTB(arr, len, fail)				\
523 	do {						\
524 		if (arr != NULL) {			\
525 			for (i = 0; i < len; i++)	\
526 				if (arr[i] != NULL)	\
527 					free(arr[i]);	\
528 			arr = NULL;			\
529 		}					\
530 		fail = 0;				\
531 	} while (/* CONSTCOND */0);
532 
533 int
534 pwcache_userdb(
535 	int		(*a_setpassent)(int),
536 	void		(*a_endpwent)(void),
537 	struct passwd *	(*a_getpwnam)(const char *),
538 	struct passwd *	(*a_getpwuid)(uid_t))
539 {
540 	int i;
541 
542 		/* a_setpassent and a_endpwent may be NULL */
543 	if (a_getpwnam == NULL || a_getpwuid == NULL)
544 		return (-1);
545 
546 	if (_pwcache_endpwent != NULL)
547 		(*_pwcache_endpwent)();
548 	FLUSHTB(uidtb, UID_SZ, uidtb_fail);
549 	FLUSHTB(usrtb, UNM_SZ, usrtb_fail);
550 	pwopn = 0;
551 	_pwcache_setpassent = a_setpassent;
552 	_pwcache_endpwent = a_endpwent;
553 	_pwcache_getpwnam = a_getpwnam;
554 	_pwcache_getpwuid = a_getpwuid;
555 
556 	return (0);
557 }
558 
559 int
560 pwcache_groupdb(
561 	int		(*a_setgroupent)(int),
562 	void		(*a_endgrent)(void),
563 	struct group *	(*a_getgrnam)(const char *),
564 	struct group *	(*a_getgrgid)(gid_t))
565 {
566 	int i;
567 
568 		/* a_setgroupent and a_endgrent may be NULL */
569 	if (a_getgrnam == NULL || a_getgrgid == NULL)
570 		return (-1);
571 
572 	if (_pwcache_endgrent != NULL)
573 		(*_pwcache_endgrent)();
574 	FLUSHTB(gidtb, GID_SZ, gidtb_fail);
575 	FLUSHTB(grptb, GNM_SZ, grptb_fail);
576 	gropn = 0;
577 	_pwcache_setgroupent = a_setgroupent;
578 	_pwcache_endgrent = a_endgrent;
579 	_pwcache_getgrnam = a_getgrnam;
580 	_pwcache_getgrgid = a_getgrgid;
581 
582 	return (0);
583 }
584 
585 
586 #ifdef TEST_PWCACHE
587 
588 struct passwd *
589 test_getpwnam(const char *name)
590 {
591 	static struct passwd foo;
592 
593 	memset(&foo, 0, sizeof(foo));
594 	if (strcmp(name, "toor") == 0) {
595 		foo.pw_uid = 666;
596 		return &foo;
597 	}
598 	return (getpwnam(name));
599 }
600 
601 int
602 main(int argc, char *argv[])
603 {
604 	uid_t	u;
605 	int	r, i;
606 
607 	printf("pass 1 (default userdb)\n");
608 	for (i = 1; i < argc; i++) {
609 		printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
610 		    i, pwopn, usrtb_fail, usrtb);
611 		r = uid_from_user(argv[i], &u);
612 		if (r == -1)
613 			printf("  uid_from_user %s: failed\n", argv[i]);
614 		else
615 			printf("  uid_from_user %s: %d\n", argv[i], u);
616 	}
617 	printf("pass 1 finish: pwopn %d usrtb_fail %d usrtb %p\n",
618 		    pwopn, usrtb_fail, usrtb);
619 
620 	puts("");
621 	printf("pass 2 (replacement userdb)\n");
622 	printf("pwcache_userdb returned %d\n",
623 	    pwcache_userdb(setpassent, test_getpwnam, getpwuid));
624 	printf("pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb);
625 
626 	for (i = 1; i < argc; i++) {
627 		printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
628 		    i, pwopn, usrtb_fail, usrtb);
629 		u = -1;
630 		r = uid_from_user(argv[i], &u);
631 		if (r == -1)
632 			printf("  uid_from_user %s: failed\n", argv[i]);
633 		else
634 			printf("  uid_from_user %s: %d\n", argv[i], u);
635 	}
636 	printf("pass 2 finish: pwopn %d usrtb_fail %d usrtb %p\n",
637 		    pwopn, usrtb_fail, usrtb);
638 
639 	puts("");
640 	printf("pass 3 (null pointers)\n");
641 	printf("pwcache_userdb returned %d\n",
642 	    pwcache_userdb(NULL, NULL, NULL));
643 
644 	return (0);
645 }
646 #endif	/* TEST_PWCACHE */
647 #endif	/* !HAVE_PWCACHE_USERDB */
648