]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/pwdutils.c
2 * No copyright is claimed. This code is in the public domain; do with
12 /* Returns allocated passwd and allocated pwdbuf to store passwd strings
13 * fields. In case of error returns NULL and set errno, for unknown user set
16 struct passwd
*xgetpwnam(const char *username
, char **pwdbuf
)
18 struct passwd
*pwd
= NULL
, *res
= NULL
;
24 *pwdbuf
= xmalloc(UL_GETPW_BUFSIZ
);
25 pwd
= xcalloc(1, sizeof(struct passwd
));
28 rc
= getpwnam_r(username
, pwd
, *pwdbuf
, UL_GETPW_BUFSIZ
, &res
);
44 /* Returns allocated group and allocated grpbuf to store group strings
45 * fields. In case of error returns NULL and set errno, for unknown group set
48 struct group
*xgetgrnam(const char *groupname
, char **grpbuf
)
50 struct group
*grp
= NULL
, *res
= NULL
;
56 *grpbuf
= xmalloc(UL_GETPW_BUFSIZ
);
57 grp
= xcalloc(1, sizeof(struct group
));
60 rc
= getgrnam_r(groupname
, grp
, *grpbuf
, UL_GETPW_BUFSIZ
, &res
);
76 struct passwd
*xgetpwuid(uid_t uid
, char **pwdbuf
)
78 struct passwd
*pwd
= NULL
, *res
= NULL
;
83 *pwdbuf
= xmalloc(UL_GETPW_BUFSIZ
);
84 pwd
= xcalloc(1, sizeof(struct passwd
));
87 rc
= getpwuid_r(uid
, pwd
, *pwdbuf
, UL_GETPW_BUFSIZ
, &res
);
103 char *xgetlogin(void)
105 struct passwd
*pw
= NULL
;
108 /* GNU Hurd implementation has an extension where a process can exist in a
109 * non-conforming environment, and thus be outside the realms of POSIX
110 * process identifiers; on this platform, getuid() fails with a status of
111 * (uid_t)(-1) and sets errno if a program is run from a non-conforming
114 * http://austingroupbugs.net/view.php?id=511
116 * The same implementation is useful for other systems, since getlogin(3)
117 * shouldn't be used as actual identification.
124 if (pw
&& pw
->pw_name
&& *pw
->pw_name
)
125 return xstrdup(pw
->pw_name
);
131 int main(int argc
, char *argv
[])
134 struct passwd
*pwd
= NULL
;
137 fprintf(stderr
, "usage: %s <username>\n", argv
[0]);
141 pwd
= xgetpwnam(argv
[1], &buf
);
143 err(EXIT_FAILURE
, "failed to get %s pwd entry", argv
[1]);
145 printf("Username: %s\n", pwd
->pw_name
);
146 printf("UID: %d\n", pwd
->pw_uid
);
147 printf("HOME: %s\n", pwd
->pw_dir
);
148 printf("GECO: %s\n", pwd
->pw_gecos
);
153 printf("Current: %s\n", (buf
= xgetlogin()));
158 #endif /* TEST_PROGRAM */