2
* Copyright 2011 Google Inc. All Rights Reserved.
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
16
* Author: Nikki VonHollen <vonhollen@gmail.com>
24
#include <sys/types.h>
26
#define GROUP_CONFIG_KEY "MOCK_GROUP"
28
static FILE *global_stream = NULL;
34
const char *path = getenv(GROUP_CONFIG_KEY);
38
global_stream = fopen(path, "r");
41
struct group *getgrent(void) {
48
return fgetgrent(global_stream);
55
fclose(global_stream);
59
struct group *getgrnam(const char *name) {
60
const char *path = getenv(GROUP_CONFIG_KEY);
64
FILE *stream = fopen(path, "r");
69
while ((entry = fgetgrent(stream))) {
70
if (strcmp(entry->gr_name, name) == 0) {
80
struct group *getgrgid(gid_t gid) {
81
const char *path = getenv(GROUP_CONFIG_KEY);
85
FILE *stream = fopen(path, "r");
90
while ((entry = fgetgrent(stream))) {
91
if (entry->gr_gid == gid) {
101
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups) {
102
const char *path = getenv(GROUP_CONFIG_KEY);
108
FILE *stream = fopen(path, "r");
114
int default_group_found = 0;
115
int groups_found = 0;
117
// Loop through all groups
119
while ((entry = fgetgrent(stream))) {
120
// Loop through all users in group
122
for (cur_user = entry->gr_mem; *cur_user; cur_user++) {
123
// Skip users who don't match arg 'user'
124
if (strcmp(*cur_user, user))
127
// Is this the default group? if so, flag it
128
if (entry->gr_gid == group)
129
default_group_found = 1;
131
// Only insert new entries if we have room
132
if (groups_found < *ngroups) {
133
groups[groups_found] = entry->gr_gid;
140
// Include the default group if it wasn't found
141
if (!default_group_found) {
142
if (groups_found < *ngroups) {
143
groups[groups_found] = group;
148
// Did we have to leave out some groups? If not, tell how many we found.
149
int retval = (groups_found > *ngroups) ? -1 : groups_found;
151
// Always tell the user how many groups we found via *ngroups
152
*ngroups = groups_found;