Subject: bug#7320: Confirmed on coreutils-8.4-13

From: Jim Meyering <[email-masked]>
Date: Fri, 27 Apr 2012 13:08:08 +0200

Marc W. Mengel wrote:
> This is still broken in RedHat in coreutils-8.4-13
>
> All of  "groups" and "id" and "id -G" report groups that you don't have
> if you list a new/different primary group in /etc/passwd.
>
> This is just plain wrong.  "id" and "groups" should list the groups you
> actually have, not what you would possibly have if you logged out and
> back in again.

Thank you for the report.
It looks like there is indeed a bug.

I demonstrated it with this:

    echo 'for i in 1 2; do id -G; sleep 1.5; done; sleep 4' \
      |su -s /bin/sh ftp - &
    sleep 1; perl -pi -e 's/^(ftp:x:\d+):(\d+)/$1:9876/' /etc/passwd

Those id -G commands printed the following:

    50
    50 9876

With the patch below, they print this:

    50
    50

The problem is that group-list.c(print_group_list), called by id.c
did not invoke xgetgroups properly.  xgetgroups is just a wrapper
around mgetgroups, which has this comment:

     If USERNAME is
     NULL, store the supplementary groups of the current process, and GID
     should be -1 or the effective group ID (getegid).

In the case you've noted, USERNAME is indeed NULL,
so print_group_list should pass the effective group ID,
and not getpwuid(ruid)->pw_gid.

This also shows that when username is NULL, print_group_list's
call to getpwuid is now useless and wasteful.

With all that, here's the patch I expect to commit:

diff --git a/src/group-list.c b/src/group-list.c
index cf49911..edbb342 100644
--- a/src/group-list.c
+++ b/src/group-list.c
@@ -38,11 +38,14 @@ print_group_list (const char *username,
                   bool use_names)
 {
   bool ok = true;
-  struct passwd *pwd;
+  struct passwd *pwd = NULL;

-  pwd = getpwuid (ruid);
-  if (pwd == NULL)
-    ok = false;
+  if (username)
+    {
+      pwd = getpwuid (ruid);
+      if (pwd == NULL)
+        ok = false;
+    }

   if (!print_group (rgid, use_names))
     ok = false;
@@ -58,8 +61,7 @@ print_group_list (const char *username,
     gid_t *groups;
     int i;

-    int n_groups = xgetgroups (username, (pwd ? pwd->pw_gid : (gid_t) -1),
-                               &groups);
+    int n_groups = xgetgroups (username, (pwd ? pwd->pw_gid : egid), &groups);
     if (n_groups < 0)
       {
         if (username)