]> 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>
Thu, 24 Jul 2025 11:16:59 +0000 (13:16 +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>
sys-utils/setpriv.c

index c6ff7718e710b541ed1042f4af7d1cc1a3a1f062..a5c832f381a462656af52aed0e43723b6966c5c7 100644 (file)
@@ -295,19 +295,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: "));
@@ -323,6 +319,10 @@ static void dump_groups(void)
        }
        printf("\n");
        free(groups);
+       return;
+failed:
+       free(groups);
+       warn("getgroups failed");
 }
 
 static void dump_pdeathsig(void)