getgroups: fix compilation when getgroups is available
[gnulib.git] / lib / getgroups.c
1 /* provide consistent interface to getgroups for systems that don't allow N==0
2
3    Copyright (C) 1996, 1999, 2003, 2006, 2007, 2008 Free Software
4    Foundation, Inc.
5
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.
10
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.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /* written by Jim Meyering */
20
21 #include <config.h>
22
23 #undef getgroups
24
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <errno.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30
31 #include "xalloc.h"
32
33 /* On at least Ultrix 4.3 and NextStep 3.2, getgroups (0, 0) always fails.
34    On other systems, it returns the number of supplemental groups for the
35    process.  This function handles that special case and lets the system-
36    provided function handle all others. */
37
38 int
39 rpl_getgroups (int n, GETGROUPS_T *group)
40 {
41   int n_groups;
42   GETGROUPS_T *gbuf;
43   int saved_errno;
44
45   if (n != 0)
46     return getgroups (n, group);
47
48   n = 20;
49   while (1)
50     {
51       /* No need to worry about address arithmetic overflow here,
52          since the ancient systems that we're running on have low
53          limits on the number of secondary groups.  */
54       gbuf = xmalloc (n * sizeof *gbuf);
55       n_groups = getgroups (n, gbuf);
56       if (n_groups < n)
57         break;
58       free (gbuf);
59       n += 10;
60     }
61
62   saved_errno = errno;
63   free (gbuf);
64   errno = saved_errno;
65
66   return n_groups;
67 }