- while ((grp = getgrent ()) != 0)
- for (cp = grp->gr_mem; *cp; ++cp)
- if (!strcmp (username, *cp))
- {
- if (maxcount != 0)
- {
- if (count >= maxcount)
- {
- endgrent ();
- return count;
- }
- grouplist[count] = grp->gr_gid;
- }
- count++;
- }
- endgrent ();
+ while (1)
+ {
+ char **cp;
+ struct group *grp;
+
+ errno = 0;
+ grp = getgrent ();
+ if (grp == NULL)
+ break;
+
+ for (cp = grp->gr_mem; *cp; ++cp)
+ {
+ int n;
+
+ if ( ! STREQ (username, *cp))
+ continue;
+
+ /* See if this group number is already on the list. */
+ for (n = 0; n < count; ++n)
+ if (grouplist && grouplist[n] == grp->gr_gid)
+ break;
+
+ /* If it's a new group number, then try to add it to the list. */
+ if (n == count)
+ {
+ if (maxcount != 0)
+ {
+ if (count >= maxcount)
+ goto done;
+ grouplist[count] = grp->gr_gid;
+ }
+ if (count == INT_MAX)
+ {
+ errno = EOVERFLOW;
+ goto done;
+ }
+ count++;
+ }
+ }
+ }
+
+ if (errno != 0)
+ count = -1;
+
+ done:
+ {
+ int saved_errno = errno;
+ endgrent ();
+ errno = saved_errno;
+ }
+