Re: getgrouplist(3) vs. getgroups(3)



On Fri, Jul 22, 2005 at 10:23:27AM +0200, Roland Illig wrote:
> +/* Return the index of the permissions triplet */
> +int
> +get_user_permissions (struct stat *buf) {
> +    static gboolean initialized = FALSE;
> +    static gid_t groups[NGROUPS_MAX];

NGROUPS_MAX can be fairly large, plus it is max number of
supplemental groups, so getgroups might want to return
NGROUPS_MAX+1 groups.  Not to mention that the real number
of max supplemental groups is sysconf (_SC_NGROUPS_MAX) + 1,
which can differ from NGROUPS_MAX+1.

But, IMHO far better would be to:
static gid_t *groups;
if (!groups) {
  uid = getuid ();
  n = getgroups (0, NULL);
  if (n < 0) error_handling;
  groups = malloc (n * sizeof (gid_t));
  if (groups == NULL) error_handling;
  n = getgroups (n, groups);
  if (n < 0) error_handling;
}

and perhaps if n is big enough qsort groups array and use
a binary search instead of linear one.

> +    static int n;
> +    static uid_t uid;
> +    int i;
> +
> +    if (!initialized) {
> +	uid = getuid();
> +	n = getgroups(NGROUPS_MAX, groups);
> +	initialized = TRUE;
> +    }
> +
> +    if (buf->st_uid == uid || uid == 0)
> +       return 0;
> +
> +    for (i = 0; i < n; i++) {
> +	if (buf->st_gid == groups[i])
> +	    return 1;
> +    }
> +
> +    return 2;
>  }

	Jakub



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]