PostgreSQL Source Code  git master
user.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * user.c
4  *
5  * Wrapper functions for user and home directory lookup.
6  *
7  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
8  *
9  * src/port/user.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 
14 #include "c.h"
15 
16 #include <pwd.h>
17 
18 #ifndef WIN32
19 
20 /*
21  * pg_get_user_name - get the name of the user with the given ID
22  *
23  * On success, the user name is returned into the buffer (of size buflen),
24  * and "true" is returned. On failure, a localized error message is
25  * returned into the buffer, and "false" is returned.
26  */
27 bool
28 pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
29 {
30  char pwdbuf[BUFSIZ];
31  struct passwd pwdstr;
32  struct passwd *pw = NULL;
33  int pwerr;
34 
35  pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
36  if (pw != NULL)
37  {
38  strlcpy(buffer, pw->pw_name, buflen);
39  return true;
40  }
41  if (pwerr != 0)
42  snprintf(buffer, buflen,
43  _("could not look up local user ID %d: %s"),
44  (int) user_id,
45  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
46  else
47  snprintf(buffer, buflen,
48  _("local user with ID %d does not exist"),
49  (int) user_id);
50  return false;
51 }
52 
53 /*
54  * pg_get_user_home_dir - get the home directory of the user with the given ID
55  *
56  * On success, the directory path is returned into the buffer (of size buflen),
57  * and "true" is returned. On failure, a localized error message is
58  * returned into the buffer, and "false" is returned.
59  *
60  * Note that this does not incorporate the common behavior of checking
61  * $HOME first, since it's independent of which user_id is queried.
62  */
63 bool
64 pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
65 {
66  char pwdbuf[BUFSIZ];
67  struct passwd pwdstr;
68  struct passwd *pw = NULL;
69  int pwerr;
70 
71  pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
72  if (pw != NULL)
73  {
74  strlcpy(buffer, pw->pw_dir, buflen);
75  return true;
76  }
77  if (pwerr != 0)
78  snprintf(buffer, buflen,
79  _("could not look up local user ID %d: %s"),
80  (int) user_id,
81  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
82  else
83  snprintf(buffer, buflen,
84  _("local user with ID %d does not exist"),
85  (int) user_id);
86  return false;
87 }
88 
89 #endif /* !WIN32 */
#define _(x)
Definition: elog.c:90
bool pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
Definition: user.c:64
bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
Definition: user.c:28
#define snprintf
Definition: port.h:238
#define strerror_r
Definition: port.h:255
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int uid_t
Definition: win32_port.h:244