]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/shadow/grp/: agetgroups(): Add function
authorAlejandro Colomar <alx@kernel.org>
Tue, 19 Nov 2024 00:20:56 +0000 (01:20 +0100)
committerSerge Hallyn <serge@hallyn.com>
Fri, 24 Jan 2025 13:58:13 +0000 (07:58 -0600)
This encapsulates the logic for calling getgroups(3), which requires two
calls plus a malloc(3) call to do it correctly.

Reviewed-by: Serge Hallyn <serge@hallyn.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/shadow/grp/agetgroups.c [new file with mode: 0644]
lib/shadow/grp/agetgroups.h [new file with mode: 0644]

index 95db1053c9b1282b182f8fab4e4d79585d1366f2..dc67df9e86ffadcd8be0daf348a666a2c2380a41 100644 (file)
@@ -173,6 +173,8 @@ libshadow_la_SOURCES = \
        sgroupio.c \
        sgroupio.h\
        shadow.c \
+       shadow/grp/agetgroups.c \
+       shadow/grp/agetgroups.h \
        shadowio.c \
        shadowio.h \
        shadowlog.c \
diff --git a/lib/shadow/grp/agetgroups.c b/lib/shadow/grp/agetgroups.c
new file mode 100644 (file)
index 0000000..9bc47cc
--- /dev/null
@@ -0,0 +1,13 @@
+// SPDX-FileCopyrightText: 2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#include <config.h>
+
+#include "shadow/grp/agetgroups.h"
+
+#include <stddef.h>
+#include <sys/types.h>
+
+
+extern inline gid_t *agetgroups(size_t *ngids);
diff --git a/lib/shadow/grp/agetgroups.h b/lib/shadow/grp/agetgroups.h
new file mode 100644 (file)
index 0000000..4317755
--- /dev/null
@@ -0,0 +1,52 @@
+// SPDX-FileCopyrightText: 2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#ifndef SHADOW_INCLUDE_LIB_SHADOW_GRP_AGETGROUPS_H_
+#define SHADOW_INCLUDE_LIB_SHADOW_GRP_AGETGROUPS_H_
+
+
+#include <config.h>
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "alloc/malloc.h"
+#include "attr.h"
+
+
+ATTR_ACCESS(write_only, 1)
+ATTR_MALLOC(free)
+inline gid_t *agetgroups(size_t *ngids);
+
+
+// Like getgroups(3), but allocate the buffer.
+// *ngids is used to return the number of elements in the allocated array.
+inline gid_t *
+agetgroups(size_t *ngids)
+{
+       int    n;
+       gid_t  *gids;
+
+       n = getgroups(0, NULL);
+       if (n == -1)
+               return NULL;
+
+       gids = MALLOC(n, gid_t);
+       if (gids == NULL)
+               return NULL;
+
+       n = getgroups(n, gids);
+       if (n == -1) {
+               free(gids);
+               return NULL;
+       }
+
+       *ngids = n;
+       return gids;
+}
+
+
+#endif  // include guard