]> git.ipfire.org Git - thirdparty/util-linux.git/blame - lib/pwdutils.c
script: document SIGUSR1
[thirdparty/util-linux.git] / lib / pwdutils.c
CommitLineData
4f5f35fc
KZ
1#include <stdlib.h>
2
3#include "c.h"
4#include "pwdutils.h"
5#include "xalloc.h"
6
7/* Returns allocated passwd and allocated pwdbuf to store passwd strings
8 * fields. In case of error returns NULL and set errno, for unknown user set
9 * errno to EINVAL
10 */
11struct passwd *xgetpwnam(const char *username, char **pwdbuf)
12{
13 struct passwd *pwd = NULL, *res = NULL;
14 int rc;
15
16 if (!pwdbuf || !username)
17 return NULL;
18
19 *pwdbuf = xmalloc(UL_GETPW_BUFSIZ);
20 pwd = xcalloc(1, sizeof(struct passwd));
21
22 errno = 0;
23 rc = getpwnam_r(username, pwd, *pwdbuf, UL_GETPW_BUFSIZ, &res);
24 if (rc != 0) {
25 errno = rc;
26 goto failed;
27 }
28 if (!res) {
29 errno = EINVAL;
30 goto failed;
31 }
32 return pwd;
33failed:
34 free(pwd);
35 free(*pwdbuf);
36 return NULL;
37}
38
cd083615
QR
39struct passwd *xgetpwuid(uid_t uid, char **pwdbuf)
40{
41 struct passwd *pwd = NULL, *res = NULL;
42 int rc;
43
44 if (!pwdbuf)
45 return NULL;
46
47 *pwdbuf = xmalloc(UL_GETPW_BUFSIZ);
48 pwd = xcalloc(1, sizeof(struct passwd));
49
50 errno = 0;
51 rc = getpwuid_r(uid, pwd, *pwdbuf, UL_GETPW_BUFSIZ, &res);
52 if (rc != 0) {
53 errno = rc;
54 goto failed;
55 }
56 if (!res) {
57 errno = EINVAL;
58 goto failed;
59 }
60 return pwd;
61failed:
62 free(pwd);
63 free(*pwdbuf);
64 return NULL;
65}
66
1742c8d8
KZ
67char *xgetlogin(void)
68{
69 struct passwd *pw = NULL;
70 uid_t ruid;
71 char *user;
72
73 user = getlogin();
74 if (user)
75 return xstrdup(user);
76
77 /* GNU Hurd implementation has an extension where a process can exist in a
78 * non-conforming environment, and thus be outside the realms of POSIX
79 * process identifiers; on this platform, getuid() fails with a status of
80 * (uid_t)(-1) and sets errno if a program is run from a non-conforming
81 * environment.
82 *
83 * http://austingroupbugs.net/view.php?id=511
84 */
85 errno = 0;
86 ruid = getuid();
87
88 if (errno == 0)
89 pw = getpwuid(ruid);
90 if (pw && pw->pw_name && *pw->pw_name)
91 return xstrdup(pw->pw_name);
92
93 return NULL;
94}
4f5f35fc
KZ
95
96#ifdef TEST_PROGRAM
97int main(int argc, char *argv[])
98{
1742c8d8 99 char *buf = NULL;
4f5f35fc
KZ
100 struct passwd *pwd = NULL;
101
102 if (argc != 2) {
103 fprintf(stderr, "usage: %s <username>\n", argv[0]);
104 return EXIT_FAILURE;
105 }
106
1742c8d8 107 pwd = xgetpwnam(argv[1], &buf);
4f5f35fc
KZ
108 if (!pwd)
109 err(EXIT_FAILURE, "failed to get %s pwd entry", argv[1]);
110
111 printf("Username: %s\n", pwd->pw_name);
112 printf("UID: %d\n", pwd->pw_uid);
113 printf("HOME: %s\n", pwd->pw_dir);
114 printf("GECO: %s\n", pwd->pw_gecos);
115
116 free(pwd);
1742c8d8
KZ
117 free(buf);
118
119 printf("Current: %s\n", (buf = xgetlogin()));
120 free(buf);
121
4f5f35fc
KZ
122 return EXIT_SUCCESS;
123}
124#endif /* TEST_PROGRAM */