vnstat  2.9
About: vnStat is a console-based network traffic monitor (using the /proc filesystem).
  Fossies Dox: vnstat-2.9.tar.gz  ("unofficial" and yet experimental doxygen-generated source code documentation)  

id.c
Go to the documentation of this file.
1#include "common.h"
2#include "id.h"
3
4uid_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
33gid_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
62void 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
96void 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
130int hasroot(void)
131{
132 if (getuid() != 0 && geteuid() != 0) {
133 return 0;
134 }
135 return 1;
136}
int isnumeric(const char *s)
Definition: common.c:260
int debug
Definition: common.c:8
void setuser(const char *user)
Definition: id.c:62
gid_t getgroup(const char *group)
Definition: id.c:33
void setgroup(const char *group)
Definition: id.c:96
uid_t getuser(const char *user)
Definition: id.c:4
int hasroot(void)
Definition: id.c:130