1 /* getugroups.c -- return a list of the groups a user is in
3 Copyright (C) 1990, 1991, 1998, 1999, 2000, 2003, 2004, 2005 Free
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 /* Written by David MacKenzie. */
26 #include <sys/types.h>
27 #include <stdio.h> /* grp.h on alpha OSF1 V2.0 uses "FILE *". */
34 # define EOVERFLOW EINVAL
37 /* setgrent, getgrent, and endgrent are not specified by POSIX.1,
38 so header files might not declare them.
39 If you don't have them at all, we can't implement this function.
41 struct group *getgrent ();
45 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
47 /* Like `getgroups', but for user USERNAME instead of for the current
48 process. Store at most MAXCOUNT group IDs in the GROUPLIST array.
49 If GID is not -1, store it first (if possible). GID should be the
50 group ID (pw_gid) obtained from getpwuid, in case USERNAME is not
51 listed in /etc/groups.
52 Always return the number of groups of which USERNAME is a member. */
55 getugroups (int maxcount, GETGROUPS_T *grouplist, char *username, gid_t gid)
59 register int count = 0;
61 if (gid != (gid_t) -1)
64 grouplist[count] = gid;
69 while ((grp = getgrent ()) != 0)
71 for (cp = grp->gr_mem; *cp; ++cp)
75 if ( ! STREQ (username, *cp))
78 /* See if this group number is already on the list. */
79 for (n = 0; n < count; ++n)
80 if (grouplist && grouplist[n] == grp->gr_gid)
83 /* If it's a new group number, then try to add it to the list. */
88 if (count >= maxcount)
93 grouplist[count] = grp->gr_gid;