4c67f3d55d6184f1001f0b30bcab341361c42531
[rsync/rsync.git] / getgroups.c
1 /*
2  * Print out the gids of all groups for the current user.  This is like
3  * `id -G` on Linux, but it's too hard to find a portable equivalent.
4  *
5  * Copyright (C) 2002 Martin Pool
6  * Copyright (C) 2003, 2004 Wayne Davison
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "rsync.h"
24
25 int
26 main(UNUSED(int argc), UNUSED(char *argv[]))
27 {
28         int n, i;
29         gid_t *list;
30         gid_t gid = MY_GID();
31         int gid_in_list = 0;
32
33 #ifdef HAVE_GETGROUPS
34         if ((n = getgroups(0, NULL)) < 0) {
35                 perror("getgroups");
36                 return 1;
37         }
38 #else
39         n = 0;
40 #endif
41
42         list = (gid_t*)malloc(sizeof (gid_t) * (n + 1));
43         if (!list) {
44                 fprintf(stderr, "out of memory!\n");
45                 exit(1);
46         }
47
48 #ifdef HAVE_GETGROUPS
49         if (n > 0)
50                 n = getgroups(n, list);
51 #endif
52
53         for (i = 0; i < n; i++)  {
54                 printf("%lu ", (unsigned long)list[i]);
55                 if (list[i] == gid)
56                         gid_in_list = 1;
57         }
58         /* The default gid might not be in the list on some systems. */
59         if (!gid_in_list)
60                 printf("%lu", (unsigned long)gid);
61         printf("\n");
62
63         return 0;
64 }