aboutsummaryrefslogtreecommitdiff
path: root/lib/mlibc/tests/posix/grp.c
blob: 3d334fe6e5e97981ddd08380d3c76560e4a1bb62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdlib.h>
#include <stdio.h>
#include <grp.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>

void check_root_group(struct group *grp) {
	assert(grp);

	printf("group name: %s\n", grp->gr_name);
	fflush(stdout);

	assert(grp->gr_gid == 0);
	assert(!strcmp(grp->gr_name, "root"));

	// Depending on your system, the root group may or may not contain the root user.
	if (grp->gr_mem[0] != NULL) {
		bool found = false;
		for (size_t i = 0; grp->gr_mem[i] != NULL; i++) {
			printf("group member: %s\n", grp->gr_mem[i]);
			fflush(stdout);

			if (!strcmp(grp->gr_mem[i], "root")) {
				found = true;
				break;
			}
		}
		assert(found);
	}
}

int main()
{
	struct group grp, *result = NULL;
	char *buf;
	size_t bufsize;
	int s;
	bool password = false;

	bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
	assert(bufsize > 0 && bufsize < 0x100000);

	buf = malloc(bufsize);
	assert(buf);

	s = getgrnam_r("root", &grp, buf, bufsize, &result);
	assert(!s);
	check_root_group(result);

	s = getgrgid_r(0, &grp, buf, bufsize, &result);
	assert(!s);
	check_root_group(result);

	result = getgrnam("root");
	check_root_group(result);

	result = getgrgid(0);
	check_root_group(result);

	result = getgrnam("this_group_doesnt_exist");
	assert(!result);
#ifndef USE_HOST_LIBC
	// This is not guaranteed.
	assert(errno == ESRCH);
#endif

	s = getgrnam_r("this_group_doesnt_exist", &grp, buf, bufsize, &result);
	assert(!result);
#ifndef USE_HOST_LIBC
	// This is not guaranteed.
	assert(s == ESRCH);
#endif

	errno = 0;
	setgrent();
	assert(errno == 0);

	result = getgrent();
	assert(result);
	grp.gr_name = strdup(result->gr_name);
	if(result->gr_passwd) {
		password = true;
	}
	grp.gr_passwd = strdup(result->gr_passwd);
	grp.gr_gid = result->gr_gid;
	assert(grp.gr_name);
	if(password)
		assert(grp.gr_passwd);

	assert(grp.gr_name);
	if(password)
		assert(grp.gr_passwd);

	endgrent();

	result = getgrent();
	assert(result);
	assert(strcmp(result->gr_name, grp.gr_name) == 0);
	if(password)
		assert(strcmp(result->gr_passwd, grp.gr_passwd) == 0);
	assert(result->gr_gid == grp.gr_gid);

	free(grp.gr_name);
	if(password)
		free(grp.gr_passwd);
	free(buf);
}