#include "includes.h"
#include <sys/types.h>
#include <sys/param.h>
#include <grp.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#ifdef __APPLE_MEMBERSHIP__
#include <membership.h>
#endif
#include "xmalloc.h"
#include "groupaccess.h"
#include "match.h"
#include "log.h"
#ifdef __APPLE_MEMBERSHIP__
int32_t getgrouplist_2(const char *, gid_t, gid_t **);
int32_t getgroupcount(const char *, gid_t);
#endif
static int ngroups;
static char **groups_byname;
#ifdef __APPLE_MEMBERSHIP__
uuid_t u_uuid;
#endif
int
ga_init(struct passwd *pw)
{
gid_t *groups_bygid = NULL;
int i, j;
struct group *gr;
#ifdef __APPLE_MEMBERSHIP__
if (0 != mbr_uid_to_uuid(pw->pw_uid, u_uuid))
return 0;
#endif
if (ngroups > 0)
ga_free();
#ifndef __APPLE_MEMBERSHIP__
ngroups = NGROUPS_MAX;
#if defined(HAVE_SYSCONF) && defined(_SC_NGROUPS_MAX)
ngroups = MAX(NGROUPS_MAX, sysconf(_SC_NGROUPS_MAX));
#endif
groups_bygid = xcalloc(ngroups, sizeof(*groups_bygid));
#else
if (-1 == (ngroups = getgrouplist_2(pw->pw_name, pw->pw_gid,
&groups_bygid))) {
logit("getgrouplist_2 failed");
return 0;
}
#endif
groups_byname = xcalloc(ngroups, sizeof(*groups_byname));
#ifndef __APPLE_MEMBERSHIP__
if (getgrouplist(pw->pw_name, pw->pw_gid, groups_bygid, &ngroups) == -1) {
logit("getgrouplist: groups list too small");
xfree(groups_bygid);
return 0;
}
#endif
for (i = 0, j = 0; i < ngroups; i++)
if ((gr = getgrgid(groups_bygid[i])) != NULL)
groups_byname[j++] = xstrdup(gr->gr_name);
xfree(groups_bygid);
return (ngroups = j);
}
int
ga_match(char * const *groups, int n)
{
int i, j;
for (i = 0; i < ngroups; i++)
for (j = 0; j < n; j++)
if (match_pattern(groups_byname[i], groups[j]))
return 1;
return 0;
}
int
ga_match_pattern_list(const char *group_pattern)
{
int i, found = 0;
size_t len = strlen(group_pattern);
for (i = 0; i < ngroups; i++) {
switch (match_pattern_list(groups_byname[i],
group_pattern, len, 0)) {
case -1:
return 0;
case 0:
continue;
case 1:
found = 1;
}
}
return found;
}
void
ga_free(void)
{
int i;
if (ngroups > 0) {
for (i = 0; i < ngroups; i++)
xfree(groups_byname[i]);
ngroups = 0;
xfree(groups_byname);
}
}