]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
setpriv: Improve getgroups() Portability
authorKarel Zak <kzak@redhat.com>
Mon, 21 Jul 2025 06:16:25 +0000 (08:16 +0200)
committerKarel Zak <kzak@redhat.com>
Tue, 9 Sep 2025 10:02:49 +0000 (12:02 +0200)
setpriv(1) is Linux-only, and on Linux, getgroups() returns at least one group.
However, it's better to use more portable and generic code patterns and assume
that getgroups() can return zero.

Fixes: https://github.com/util-linux/util-linux/issues/3654
Reported-by: Alejandro Colomar <alx@kernel.org>
Signed-off-by: Karel Zak <kzak@redhat.com>
(cherry picked from commit 434a5633a563066357bbc3f331838ed41041ec1a)

sys-utils/setpriv.c

index daa3ab366b17658bdd8ade84cf3da592771199f9..7242c333dbe6fa951137cf85adc299927bdc6d11 100644 (file)
@@ -294,19 +294,15 @@ static void dump_label(const char *name)
 static void dump_groups(void)
 {
        int n = getgroups(0, NULL);
-       gid_t *groups;
-
-       if (n < 0) {
-               warn("getgroups failed");
-               return;
-       }
-
-       groups = xmalloc(n * sizeof(gid_t));
-       n = getgroups(n, groups);
-       if (n < 0) {
-               free(groups);
-               warn("getgroups failed");
-               return;
+       gid_t *groups = NULL;
+
+       if (n < 0)
+               goto failed;
+       if (n) {
+               groups = xmalloc(n * sizeof(gid_t));
+               n = getgroups(n, groups);
+               if (n < 0)
+                       goto failed;
        }
 
        printf(_("Supplementary groups: "));
@@ -322,6 +318,10 @@ static void dump_groups(void)
        }
        printf("\n");
        free(groups);
+       return;
+failed:
+       free(groups);
+       warn("getgroups failed");
 }
 
 static void dump_pdeathsig(void)