xref: /csrg-svn/lib/libc/gen/pwcache.c (revision 40281)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #if defined(LIBC_SCCS) && !defined(lint)
19 static char sccsid[] = "@(#)pwcache.c	5.2 (Berkeley) 03/05/90";
20 #endif /* LIBC_SCCS and not lint */
21 
22 #include <sys/types.h>
23 #include <utmp.h>
24 #include <pwd.h>
25 #include <grp.h>
26 
27 #define	NCACHE	64			/* power of 2 */
28 #define	MASK	NCACHE - 1		/* bits to store with */
29 
30 static	int pwopen = 0;
31 static	int gropen = 0;
32 
33 char *
34 user_from_uid(uid)
35 	uid_t uid;
36 {
37 	static struct ncache {
38 		uid_t	uid;
39 		char	name[UT_NAMESIZE + 1];
40 	} c_uid[NCACHE];
41 	static char nbuf[15];		/* 32 bits == 10 digits */
42 	register struct passwd *pw;
43 	register struct ncache *cp;
44 
45 	cp = c_uid + (uid & MASK);
46 	if (cp->uid != uid || !*cp->name) {
47 		if (pwopen == 0) {
48 			setpassent(1);
49 			pwopen++;
50 		}
51 		/* if can't find owner, use user id instead */
52 		if (!(pw = getpwuid(uid))) {
53 			(void)sprintf(nbuf, "%u", uid);
54 			return(nbuf);
55 		}
56 		cp->uid = uid;
57 		(void)strncpy(cp->name, pw->pw_name, UT_NAMESIZE);
58 		cp->name[UT_NAMESIZE] = '\0';
59 	}
60 	return(cp->name);
61 }
62 
63 char *
64 group_from_gid(gid)
65 	gid_t gid;
66 {
67 	static struct ncache {
68 		gid_t	gid;
69 		char	name[UT_NAMESIZE];
70 	} c_gid[NCACHE];
71 	static char nbuf[15];		/* 32 bits == 10 digits */
72 	register struct group *gr;
73 	register struct ncache *cp;
74 
75 	cp = c_gid + (gid & MASK);
76 	if (cp->gid != gid || !*cp->name) {
77 		if (gropen == 0) {
78 			setgroupent(1);
79 			gropen++;
80 		}
81 		/* if can't find group, use group id instead */
82 		if (!(gr = getgrgid(gid))) {
83 			(void)sprintf(nbuf, "%u", gid);
84 			return(nbuf);
85 		}
86 		cp->gid = gid;
87 		(void)strncpy(cp->name, gr->gr_name, UT_NAMESIZE);
88 		cp->name[UT_NAMESIZE] = '\0';
89 	}
90 	return(cp->name);
91 }
92