This source file includes following definitions.
- free_group_info
- get_group_info
- group_member
- main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 #include <config.h>
20
21
22 #include <unistd.h>
23
24 #include <stdckdint.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <stdlib.h>
28
29
30
31 enum { GROUPBUF_SIZE = 100 };
32
33 struct group_info
34 {
35 gid_t *group;
36 gid_t groupbuf[GROUPBUF_SIZE];
37 };
38
39 static void
40 free_group_info (struct group_info const *g)
41 {
42 if (g->group != g->groupbuf)
43 free (g->group);
44 }
45
46 static int
47 get_group_info (struct group_info *gi)
48 {
49 int n_groups = getgroups (GROUPBUF_SIZE, gi->groupbuf);
50 gi->group = gi->groupbuf;
51
52 if (n_groups < 0)
53 {
54 int n_group_slots = getgroups (0, NULL);
55 size_t nbytes;
56 if (! ckd_mul (&nbytes, n_group_slots, sizeof *gi->group))
57 {
58 gi->group = malloc (nbytes);
59 if (gi->group)
60 n_groups = getgroups (n_group_slots, gi->group);
61 }
62 }
63
64
65 return n_groups;
66 }
67
68
69
70
71
72
73 int
74 group_member (gid_t gid)
75 {
76 int i;
77 int found;
78 struct group_info gi;
79 int n_groups = get_group_info (&gi);
80
81
82 found = 0;
83 for (i = 0; i < n_groups; i++)
84 {
85 if (gid == gi.group[i])
86 {
87 found = 1;
88 break;
89 }
90 }
91
92 free_group_info (&gi);
93
94 return found;
95 }
96
97 #ifdef TEST
98
99 int
100 main (int argc, char **argv)
101 {
102 int i;
103
104 for (i = 1; i < argc; i++)
105 {
106 gid_t gid;
107
108 gid = atoi (argv[i]);
109 printf ("%d: %s\n", gid, group_member (gid) ? "yes" : "no");
110 }
111 exit (0);
112 }
113
114 #endif