Refactor groups proxy 94/187294/2
authorMichal Bloch <m.bloch@samsung.com>
Tue, 21 Aug 2018 17:53:54 +0000 (19:53 +0200)
committerHyotaek Shim <hyotaek.shim@samsung.com>
Wed, 29 Aug 2018 03:01:42 +0000 (03:01 +0000)
Fixes container misuse. Happens to remove a false positive
SVACE static analysis warning in the process.

Change-Id: I71f3789dbfb33b9dfadf880f70e4f2ca7747b53e
Signed-off-by: Michal Bloch <m.bloch@samsung.com>
src/internal/groups_proxy.cpp

index 93f500b..9d9cb02 100644 (file)
@@ -2,6 +2,7 @@
 #include "tslog.hpp"
 #include <grp.h>
 #include <pwd.h>
+#include <array>
 
 /**
  * \file
  */
 
 std::vector<gid_t> get_groups(const uid_t uid, const gid_t gid) {
-       const int max_groups = 100;
-       std::vector<gid_t> groups(max_groups);
-       int ngroups = max_groups;
-       std::vector<char> buf(1024);
+       std::array <char, 1024> buf;
        struct passwd *user_pw = nullptr;
        struct passwd pwd;
 
-       if (getpwuid_r(uid, &pwd, &buf[0], buf.size(), &user_pw)) {
+       if (getpwuid_r(uid, &pwd, buf.data(), buf.size(), &user_pw)) {
                if (tslog::enabled())
                        std::cout << "getpwuid_r failed" << " uid:" << uid << " gid: " << gid << std::endl;
-               groups.clear();
-               return groups;
+               return {};
        }
        if (!user_pw) {
                if (tslog::enabled())
                        std::cout << "getpwuid_r failed. no matching password record was found" << " uid:" << uid << " gid: " << gid << std::endl;
-               groups.clear();
-               return groups;
+               return {};
        }
 
-       if (getgrouplist(user_pw->pw_name, gid, &groups[0], &ngroups) < 0) {
+       int ngroups = 0;
+       int r = getgrouplist(user_pw->pw_name, gid, NULL, &ngroups);
+
+       if (ngroups == 0)
+               return {};
+
+       auto groups = std::vector<gid_t> (ngroups);
+       r = getgrouplist(user_pw->pw_name, gid, groups.data(), &ngroups);
+       if (r < 0) {
                if (tslog::enabled())
                        std::cout << "getgrouplist failed" << " uid:" << uid << " gid: " << gid << std::endl;
                groups.clear();
-               return groups;
        }
-       groups.resize(ngroups);
        return groups;
 }