Line data Source code
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 20628 : pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
29 : {
30 : char pwdbuf[BUFSIZ];
31 : struct passwd pwdstr;
32 20628 : struct passwd *pw = NULL;
33 : int pwerr;
34 :
35 20628 : pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
36 20628 : if (pw != NULL)
37 : {
38 20628 : strlcpy(buffer, pw->pw_name, buflen);
39 20628 : return true;
40 : }
41 0 : if (pwerr != 0)
42 0 : snprintf(buffer, buflen,
43 0 : _("could not look up local user ID %d: %s"),
44 : (int) user_id,
45 : strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
46 : else
47 0 : snprintf(buffer, buflen,
48 0 : _("local user with ID %d does not exist"),
49 : (int) user_id);
50 0 : 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 0 : pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
65 : {
66 : char pwdbuf[BUFSIZ];
67 : struct passwd pwdstr;
68 0 : struct passwd *pw = NULL;
69 : int pwerr;
70 :
71 0 : pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
72 0 : if (pw != NULL)
73 : {
74 0 : strlcpy(buffer, pw->pw_dir, buflen);
75 0 : return true;
76 : }
77 0 : if (pwerr != 0)
78 0 : snprintf(buffer, buflen,
79 0 : _("could not look up local user ID %d: %s"),
80 : (int) user_id,
81 : strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
82 : else
83 0 : snprintf(buffer, buflen,
84 0 : _("local user with ID %d does not exist"),
85 : (int) user_id);
86 0 : return false;
87 : }
88 :
89 : #endif /* !WIN32 */
|