740027
diff --git a/lib/getugroups.c b/lib/getugroups.c
740027
index 299bae6..8ece29b 100644
740027
--- a/lib/getugroups.c
740027
+++ b/lib/getugroups.c
740027
@@ -19,6 +19,9 @@
740027
 
740027
 #include <config.h>
740027
 
740027
+/* We do not need this code if getgrouplist(3) is available.  */
740027
+#ifndef HAVE_GETGROUPLIST
740027
+
740027
 #include "getugroups.h"
740027
 
740027
 #include <errno.h>
740027
@@ -123,3 +126,4 @@ getugroups (int maxcount, gid_t *grouplist, char const *username,
740027
 }
740027
 
740027
 #endif /* HAVE_GRP_H */
740027
+#endif	/* have getgrouplist */
740027
diff --git a/lib/mgetgroups.c b/lib/mgetgroups.c
740027
index 76474c2..0a9d221 100644
740027
--- a/lib/mgetgroups.c
740027
+++ b/lib/mgetgroups.c
740027
@@ -115,9 +115,17 @@ mgetgroups (char const *username, gid_t gid, gid_t **groups)
740027
   /* else no username, so fall through and use getgroups. */
740027
 #endif
740027
 
740027
-  max_n_groups = (username
740027
-                  ? getugroups (0, NULL, username, gid)
740027
-                  : getgroups (0, NULL));
740027
+  if (!username)
740027
+    max_n_groups = getgroups(0, NULL);
740027
+  else 
740027
+  {
740027
+#ifdef HAVE_GETGROUPLIST
740027
+    max_n_groups = 0;
740027
+    getgrouplist (username, gid, NULL, &max_n_groups);
740027
+#else
740027
+    max_n_groups = getugroups (0, NULL, username, gid);
740027
+#endif
740027
+  }
740027
 
740027
   /* If we failed to count groups because there is no supplemental
740027
      group support, then return an array containing just GID.
740027
@@ -139,10 +147,25 @@ mgetgroups (char const *username, gid_t gid, gid_t **groups)
740027
   if (g == NULL)
740027
     return -1;
740027
 
740027
-  ng = (username
740027
-        ? getugroups (max_n_groups, g, username, gid)
740027
-        : getgroups (max_n_groups - (gid != (gid_t) -1),
740027
-                                g + (gid != (gid_t) -1)));
740027
+  if (!username)
740027
+    ng = getgroups (max_n_groups - (gid != (gid_t)-1), g + (gid != (gid_t)-1));
740027
+  else
740027
+  {
740027
+#ifdef HAVE_GETGROUPLIST
740027
+    int e;
740027
+    ng = max_n_groups;
740027
+    while ((e = getgrouplist (username, gid, g, &ng)) == -1
740027
+	&& ng > max_n_groups)
740027
+    {
740027
+      max_n_groups = ng;
740027
+      g = xrealloc (g, max_n_groups * sizeof (GETGROUPS_T));
740027
+    }
740027
+    if (e == -1)
740027
+      ng = -1;
740027
+#else
740027
+    ng = getugroups (max_n_groups, g, username, gid);
740027
+#endif
740027
+  }
740027
 
740027
   if (ng < 0)
740027
     {
740027
diff --git a/m4/jm-macros.m4 b/m4/jm-macros.m4
740027
index 62777c7..5180243 100644
740027
--- a/m4/jm-macros.m4
740027
+++ b/m4/jm-macros.m4
740027
@@ -78,6 +78,7 @@ 
740027
     fchown
740027
     fchmod
740027
     ftruncate
740027
+    getgrouplist
740027
     iswspace
740027
     mkfifo
740027
     mbrlen