-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpwd.c
124 lines (116 loc) · 2.31 KB
/
pwd.c
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "pwd.h"
#include "fcntl.h"
#include "user.h"
static struct passwd current_passwd;
static char current_line[MAX_PASSWD_LINE_LENGTH];
static int fd;
// This function assumes that fd is already open
// Returns -1 if could not read next entry
static int
get_and_parse_pwent(void)
{
char* tokens[NUMBER_OF_PASSWD_TOKENS];
int ok = 0;
fgets(current_line, MAX_PASSWD_LINE_LENGTH, fd);
int length = strlen(current_line);
if (current_line[length - 1] == '\n' ||
current_line[length - 1] == '\r') {
current_line[length - 1] = 0;
}
int next_token = 0;
int i;
for (i = 0; current_line[i]; ++i) {
if (current_line[i] == ':') {
if (ok == 0) {
tokens[next_token++] = current_line + i;
}
current_line[i] = 0;
ok = 0;
} else if (ok == 0 && next_token < NUMBER_OF_PASSWD_TOKENS) {
ok = 1;
tokens[next_token++] = current_line + i;
}
}
if (i == 0) return -1;
current_passwd.pw_name = tokens[0];
current_passwd.pw_passwd = tokens[1];
current_passwd.pw_uid = atoi(tokens[2]);
current_passwd.pw_gid = atoi(tokens[3]);
current_passwd.pw_gecos = tokens[4];
current_passwd.pw_dir = tokens[5];
current_passwd.pw_shell = tokens[6];
return 0;
}
struct passwd*
getpwent(void)
{
if (fd == 0) {
fd = open(PASSWD_FILE, O_RDONLY);
if (fd < 0) {
fd = 0;
return 0;
}
}
if (get_and_parse_pwent() == -1) {
return 0;
}
return ¤t_passwd;
}
void
setpwent(void)
{
if (fd != 0) {
close(fd);
fd = 0;
}
fd = open(PASSWD_FILE, O_RDONLY);
if (fd < 0) fd = 0;
}
void
endpwent(void)
{
if (fd != 0) {
close(fd);
fd = 0;
}
}
struct passwd*
getpwnam(const char* name)
{
setpwent();
while (getpwent()) {
if (strcmp(name, current_passwd.pw_name) == 0) {
endpwent();
return ¤t_passwd;
}
}
endpwent();
return 0;
}
struct passwd*
getpwuid(uid_t uid)
{
setpwent();
while (getpwent()) {
if (current_passwd.pw_uid == uid) {
endpwent();
return ¤t_passwd;
}
}
endpwent();
return 0;
}
int
putpwent(struct passwd* pass, int fd)
{
if (pass == 0) return -1;
printf(fd, "%s:%s:%d:%d:%s:%s:%s\n",
pass->pw_name,
pass->pw_passwd,
pass->pw_uid,
pass->pw_gid,
pass->pw_gecos,
pass->pw_dir,
pass->pw_shell);
return 0;
}