Skip to content

Commit

Permalink
util: code cleanup
Browse files Browse the repository at this point in the history
Signed-off-by: He Xian <hexian000@outlook.com>
  • Loading branch information
hexian000 committed Jan 28, 2024
1 parent 39b9bb3 commit 342c77e
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions src/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -133,27 +133,23 @@ void drop_privileges(const char *name)
char buf[len + 1];
memcpy(buf, name, len + 1);

const char *user, *group;
char *colon = strchr(buf, ':');
const char *user = NULL, *group = NULL;
char *const colon = strchr(buf, ':');
if (colon != NULL) {
if (colon != buf) {
user = buf;
} else {
user = NULL;
}
*colon = '\0';
if (colon[1] != '\0') {
group = &colon[1];
} else {
group = NULL;
}
} else {
user = buf;
group = NULL;
}

uid_t uid;
gid_t gid;
uid_t uid = (uid_t)-1;
gid_t gid = (gid_t)-1;
const struct passwd *pw = NULL;

if (user != NULL) {
Expand Down Expand Up @@ -190,7 +186,7 @@ void drop_privileges(const char *name)
(intmax_t)gr->gr_gid);
gid = gr->gr_gid;
}
} else if (colon != NULL) {
} else if (user != NULL && colon != NULL) {
/* group is not specified, search from user database */
if (pw == NULL) {
pw = getpwuid(uid);
Expand All @@ -212,15 +208,15 @@ void drop_privileges(const char *name)
strerror(err));
}
#endif
if (group != NULL || colon != NULL) {
if (gid != (gid_t)-1) {
LOGD_F("setgid: %jd", (intmax_t)gid);
if (setgid(gid) != 0 || setegid(gid) != 0) {
const int err = errno;
LOGW_F("unable to drop group privileges: %s",
strerror(err));
}
}
if (user != NULL) {
if (uid != (uid_t)-1) {
LOGD_F("setuid: %jd", (intmax_t)uid);
if (setuid(uid) != 0 || seteuid(uid) != 0) {
const int err = errno;
Expand Down

0 comments on commit 342c77e

Please sign in to comment.