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[] = "@(#)getgrent.c 8.1 (Berkeley) 06/04/93"; 10 #endif /* LIBC_SCCS and not lint */ 11 12 #include <sys/types.h> 13 #include <stdio.h> 14 #include <stdlib.h> 15 #include <grp.h> 16 17 static FILE *_gr_fp; 18 static struct group _gr_group; 19 static int _gr_stayopen; 20 static int grscan(), start_gr(); 21 22 #define MAXGRP 200 23 static char *members[MAXGRP]; 24 #define MAXLINELENGTH 1024 25 static char line[MAXLINELENGTH]; 26 27 struct group * 28 getgrent() 29 { 30 if (!_gr_fp && !start_gr() || !grscan(0, 0, NULL)) 31 return(NULL); 32 return(&_gr_group); 33 } 34 35 struct group * 36 getgrnam(name) 37 const char *name; 38 { 39 int rval; 40 41 if (!start_gr()) 42 return(NULL); 43 rval = grscan(1, 0, name); 44 if (!_gr_stayopen) 45 endgrent(); 46 return(rval ? &_gr_group : NULL); 47 } 48 49 struct group * 50 #ifdef __STDC__ 51 getgrgid(gid_t gid) 52 #else 53 getgrgid(gid) 54 gid_t gid; 55 #endif 56 { 57 int rval; 58 59 if (!start_gr()) 60 return(NULL); 61 rval = grscan(1, gid, NULL); 62 if (!_gr_stayopen) 63 endgrent(); 64 return(rval ? &_gr_group : NULL); 65 } 66 67 static 68 start_gr() 69 { 70 if (_gr_fp) { 71 rewind(_gr_fp); 72 return(1); 73 } 74 return((_gr_fp = fopen(_PATH_GROUP, "r")) ? 1 : 0); 75 } 76 77 int 78 setgrent() 79 { 80 return(setgroupent(0)); 81 } 82 83 int 84 setgroupent(stayopen) 85 int stayopen; 86 { 87 if (!start_gr()) 88 return(0); 89 _gr_stayopen = stayopen; 90 return(1); 91 } 92 93 void 94 endgrent() 95 { 96 if (_gr_fp) { 97 (void)fclose(_gr_fp); 98 _gr_fp = NULL; 99 } 100 } 101 102 static 103 grscan(search, gid, name) 104 register int search, gid; 105 register char *name; 106 { 107 register char *cp, **m; 108 char *bp; 109 char *fgets(), *strsep(), *index(); 110 111 for (;;) { 112 if (!fgets(line, sizeof(line), _gr_fp)) 113 return(0); 114 bp = line; 115 /* skip lines that are too big */ 116 if (!index(line, '\n')) { 117 int ch; 118 119 while ((ch = getc(_gr_fp)) != '\n' && ch != EOF) 120 ; 121 continue; 122 } 123 _gr_group.gr_name = strsep(&bp, ":\n"); 124 if (search && name && strcmp(_gr_group.gr_name, name)) 125 continue; 126 _gr_group.gr_passwd = strsep(&bp, ":\n"); 127 if (!(cp = strsep(&bp, ":\n"))) 128 continue; 129 _gr_group.gr_gid = atoi(cp); 130 if (search && name == NULL && _gr_group.gr_gid != gid) 131 continue; 132 for (m = _gr_group.gr_mem = members;; ++m) { 133 if (m == &members[MAXGRP - 1]) { 134 *m = NULL; 135 break; 136 } 137 if ((*m = strsep(&bp, ", \n")) == NULL) 138 break; 139 } 140 return(1); 141 } 142 /* NOTREACHED */ 143 } 144