diff options
author | Karel Zak | 2016-10-14 13:21:17 +0200 |
---|---|---|
committer | Karel Zak | 2017-09-18 11:48:56 +0200 |
commit | 4f5f35fc83067b2c4874fce00ea0b53ef2488489 (patch) | |
tree | 78a973ea1f65700bdd1ce891e6ad83bbf43194ca /lib | |
parent | su: consolidate tty name usage (diff) | |
download | kernel-qcow2-util-linux-4f5f35fc83067b2c4874fce00ea0b53ef2488489.tar.gz kernel-qcow2-util-linux-4f5f35fc83067b2c4874fce00ea0b53ef2488489.tar.xz kernel-qcow2-util-linux-4f5f35fc83067b2c4874fce00ea0b53ef2488489.zip |
login: add xgetpwnam()
Signed-off-by: Karel Zak <kzak@redhat.com>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/Makemodule.am | 5 | ||||
-rw-r--r-- | lib/pwdutils.c | 64 |
2 files changed, 69 insertions, 0 deletions
diff --git a/lib/Makemodule.am b/lib/Makemodule.am index 73ac9a6f5..5a692b7b7 100644 --- a/lib/Makemodule.am +++ b/lib/Makemodule.am @@ -18,6 +18,7 @@ libcommon_la_SOURCES = \ lib/pager.c \ lib/parse-date.y \ lib/path.c \ + lib/pwdutils.c \ lib/randutils.c \ lib/setproctitle.c \ lib/strutils.c \ @@ -74,6 +75,7 @@ check_PROGRAMS += \ test_colors \ test_fileutils \ test_ismounted \ + test_pwdutils \ test_mangle \ test_randutils \ test_strutils \ @@ -149,3 +151,6 @@ test_canonicalize_CFLAGS = $(AM_CFLAGS) -DTEST_PROGRAM_CANONICALIZE test_timeutils_SOURCES = lib/timeutils.c lib/strutils.c test_timeutils_CFLAGS = $(AM_CFLAGS) -DTEST_PROGRAM_TIMEUTILS + +test_pwdutils_SOURCES = lib/pwdutils.c +test_pwdutils_CFLAGS = $(AM_CFLAGS) -DTEST_PROGRAM diff --git a/lib/pwdutils.c b/lib/pwdutils.c new file mode 100644 index 000000000..58e75a45b --- /dev/null +++ b/lib/pwdutils.c @@ -0,0 +1,64 @@ +#include <stdlib.h> + +#include "c.h" +#include "pwdutils.h" +#include "xalloc.h" + +/* Returns allocated passwd and allocated pwdbuf to store passwd strings + * fields. In case of error returns NULL and set errno, for unknown user set + * errno to EINVAL + */ +struct passwd *xgetpwnam(const char *username, char **pwdbuf) +{ + struct passwd *pwd = NULL, *res = NULL; + int rc; + + if (!pwdbuf || !username) + return NULL; + + *pwdbuf = xmalloc(UL_GETPW_BUFSIZ); + pwd = xcalloc(1, sizeof(struct passwd)); + + errno = 0; + rc = getpwnam_r(username, pwd, *pwdbuf, UL_GETPW_BUFSIZ, &res); + if (rc != 0) { + errno = rc; + goto failed; + } + if (!res) { + errno = EINVAL; + goto failed; + } + return pwd; +failed: + free(pwd); + free(*pwdbuf); + return NULL; +} + + +#ifdef TEST_PROGRAM +int main(int argc, char *argv[]) +{ + char *pwdbuf = NULL; + struct passwd *pwd = NULL; + + if (argc != 2) { + fprintf(stderr, "usage: %s <username>\n", argv[0]); + return EXIT_FAILURE; + } + + pwd = xgetpwnam(argv[1], &pwdbuf); + if (!pwd) + err(EXIT_FAILURE, "failed to get %s pwd entry", argv[1]); + + printf("Username: %s\n", pwd->pw_name); + printf("UID: %d\n", pwd->pw_uid); + printf("HOME: %s\n", pwd->pw_dir); + printf("GECO: %s\n", pwd->pw_gecos); + + free(pwd); + free(pwdbuf); + return EXIT_SUCCESS; +} +#endif /* TEST_PROGRAM */ |