Home | History | Annotate | Download | only in brillo
      1 // Copyright 2015 The Chromium OS Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "brillo/userdb_utils.h"
      6 
      7 #include <grp.h>
      8 #include <pwd.h>
      9 #include <sys/types.h>
     10 #include <unistd.h>
     11 
     12 #include <vector>
     13 
     14 #include <base/logging.h>
     15 
     16 namespace brillo {
     17 namespace userdb {
     18 
     19 bool GetUserInfo(const std::string& user, uid_t* uid, gid_t* gid) {
     20   ssize_t buf_len = sysconf(_SC_GETPW_R_SIZE_MAX);
     21   if (buf_len < 0)
     22     buf_len = 16384;  // 16K should be enough?...
     23   passwd pwd_buf;
     24   passwd* pwd = nullptr;
     25   std::vector<char> buf(buf_len);
     26   if (getpwnam_r(user.c_str(), &pwd_buf, buf.data(), buf_len, &pwd) || !pwd) {
     27     PLOG(ERROR) << "Unable to find user " << user;
     28     return false;
     29   }
     30 
     31   if (uid)
     32     *uid = pwd->pw_uid;
     33   if (gid)
     34     *gid = pwd->pw_gid;
     35   return true;
     36 }
     37 
     38 bool GetGroupInfo(const std::string& group, gid_t* gid) {
     39   ssize_t buf_len = sysconf(_SC_GETGR_R_SIZE_MAX);
     40   if (buf_len < 0)
     41     buf_len = 16384;  // 16K should be enough?...
     42   struct group grp_buf;
     43   struct group* grp = nullptr;
     44   std::vector<char> buf(buf_len);
     45   if (getgrnam_r(group.c_str(), &grp_buf, buf.data(), buf_len, &grp) || !grp) {
     46     PLOG(ERROR) << "Unable to find group " << group;
     47     return false;
     48   }
     49 
     50   if (gid)
     51     *gid = grp->gr_gid;
     52   return true;
     53 }
     54 
     55 }  // namespace userdb
     56 }  // namespace brillo
     57