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