Change copyright notice from GPLv2+ to GPLv3+.
[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 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* written by Jim Meyering */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <errno.h>
25 #include <stdlib.h>
26
27 #include "xalloc.h"
28
29 /* On at least Ultrix 4.3 and NextStep 3.2, getgroups (0, 0) always fails.
30    On other systems, it returns the number of supplemental groups for the
31    process.  This function handles that special case and lets the system-
32    provided function handle all others. */
33
34 int
35 getgroups (int n, GETGROUPS_T *group)
36 {
37   int n_groups;
38   GETGROUPS_T *gbuf;
39   int saved_errno;
40
41 #undef getgroups
42
43   if (n != 0)
44     return getgroups (n, group);
45
46   n = 20;
47   while (1)
48     {
49       /* No need to worry about address arithmetic overflow here,
50          since the ancient systems that we're running on have low
51          limits on the number of secondary groups.  */
52       gbuf = xmalloc (n * sizeof *gbuf);
53       n_groups = getgroups (n, gbuf);
54       if (n_groups < n)
55         break;
56       free (gbuf);
57       n += 10;
58     }
59
60   saved_errno = errno;
61   free (gbuf);
62   errno = saved_errno;
63
64   return n_groups;
65 }