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.3 (Berkeley) 03/13/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 #include <stdio.h> 27 28 #define NCACHE 64 /* power of 2 */ 29 #define MASK NCACHE - 1 /* bits to store with */ 30 31 static int pwopen = 0; 32 static int gropen = 0; 33 34 char * 35 user_from_uid(uid, nouser) 36 uid_t uid; 37 int nouser; 38 { 39 static struct ncache { 40 uid_t uid; 41 char name[UT_NAMESIZE + 1]; 42 } c_uid[NCACHE]; 43 static char nbuf[15]; /* 32 bits == 10 digits */ 44 register struct passwd *pw; 45 register struct ncache *cp; 46 47 cp = c_uid + (uid & MASK); 48 if (cp->uid != uid || !*cp->name) { 49 if (pwopen == 0) { 50 setpassent(1); 51 pwopen++; 52 } 53 if (!(pw = getpwuid(uid))) { 54 if (nouser) 55 return((char *)NULL); 56 (void)sprintf(nbuf, "%u", uid); 57 return(nbuf); 58 } 59 cp->uid = uid; 60 (void)strncpy(cp->name, pw->pw_name, UT_NAMESIZE); 61 cp->name[UT_NAMESIZE] = '\0'; 62 } 63 return(cp->name); 64 } 65 66 char * 67 group_from_gid(gid, nogroup) 68 gid_t gid; 69 int nogroup; 70 { 71 static struct ncache { 72 gid_t gid; 73 char name[UT_NAMESIZE]; 74 } c_gid[NCACHE]; 75 static char nbuf[15]; /* 32 bits == 10 digits */ 76 register struct group *gr; 77 register struct ncache *cp; 78 79 cp = c_gid + (gid & MASK); 80 if (cp->gid != gid || !*cp->name) { 81 if (gropen == 0) { 82 setgroupent(1); 83 gropen++; 84 } 85 if (!(gr = getgrgid(gid))) { 86 if (nogroup) 87 return((char *)NULL); 88 (void)sprintf(nbuf, "%u", gid); 89 return(nbuf); 90 } 91 cp->gid = gid; 92 (void)strncpy(cp->name, gr->gr_name, UT_NAMESIZE); 93 cp->name[UT_NAMESIZE] = '\0'; 94 } 95 return(cp->name); 96 } 97