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