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