1 /* 2 * Copyright (c) 1989 The Regents of the University of California. 3 * All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #if defined(LIBC_SCCS) && !defined(lint) 9 static char sccsid[] = "@(#)getgrent.c 5.8 (Berkeley) 02/23/91"; 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 const char *_gr_file = _PATH_GROUP; 21 static start_gr(); 22 static grscan(); 23 24 #define MAXGRP 200 25 static char *members[MAXGRP]; 26 #define MAXLINELENGTH 1024 27 static char line[MAXLINELENGTH]; 28 29 struct group * 30 getgrent() 31 { 32 if (!_gr_fp && !start_gr() || !grscan(0, 0, (char *)NULL)) 33 return((struct group *)NULL); 34 return(&_gr_group); 35 } 36 37 struct group * 38 getgrnam(name) 39 const char *name; 40 { 41 int rval; 42 43 if (!start_gr()) 44 return((struct group *)NULL); 45 rval = grscan(1, 0, name); 46 if (!_gr_stayopen) 47 endgrent(); 48 return(rval ? &_gr_group : (struct group *)NULL); 49 } 50 51 struct group * 52 #ifdef __STDC__ 53 getgrgid(gid_t gid) 54 #else 55 getgrgid(gid) 56 gid_t gid; 57 #endif 58 { 59 int rval; 60 61 if (!start_gr()) 62 return((struct group *)NULL); 63 rval = grscan(1, gid, (char *)NULL); 64 if (!_gr_stayopen) 65 endgrent(); 66 return(rval ? &_gr_group : (struct group *)NULL); 67 } 68 69 static 70 start_gr() 71 { 72 if (_gr_fp) { 73 rewind(_gr_fp); 74 return(1); 75 } 76 return((_gr_fp = fopen(_gr_file, "r")) ? 1 : 0); 77 } 78 79 int 80 setgrent() 81 { 82 return(setgroupent(0)); 83 } 84 85 int 86 setgroupent(stayopen) 87 int stayopen; 88 { 89 if (!start_gr()) 90 return(0); 91 _gr_stayopen = stayopen; 92 return(1); 93 } 94 95 void 96 endgrent() 97 { 98 if (_gr_fp) { 99 (void)fclose(_gr_fp); 100 _gr_fp = (FILE *)NULL; 101 } 102 } 103 104 void 105 setgrfile(file) 106 const char *file; 107 { 108 _gr_file = file; 109 } 110 111 static 112 grscan(search, gid, name) 113 register int search, gid; 114 register char *name; 115 { 116 register char *cp, **m; 117 char *bp; 118 char *fgets(), *strsep(), *index(); 119 120 for (;;) { 121 if (!fgets(line, sizeof(line), _gr_fp)) 122 return(0); 123 bp = line; 124 /* skip lines that are too big */ 125 if (!index(line, '\n')) { 126 int ch; 127 128 while ((ch = getc(_gr_fp)) != '\n' && ch != EOF) 129 ; 130 continue; 131 } 132 _gr_group.gr_name = strsep(&bp, ":\n"); 133 if (search && name && strcmp(_gr_group.gr_name, name)) 134 continue; 135 _gr_group.gr_passwd = strsep(&bp, ":\n"); 136 if (!(cp = strsep(&bp, ":\n"))) 137 continue; 138 _gr_group.gr_gid = atoi(cp); 139 if (search && name == NULL && _gr_group.gr_gid != gid) 140 continue; 141 for (m = _gr_group.gr_mem = members;; ++m) { 142 if (m == &members[MAXGRP - 1]) { 143 *m = NULL; 144 break; 145 } 146 if ((*m = strsep(&bp, ", \n")) == NULL) 147 break; 148 } 149 return(1); 150 } 151 /* NOTREACHED */ 152 } 153