From cd083615b4a2d9a1ca01467b8012fedca500e22f Mon Sep 17 00:00:00 2001 From: Quentin Rameau Date: Sat, 21 Sep 2019 20:50:20 +0200 Subject: [PATCH] lib/pwdutils: add xgetpwuid --- include/pwdutils.h | 1 + lib/pwdutils.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/include/pwdutils.h b/include/pwdutils.h index a69dd6b454..bea46e57e3 100644 --- a/include/pwdutils.h +++ b/include/pwdutils.h @@ -5,6 +5,7 @@ #include extern struct passwd *xgetpwnam(const char *username, char **pwdbuf); +extern struct passwd *xgetpwuid(uid_t uid, char **pwdbuf); extern char *xgetlogin(void); #endif /* UTIL_LINUX_PWDUTILS_H */ diff --git a/lib/pwdutils.c b/lib/pwdutils.c index 25b4daed0e..d54458d65d 100644 --- a/lib/pwdutils.c +++ b/lib/pwdutils.c @@ -36,6 +36,34 @@ failed: return NULL; } +struct passwd *xgetpwuid(uid_t uid, char **pwdbuf) +{ + struct passwd *pwd = NULL, *res = NULL; + int rc; + + if (!pwdbuf) + return NULL; + + *pwdbuf = xmalloc(UL_GETPW_BUFSIZ); + pwd = xcalloc(1, sizeof(struct passwd)); + + errno = 0; + rc = getpwuid_r(uid, 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; +} + char *xgetlogin(void) { struct passwd *pw = NULL; -- 2.47.3