exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / group-member.c
blob43b498310034c26b9cdebf68e281b8043d71d68b
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-2024 Free Software
4 Foundation, Inc.
6 This file is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 This file 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 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>. */
19 #include <config.h>
21 /* Specification. */
22 #include <unistd.h>
24 #include <stdckdint.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <stdlib.h>
29 /* Most processes have no more than this many groups, and for these
30 processes we can avoid using malloc. */
31 enum { GROUPBUF_SIZE = 100 };
33 struct group_info
35 gid_t *group;
36 gid_t groupbuf[GROUPBUF_SIZE];
39 static void
40 free_group_info (struct group_info const *g)
42 if (g->group != g->groupbuf)
43 free (g->group);
46 static int
47 get_group_info (struct group_info *gi)
49 int n_groups = getgroups (GROUPBUF_SIZE, gi->groupbuf);
50 gi->group = gi->groupbuf;
52 if (n_groups < 0)
54 int n_group_slots = getgroups (0, NULL);
55 size_t nbytes;
56 if (! ckd_mul (&nbytes, n_group_slots, sizeof *gi->group))
58 gi->group = malloc (nbytes);
59 if (gi->group)
60 n_groups = getgroups (n_group_slots, gi->group);
64 /* In case of error, the user loses. */
65 return n_groups;
68 /* Return non-zero if GID is one that we have in our groups list.
69 Note that the groups list is not guaranteed to contain the current
70 or effective group ID, so they should generally be checked
71 separately. */
73 int
74 group_member (gid_t gid)
76 int i;
77 int found;
78 struct group_info gi;
79 int n_groups = get_group_info (&gi);
81 /* Search through the list looking for GID. */
82 found = 0;
83 for (i = 0; i < n_groups; i++)
85 if (gid == gi.group[i])
87 found = 1;
88 break;
92 free_group_info (&gi);
94 return found;
97 #ifdef TEST
99 int
100 main (int argc, char **argv)
102 int i;
104 for (i = 1; i < argc; i++)
106 gid_t gid;
108 gid = atoi (argv[i]);
109 printf ("%d: %s\n", gid, group_member (gid) ? "yes" : "no");
111 exit (0);
114 #endif /* TEST */