xref: /csrg-svn/lib/libc/gen/pwcache.c (revision 40263)
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.1 (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 char *
31 user_from_uid(uid)
32 	uid_t uid;
33 {
34 	static struct ncache {
35 		uid_t	uid;
36 		char	name[UT_NAMESIZE + 1];
37 	} c_uid[NCACHE];
38 	static char nbuf[15];		/* 32 bits == 10 digits */
39 	register struct passwd *pw;
40 	register struct ncache *cp;
41 
42 	cp = c_uid + (uid & MASK);
43 	if (cp->uid != uid || !*cp->name) {
44 		/* if can't find owner, use user id instead */
45 		if (!(pw = getpwuid(uid))) {
46 			(void)sprintf(nbuf, "%u", uid);
47 			return(nbuf);
48 		}
49 		cp->uid = uid;
50 		(void)strncpy(cp->name, pw->pw_name, UT_NAMESIZE);
51 		cp->name[UT_NAMESIZE] = '\0';
52 	}
53 	return(cp->name);
54 }
55 
56 char *
57 group_from_gid(gid)
58 	gid_t gid;
59 {
60 	static struct ncache {
61 		gid_t	gid;
62 		char	name[UT_NAMESIZE];
63 	} c_gid[NCACHE];
64 	static char nbuf[15];		/* 32 bits == 10 digits */
65 	register struct group *gr;
66 	register struct ncache *cp;
67 
68 	cp = c_gid + (gid & MASK);
69 	if (cp->gid != gid || !*cp->name) {
70 		/* if can't find group, use group id instead */
71 		if (!(gr = getgrgid(gid))) {
72 			(void)sprintf(nbuf, "%u", gid);
73 			return(nbuf);
74 		}
75 		cp->gid = gid;
76 		(void)strncpy(cp->name, gr->gr_name, UT_NAMESIZE);
77 		cp->name[UT_NAMESIZE] = '\0';
78 	}
79 	return(cp->name);
80 }
81