Ignore not-yet-defined Portals in pg_cursors view.
[pgsql.git] / src / port / user.c
blob7444aeb64b287ed157c6dddb00c46129aec701bb
1 /*-------------------------------------------------------------------------
3 * user.c
5 * Wrapper functions for user and home directory lookup.
7 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
9 * src/port/user.c
11 *-------------------------------------------------------------------------
14 #include "c.h"
16 #include <pwd.h>
18 #ifndef WIN32
21 * pg_get_user_name - get the name of the user with the given ID
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.
27 bool
28 pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
30 char pwdbuf[BUFSIZ];
31 struct passwd pwdstr;
32 struct passwd *pw = NULL;
33 int pwerr;
35 pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
36 if (pw != NULL)
38 strlcpy(buffer, pw->pw_name, buflen);
39 return true;
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;
54 * pg_get_user_home_dir - get the home directory of the user with the given ID
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.
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.
63 bool
64 pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
66 char pwdbuf[BUFSIZ];
67 struct passwd pwdstr;
68 struct passwd *pw = NULL;
69 int pwerr;
71 pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
72 if (pw != NULL)
74 strlcpy(buffer, pw->pw_dir, buflen);
75 return true;
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;
89 #endif /* !WIN32 */