1 /* group-member.c -- determine whether group id is in calling user's group list
3 Copyright (C) 1994, 1997-1998, 2003, 2005-2006, 2009-2017 Free Software
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 3 of the License, or
9 (at your option) any later version.
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, see <https://www.gnu.org/licenses/>. */
25 #include <sys/types.h>
28 #include "xalloc-oversized.h"
30 /* Most processes have no more than this many groups, and for these
31 processes we can avoid using malloc. */
32 enum { GROUPBUF_SIZE
= 100 };
37 gid_t groupbuf
[GROUPBUF_SIZE
];
41 free_group_info (struct group_info
const *g
)
43 if (g
->group
!= g
->groupbuf
)
48 get_group_info (struct group_info
*gi
)
50 int n_groups
= getgroups (GROUPBUF_SIZE
, gi
->groupbuf
);
51 gi
->group
= gi
->groupbuf
;
55 int n_group_slots
= getgroups (0, NULL
);
56 if (0 <= n_group_slots
57 && ! xalloc_oversized (n_group_slots
, sizeof *gi
->group
))
59 gi
->group
= malloc (n_group_slots
* sizeof *gi
->group
);
61 n_groups
= getgroups (n_group_slots
, gi
->group
);
65 /* In case of error, the user loses. */
69 /* Return non-zero if GID is one that we have in our groups list.
70 Note that the groups list is not guaranteed to contain the current
71 or effective group ID, so they should generally be checked
75 group_member (gid_t gid
)
80 int n_groups
= get_group_info (&gi
);
82 /* Search through the list looking for GID. */
84 for (i
= 0; i
< n_groups
; i
++)
86 if (gid
== gi
.group
[i
])
93 free_group_info (&gi
);
101 main (int argc
, char **argv
)
105 for (i
= 1; i
< argc
; i
++)
109 gid
= atoi (argv
[i
]);
110 printf ("%d: %s\n", gid
, group_member (gid
) ? "yes" : "no");