1 /* Initgroups handling in nss_files module.
2 Copyright (C) 2011-2022 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 <https://www.gnu.org/licenses/>. */
22 #include <stdio_ext.h>
24 #include <sys/param.h>
27 #include <scratch_buffer.h>
29 #include <nss_files.h>
32 _nss_files_initgroups_dyn (const char *user
, gid_t group
, long int *start
,
33 long int *size
, gid_t
**groupsp
, long int limit
,
36 FILE *stream
= __nss_files_fopen ("/etc/group");
40 return *errnop
== ENOMEM
? NSS_STATUS_TRYAGAIN
: NSS_STATUS_UNAVAIL
;
45 enum nss_status status
= NSS_STATUS_SUCCESS
;
48 struct scratch_buffer tmpbuf
;
49 scratch_buffer_init (&tmpbuf
);
51 gid_t
*groups
= *groupsp
;
53 /* We have to iterate over the entire file. */
57 fgetpos (stream
, &pos
);
58 ssize_t n
= __getline (&line
, &linelen
, stream
);
61 if (! __feof_unlocked (stream
))
62 status
= ((*errnop
= errno
) == ENOMEM
63 ? NSS_STATUS_TRYAGAIN
: NSS_STATUS_UNAVAIL
);
68 int res
= _nss_files_parse_grent (line
, &grp
,
69 tmpbuf
.data
, tmpbuf
.length
, errnop
);
72 if (!scratch_buffer_grow (&tmpbuf
))
75 status
= NSS_STATUS_TRYAGAIN
;
78 /* Reread current line, the parser has clobbered it. */
79 fsetpos (stream
, &pos
);
83 if (res
> 0 && grp
.gr_gid
!= group
)
84 for (char **m
= grp
.gr_mem
; *m
!= NULL
; ++m
)
85 if (strcmp (*m
, user
) == 0)
87 /* Matches user. Insert this group. */
90 /* Need a bigger buffer. */
91 if (limit
> 0 && *size
== limit
)
92 /* We reached the maximum. */
99 newsize
= MIN (limit
, 2 * *size
);
101 gid_t
*newgroups
= realloc (groups
,
102 newsize
* sizeof (*groups
));
103 if (newgroups
== NULL
)
106 status
= NSS_STATUS_TRYAGAIN
;
109 *groupsp
= groups
= newgroups
;
113 groups
[*start
] = grp
.gr_gid
;
123 scratch_buffer_free (&tmpbuf
);
128 return status
== NSS_STATUS_SUCCESS
&& !any
? NSS_STATUS_NOTFOUND
: status
;
130 libc_hidden_def (_nss_files_initgroups_dyn
)