]> git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/pwdutils.c
fdisk: cleanup wipe warning
[thirdparty/util-linux.git] / lib / pwdutils.c
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 */
11 struct 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;
33 failed:
34 free(pwd);
35 free(*pwdbuf);
36 return NULL;
37 }
38
39 char *xgetlogin(void)
40 {
41 struct passwd *pw = NULL;
42 uid_t ruid;
43 char *user;
44
45 user = getlogin();
46 if (user)
47 return xstrdup(user);
48
49 /* GNU Hurd implementation has an extension where a process can exist in a
50 * non-conforming environment, and thus be outside the realms of POSIX
51 * process identifiers; on this platform, getuid() fails with a status of
52 * (uid_t)(-1) and sets errno if a program is run from a non-conforming
53 * environment.
54 *
55 * http://austingroupbugs.net/view.php?id=511
56 */
57 errno = 0;
58 ruid = getuid();
59
60 if (errno == 0)
61 pw = getpwuid(ruid);
62 if (pw && pw->pw_name && *pw->pw_name)
63 return xstrdup(pw->pw_name);
64
65 return NULL;
66 }
67
68 #ifdef TEST_PROGRAM
69 int main(int argc, char *argv[])
70 {
71 char *buf = NULL;
72 struct passwd *pwd = NULL;
73
74 if (argc != 2) {
75 fprintf(stderr, "usage: %s <username>\n", argv[0]);
76 return EXIT_FAILURE;
77 }
78
79 pwd = xgetpwnam(argv[1], &buf);
80 if (!pwd)
81 err(EXIT_FAILURE, "failed to get %s pwd entry", argv[1]);
82
83 printf("Username: %s\n", pwd->pw_name);
84 printf("UID: %d\n", pwd->pw_uid);
85 printf("HOME: %s\n", pwd->pw_dir);
86 printf("GECO: %s\n", pwd->pw_gecos);
87
88 free(pwd);
89 free(buf);
90
91 printf("Current: %s\n", (buf = xgetlogin()));
92 free(buf);
93
94 return EXIT_SUCCESS;
95 }
96 #endif /* TEST_PROGRAM */