summaryrefslogtreecommitdiff
path: root/lib/libc/pwd/getgrgid_r.c
blob: 0aec3e081a1ccb86a51193b29dbf1dd847831fb2 (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
#include "stddef.h" // for NULL

#include <errno.h>     // for ERANGE, errno
#include <limits.h>    // for LINE_MAX
#include <pwd.h>       // for passwd, getpwuid_r
#include <stdio.h>     // for fclose, fgets, fopen, FILE
#include <stdlib.h>    // for strtoul
#include <string.h>    // for strtok, memcpy, strlen
#include <sys/types.h> // for size_t, uid_t, gid_t

static char *copy_str(const char *src, char **buf, size_t *buflen)
{
	size_t len = strlen(src) + 1;
	if (len > *buflen)
		return NULL;
	char *dst = *buf;
	memcpy(dst, src, len);
	*buf += len;
	*buflen -= len;
	return dst;
}

int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result)
{
	FILE *stream = fopen("/etc/passwd", "r");
	if (stream == NULL) {
		*result = NULL;
		return errno;
	}

	char line[LINE_MAX];

	while (fgets(line, sizeof(line), stream)) {
		char *name = strtok(line, ":");
		char *passwd = strtok(NULL, ":");
		char *uid_str = strtok(NULL, ":");
		char *gid_str = strtok(NULL, ":");
		strtok(NULL, ":");
		char *dir = strtok(NULL, ":");
		char *shell = strtok(NULL, "\n");

		if (name == NULL || passwd == NULL || uid_str == NULL || gid_str == NULL)
			continue;

		uid_t file_uid = (uid_t)strtoul(uid_str, NULL, 10);
		if (file_uid != uid)
			continue;

		size_t rem = buflen;

		pwd->pw_name = copy_str(name, &buf, &rem);
		pwd->pw_dir = copy_str(dir ? dir : "", &buf, &rem);
		pwd->pw_shell = copy_str(shell ? shell : "", &buf, &rem);
		pwd->pw_uid = file_uid;
		pwd->pw_gid = (gid_t)strtoul(gid_str, NULL, 10);
		pwd->pw_uid = file_uid;
		pwd->pw_gid = (gid_t)strtoul(gid_str, NULL, 10);

		if (pwd->pw_name == NULL || pwd->pw_dir == NULL || pwd->pw_shell == NULL) {
			fclose(stream);
			return ERANGE;
		}

		fclose(stream);
		*result = pwd;
		return 0;
	}

	fclose(stream);
	*result = NULL;
	return 0;
}