Updated with Tizen:Base source codes
[external/procps.git] / proc / pwcache.c
1 // Copyright (C) 1992-1998 by Michael K. Johnson, johnsonm@redhat.com
2 // Note: most likely none of his code remains
3 //
4 // Copyright 2002, Albert Cahalan
5 //
6 // This file is placed under the conditions of the GNU Library
7 // General Public License, version 2, or any later version.
8 // See file COPYING for information on distribution conditions.
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <stdlib.h>
14 #include <pwd.h>
15 #include "alloc.h"
16 #include "pwcache.h"
17 #include <grp.h>
18
19 // might as well fill cache lines... else we waste memory anyway
20
21 #define HASHSIZE        64              /* power of 2 */
22 #define HASH(x)         ((x) & (HASHSIZE - 1))
23
24 static struct pwbuf {
25     struct pwbuf *next;
26     uid_t uid;
27     char name[P_G_SZ];
28 } *pwhash[HASHSIZE];
29
30 char *user_from_uid(uid_t uid) {
31     struct pwbuf **p;
32     struct passwd *pw;
33
34     p = &pwhash[HASH(uid)];
35     while (*p) {
36         if ((*p)->uid == uid)
37             return((*p)->name);
38         p = &(*p)->next;
39     }
40     *p = (struct pwbuf *) xmalloc(sizeof(struct pwbuf));
41     (*p)->uid = uid;
42     pw = getpwuid(uid);
43     if(!pw || strlen(pw->pw_name) >= P_G_SZ)
44         sprintf((*p)->name, "%u", uid);
45     else
46         strcpy((*p)->name, pw->pw_name);
47
48     (*p)->next = NULL;
49     return((*p)->name);
50 }
51
52 static struct grpbuf {
53     struct grpbuf *next;
54     gid_t gid;
55     char name[P_G_SZ];
56 } *grphash[HASHSIZE];
57
58 char *group_from_gid(gid_t gid) {
59     struct grpbuf **g;
60     struct group *gr;
61
62     g = &grphash[HASH(gid)];
63     while (*g) {
64         if ((*g)->gid == gid)
65             return((*g)->name);
66         g = &(*g)->next;
67     }
68     *g = (struct grpbuf *) malloc(sizeof(struct grpbuf));
69     (*g)->gid = gid;
70     gr = getgrgid(gid);
71     if (!gr || strlen(gr->gr_name) >= P_G_SZ)
72         sprintf((*g)->name, "%u", gid);
73     else
74         strcpy((*g)->name, gr->gr_name);
75     (*g)->next = NULL;
76     return((*g)->name);
77 }