"Fossies" - the Fresh Open Source Software Archive 
Member "vnstat-2.9/src/id.c" (10 May 2019, 2108 Bytes) of package /linux/misc/vnstat-2.9.tar.gz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style:
standard) with prefixed line numbers and
code folding option.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "id.c" see the
Fossies "Dox" file reference documentation.
1 #include "common.h"
2 #include "id.h"
3
4 uid_t getuser(const char *user)
5 {
6 struct passwd *pw;
7 uid_t uid;
8
9 if (!strlen(user)) {
10 return getuid();
11 }
12
13 if (isnumeric(user)) {
14 uid = (uid_t)atoi(user);
15 pw = getpwuid(uid);
16 } else {
17 pw = getpwnam(user);
18 }
19
20 if (pw == NULL) {
21 printf("Error: No such user: \"%s\".\n", user);
22 exit(EXIT_FAILURE);
23 }
24
25 uid = pw->pw_uid;
26
27 if (debug)
28 printf("getuser(%s / %d): %s (%d)\n", user, atoi(user), pw->pw_name, (int)uid);
29
30 return uid;
31 }
32
33 gid_t getgroup(const char *group)
34 {
35 struct group *gr;
36 gid_t gid;
37
38 if (!strlen(group)) {
39 return getgid();
40 }
41
42 if (isnumeric(group)) {
43 gid = (gid_t)atoi(group);
44 gr = getgrgid(gid);
45 } else {
46 gr = getgrnam(group);
47 }
48
49 if (gr == NULL) {
50 printf("Error: No such group: \"%s\".\n", group);
51 exit(EXIT_FAILURE);
52 }
53
54 gid = gr->gr_gid;
55
56 if (debug)
57 printf("getgroup(%s / %d): %s (%d)\n", group, atoi(group), gr->gr_name, (int)gid);
58
59 return gid;
60 }
61
62 void setuser(const char *user)
63 {
64 uid_t uid;
65
66 if (!strlen(user)) {
67 return;
68 }
69
70 if (isnumeric(user) && atoi(user) == 0) {
71 return;
72 }
73
74 uid = getuser(user);
75
76 if (uid == getuser("")) {
77 if (debug)
78 printf("no user switching needed, already as requested user \"%s\"\n", user);
79 return;
80 }
81
82 if (!hasroot()) {
83 printf("Error: User can only be set as root.\n");
84 exit(EXIT_FAILURE);
85 }
86
87 if (debug)
88 printf("switching to user id %d.\n", uid);
89
90 if (setuid(uid) != 0) {
91 perror("Error: setuid");
92 exit(EXIT_FAILURE);
93 }
94 }
95
96 void setgroup(const char *group)
97 {
98 gid_t gid;
99
100 if (!strlen(group)) {
101 return;
102 }
103
104 if (isnumeric(group) && atoi(group) == 0) {
105 return;
106 }
107
108 gid = getgroup(group);
109
110 if (gid == getgroup("")) {
111 if (debug)
112 printf("no group switching needed, already as requested group \"%s\"\n", group);
113 return;
114 }
115
116 if (!hasroot()) {
117 printf("Error: Group can only be set as root.\n");
118 exit(EXIT_FAILURE);
119 }
120
121 if (debug)
122 printf("switching to group id %d.\n", gid);
123
124 if (setgid(gid) != 0) {
125 perror("Error: setgid");
126 exit(EXIT_FAILURE);
127 }
128 }
129
130 int hasroot(void)
131 {
132 if (getuid() != 0 && geteuid() != 0) {
133 return 0;
134 }
135 return 1;
136 }