aboutsummaryrefslogtreecommitdiffstats
path: root/brillo/userdb_utils.cc
blob: a204094565d3a49843fea1ac20468d4f8ef65d1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2015 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "brillo/userdb_utils.h"

#include <grp.h>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>

#include <vector>

#include <base/logging.h>
#include <base/posix/eintr_wrapper.h>

namespace brillo {
namespace userdb {

bool GetUserInfo(const std::string& user, uid_t* uid, gid_t* gid) {
  ssize_t buf_len = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (buf_len < 0)
    buf_len = 16384;  // 16K should be enough?...
  passwd pwd_buf;
  passwd* pwd = nullptr;
  std::vector<char> buf(buf_len);
  if (HANDLE_EINTR(
          getpwnam_r(user.c_str(), &pwd_buf, buf.data(), buf_len, &pwd)) ||
      !pwd) {
    PLOG(ERROR) << "Unable to find user " << user;
    return false;
  }

  if (uid)
    *uid = pwd->pw_uid;
  if (gid)
    *gid = pwd->pw_gid;
  return true;
}

bool GetGroupInfo(const std::string& group, gid_t* gid) {
  ssize_t buf_len = sysconf(_SC_GETGR_R_SIZE_MAX);
  if (buf_len < 0)
    buf_len = 16384;  // 16K should be enough?...
  struct group grp_buf;
  struct group* grp = nullptr;
  std::vector<char> buf(buf_len);
  if (HANDLE_EINTR(
          getgrnam_r(group.c_str(), &grp_buf, buf.data(), buf_len, &grp)) ||
      !grp) {
    PLOG(ERROR) << "Unable to find group " << group;
    return false;
  }

  if (gid)
    *gid = grp->gr_gid;
  return true;
}

}  // namespace userdb
}  // namespace brillo