From e3ad8880110bbc46d47d4c8bc69473cb7e1cc193 Mon Sep 17 00:00:00 2001 From: Suren Baghdasaryan Date: Wed, 6 Feb 2019 13:25:29 -0800 Subject: [PATCH] libprocessgroup: Fix cgroup directory ownership setup When cgroup directory is created its user and ownership gets set, however because previous code was storing getpwnam() return value the second invocation would effectively override the previous ones result. Fix this by copying necessary results. Also change getpwnam() to getgrnam() when group name is converted into gid. getpwnam() works because of the way Android uses these ids, however more generally this is incorrect and getgrnam() should be used instead. Bug: 111307099 Test: verified user/group membership of the cgroup directories Change-Id: I78668bc1a36a74f53d8e9825e2d06e3e09501e7a Signed-off-by: Suren Baghdasaryan --- libprocessgroup/cgroup_map.cpp | 39 ++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/libprocessgroup/cgroup_map.cpp b/libprocessgroup/cgroup_map.cpp index 12cfb7e62..c5fb80464 100644 --- a/libprocessgroup/cgroup_map.cpp +++ b/libprocessgroup/cgroup_map.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -72,26 +73,28 @@ static bool Mkdir(const std::string& path, mode_t mode, const std::string& uid, } } - passwd* uid_pwd = nullptr; - passwd* gid_pwd = nullptr; - - if (!uid.empty()) { - uid_pwd = getpwnam(uid.c_str()); - if (!uid_pwd) { - PLOG(ERROR) << "Unable to decode UID for '" << uid << "'"; - return false; - } - - if (!gid.empty()) { - gid_pwd = getpwnam(gid.c_str()); - if (!gid_pwd) { - PLOG(ERROR) << "Unable to decode GID for '" << gid << "'"; - return false; - } - } + if (uid.empty()) { + return true; } - if (uid_pwd && lchown(path.c_str(), uid_pwd->pw_uid, gid_pwd ? gid_pwd->pw_uid : -1) < 0) { + passwd* uid_pwd = getpwnam(uid.c_str()); + if (!uid_pwd) { + PLOG(ERROR) << "Unable to decode UID for '" << uid << "'"; + return false; + } + + uid_t pw_uid = uid_pwd->pw_uid; + gid_t gr_gid = -1; + if (!gid.empty()) { + group* gid_pwd = getgrnam(gid.c_str()); + if (!gid_pwd) { + PLOG(ERROR) << "Unable to decode GID for '" << gid << "'"; + return false; + } + gr_gid = gid_pwd->gr_gid; + } + + if (lchown(path.c_str(), pw_uid, gr_gid) < 0) { PLOG(ERROR) << "lchown() failed for " << path; return false; }