1 /* Initgroups handling in nss_files module.
2 Copyright (C) 2011-2016 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library 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 GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
23 #include <stdio_ext.h>
25 #include <sys/param.h>
30 _nss_files_initgroups_dyn (const char *user
, gid_t group
, long int *start
,
31 long int *size
, gid_t
**groupsp
, long int limit
,
34 FILE *stream
= fopen ("/etc/group", "rce");
38 return *errnop
== ENOMEM
? NSS_STATUS_TRYAGAIN
: NSS_STATUS_UNAVAIL
;
41 /* No other thread using this stream. */
42 __fsetlocking (stream
, FSETLOCKING_BYCALLER
);
46 enum nss_status status
= NSS_STATUS_SUCCESS
;
50 void *buffer
= alloca (buflen
);
51 bool buffer_use_malloc
= false;
53 gid_t
*groups
= *groupsp
;
55 /* We have to iterate over the entire file. */
59 fgetpos (stream
, &pos
);
60 ssize_t n
= getline (&line
, &linelen
, stream
);
63 if (! feof_unlocked (stream
))
64 status
= ((*errnop
= errno
) == ENOMEM
65 ? NSS_STATUS_TRYAGAIN
: NSS_STATUS_UNAVAIL
);
70 int res
= _nss_files_parse_grent (line
, &grp
, buffer
, buflen
, errnop
);
73 size_t newbuflen
= 2 * buflen
;
74 if (buffer_use_malloc
|| ! __libc_use_alloca (buflen
+ newbuflen
))
76 void *newbuf
= realloc (buffer_use_malloc
? buffer
: NULL
,
81 status
= NSS_STATUS_TRYAGAIN
;
86 buffer_use_malloc
= true;
89 buffer
= extend_alloca (buffer
, buflen
, newbuflen
);
90 /* Reread current line, the parser has clobbered it. */
91 fsetpos (stream
, &pos
);
95 if (res
> 0 && grp
.gr_gid
!= group
)
96 for (char **m
= grp
.gr_mem
; *m
!= NULL
; ++m
)
97 if (strcmp (*m
, user
) == 0)
99 /* Matches user. Insert this group. */
102 /* Need a bigger buffer. */
103 if (limit
> 0 && *size
== limit
)
104 /* We reached the maximum. */
111 newsize
= MIN (limit
, 2 * *size
);
113 gid_t
*newgroups
= realloc (groups
,
114 newsize
* sizeof (*groups
));
115 if (newgroups
== NULL
)
118 status
= NSS_STATUS_TRYAGAIN
;
121 *groupsp
= groups
= newgroups
;
125 groups
[*start
] = grp
.gr_gid
;
135 if (buffer_use_malloc
)
141 return status
== NSS_STATUS_SUCCESS
&& !any
? NSS_STATUS_NOTFOUND
: status
;