1 /*
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * %sccs.include.redist.c%
6 */
7
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)pwcache.c 8.1 (Berkeley) 06/04/93";
10 #endif /* LIBC_SCCS and not lint */
11
12 #include <sys/types.h>
13
14 #include <grp.h>
15 #include <pwd.h>
16 #include <stdio.h>
17 #include <utmp.h>
18
19 #define NCACHE 64 /* power of 2 */
20 #define MASK NCACHE - 1 /* bits to store with */
21
22 char *
user_from_uid(uid,nouser)23 user_from_uid(uid, nouser)
24 uid_t uid;
25 int nouser;
26 {
27 static struct ncache {
28 uid_t uid;
29 char name[UT_NAMESIZE + 1];
30 } c_uid[NCACHE];
31 static int pwopen;
32 static char nbuf[15]; /* 32 bits == 10 digits */
33 register struct passwd *pw;
34 register struct ncache *cp;
35
36 cp = c_uid + (uid & MASK);
37 if (cp->uid != uid || !*cp->name) {
38 if (pwopen == 0) {
39 setpassent(1);
40 pwopen = 1;
41 }
42 if ((pw = getpwuid(uid)) == NULL) {
43 if (nouser)
44 return (NULL);
45 (void)snprintf(nbuf, sizeof(nbuf), "%u", uid);
46 return (nbuf);
47 }
48 cp->uid = uid;
49 (void)strncpy(cp->name, pw->pw_name, UT_NAMESIZE);
50 cp->name[UT_NAMESIZE] = '\0';
51 }
52 return (cp->name);
53 }
54
55 char *
group_from_gid(gid,nogroup)56 group_from_gid(gid, nogroup)
57 gid_t gid;
58 int nogroup;
59 {
60 static struct ncache {
61 gid_t gid;
62 char name[UT_NAMESIZE + 1];
63 } c_gid[NCACHE];
64 static int gropen;
65 static char nbuf[15]; /* 32 bits == 10 digits */
66 struct group *gr;
67 struct ncache *cp;
68
69 cp = c_gid + (gid & MASK);
70 if (cp->gid != gid || !*cp->name) {
71 if (gropen == 0) {
72 setgroupent(1);
73 gropen = 1;
74 }
75 if ((gr = getgrgid(gid)) == NULL) {
76 if (nogroup)
77 return (NULL);
78 (void)snprintf(nbuf, sizeof(nbuf), "%u", gid);
79 return (nbuf);
80 }
81 cp->gid = gid;
82 (void)strncpy(cp->name, gr->gr_name, UT_NAMESIZE);
83 cp->name[UT_NAMESIZE] = '\0';
84 }
85 return (cp->name);
86 }
87