unix/fiss

src/chpst/parse.c in master
Repositories | Summary | Log | Files | LICENSE

parse.c (1319B) download


 1#include "parse.h"
 2
 3#include <fcntl.h>
 4#include <grp.h>
 5#include <pwd.h>
 6#include <stdio.h>
 7#include <stdlib.h>
 8#include <string.h>
 9#include <unistd.h>
10
11
12/* uid:gid[:gid[:gid]...] */
13static int parse_ugid_num(char* str, uid_t* uid, gid_t* gids) {
14	int   i;
15	char* end;
16
17	*uid = strtoul(str, &end, 10);
18
19	if (*end != ':')
20		return -1;
21
22	str = end + 1;
23	for (i = 0; i < 60; ++i, ++str) {
24		gids[i++] = strtoul(str, &end, 10);
25
26		if (*end != ':')
27			break;
28
29		str = end + 1;
30	}
31
32	if (*str != '\0')
33		return -1;
34
35	return i;
36}
37
38int parse_ugid(char* str, uid_t* uid, gid_t* gids) {
39	struct passwd* pwd;
40	struct group*  gr;
41	char*          end;
42	char*          groupstr = NULL;
43	int            gid_size = 0;
44	char*          next;
45
46	if (str[0] == ':')
47		return parse_ugid_num(str + 1, uid, gids);
48
49	if ((end = strchr(str, ':')) != NULL) {
50		end[0]   = '\0';
51		groupstr = end + 1;
52	}
53
54	if ((pwd = getpwnam(str)) == NULL) {
55		return -1;
56	}
57	*uid = pwd->pw_uid;
58
59	if (groupstr == NULL) {
60		gids[0] = pwd->pw_gid;
61		return 1;
62	}
63
64	next = groupstr;
65
66	while (next && gid_size < 60) {
67		groupstr = next;
68		if ((end = strchr(groupstr, ':')) != NULL) {
69			end[0] = '\0';
70			next   = end + 1;
71		} else {
72			next = NULL;
73		}
74		if ((gr = getgrnam(groupstr)) == NULL)
75			return -1;
76
77		gids[gid_size++] = gr->gr_gid;
78	}
79
80	return gid_size;
81}