#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utmp.h>
#define NCACHE 64
#define MASK (NCACHE - 1)
char *
user_from_uid(uid, nouser)
uid_t uid;
int nouser;
{
static struct ncache {
uid_t uid;
char name[UT_NAMESIZE + 1];
} *c_uid[NCACHE];
static int pwopen;
static char nbuf[15];
register struct passwd *pw;
register struct ncache **cp;
cp = &c_uid[uid & MASK];
if (*cp == NULL || (*cp)->uid != uid || !*(*cp)->name) {
if (pwopen == 0) {
setpassent(1);
pwopen = 1;
}
if ((pw = getpwuid(uid)) == NULL) {
err:
if (nouser)
return (NULL);
(void)snprintf(nbuf, sizeof(nbuf), "%u", uid);
return (nbuf);
}
if (*cp == NULL) {
*cp = malloc(sizeof(struct ncache));
if (*cp == NULL)
goto err;
}
(*cp)->uid = uid;
(void)strncpy((*cp)->name, pw->pw_name, UT_NAMESIZE);
(*cp)->name[UT_NAMESIZE] = '\0';
}
return ((*cp)->name);
}
char *
group_from_gid(gid, nogroup)
gid_t gid;
int nogroup;
{
static struct ncache {
gid_t gid;
char name[UT_NAMESIZE + 1];
} *c_gid[NCACHE];
static int gropen;
static char nbuf[15];
struct group *gr;
struct ncache **cp = NULL;
cp = &c_gid[gid & MASK];
if (*cp == NULL || (*cp)->gid != gid || !*(*cp)->name) {
if (gropen == 0) {
setgroupent(1);
gropen = 1;
}
if ((gr = getgrgid(gid)) == NULL) {
err:
if (nogroup)
return (NULL);
(void)snprintf(nbuf, sizeof(nbuf), "%u", gid);
return (nbuf);
}
if (*cp == NULL) {
*cp = malloc(sizeof(struct ncache));
if (*cp == NULL)
goto err;
}
(*cp)->gid = gid;
(void)strncpy((*cp)->name, gr->gr_name, UT_NAMESIZE);
(*cp)->name[UT_NAMESIZE] = '\0';
}
return ((*cp)->name);
}