procps/proc/pwcache.c

78 lines
1.8 KiB
C
Raw Normal View History

// Copyright (C) 1992-1998 by Michael K. Johnson, johnsonm@redhat.com
// Note: most likely none of his code remains
//
// Copyright 2002, Albert Cahalan
//
// This file is placed under the conditions of the GNU Library
// General Public License, version 2, or any later version.
// See file COPYING for information on distribution conditions.
2002-02-02 04:17:29 +05:30
#include <stdio.h>
2004-08-10 10:00:27 +05:30
#include <string.h>
2002-02-02 04:17:29 +05:30
#include <sys/types.h>
#include <stdlib.h>
#include <pwd.h>
2002-12-09 12:30:07 +05:30
#include "alloc.h"
#include "pwcache.h"
2002-02-02 04:17:29 +05:30
#include <grp.h>
2002-10-14 02:49:26 +05:30
// might as well fill cache lines... else we waste memory anyway
2002-12-09 12:30:07 +05:30
#define HASHSIZE 64 /* power of 2 */
2002-02-02 04:17:29 +05:30
#define HASH(x) ((x) & (HASHSIZE - 1))
static struct pwbuf {
2002-10-14 02:49:26 +05:30
struct pwbuf *next;
2002-02-02 04:17:29 +05:30
uid_t uid;
2004-07-21 05:01:12 +05:30
char name[P_G_SZ];
2002-02-02 04:17:29 +05:30
} *pwhash[HASHSIZE];
2004-07-21 05:01:12 +05:30
char *user_from_uid(uid_t uid) {
2002-02-02 04:17:29 +05:30
struct pwbuf **p;
struct passwd *pw;
p = &pwhash[HASH(uid)];
while (*p) {
if ((*p)->uid == uid)
return((*p)->name);
p = &(*p)->next;
}
*p = (struct pwbuf *) xmalloc(sizeof(struct pwbuf));
(*p)->uid = uid;
2004-07-21 04:21:22 +05:30
pw = getpwuid(uid);
2004-08-10 10:17:07 +05:30
if(!pw || strlen(pw->pw_name) >= P_G_SZ)
2004-07-21 05:01:12 +05:30
sprintf((*p)->name, "%u", uid);
2002-02-02 04:17:29 +05:30
else
2004-07-21 05:01:12 +05:30
strcpy((*p)->name, pw->pw_name);
2004-08-10 10:17:07 +05:30
2002-02-02 04:17:29 +05:30
(*p)->next = NULL;
return((*p)->name);
}
static struct grpbuf {
2002-10-14 02:49:26 +05:30
struct grpbuf *next;
2002-02-02 04:17:29 +05:30
gid_t gid;
2004-07-21 05:01:12 +05:30
char name[P_G_SZ];
2002-02-02 04:17:29 +05:30
} *grphash[HASHSIZE];
2004-07-21 05:01:12 +05:30
char *group_from_gid(gid_t gid) {
2002-02-02 04:17:29 +05:30
struct grpbuf **g;
struct group *gr;
g = &grphash[HASH(gid)];
while (*g) {
2004-07-21 05:01:12 +05:30
if ((*g)->gid == gid)
return((*g)->name);
g = &(*g)->next;
2002-02-02 04:17:29 +05:30
}
*g = (struct grpbuf *) xmalloc(sizeof(struct grpbuf));
2002-02-02 04:17:29 +05:30
(*g)->gid = gid;
2004-07-21 04:21:22 +05:30
gr = getgrgid(gid);
2004-08-10 10:17:07 +05:30
if (!gr || strlen(gr->gr_name) >= P_G_SZ)
2004-07-21 05:01:12 +05:30
sprintf((*g)->name, "%u", gid);
2002-02-02 04:17:29 +05:30
else
2004-07-21 05:01:12 +05:30
strcpy((*g)->name, gr->gr_name);
2002-02-02 04:17:29 +05:30
(*g)->next = NULL;
return((*g)->name);
}