summaryrefslogtreecommitdiffstats
path: root/lib/pwdutils.c
diff options
context:
space:
mode:
authorKarel Zak2016-10-14 15:02:01 +0200
committerKarel Zak2017-09-18 11:48:56 +0200
commit1742c8d84c8cdba817eb62fb7c9f4eb3c1923eb6 (patch)
treed9f1698a539f4726942cc8cd3a770d7dfaceea2e /lib/pwdutils.c
parentsu: cleanup pwd struct usage (diff)
downloadkernel-qcow2-util-linux-1742c8d84c8cdba817eb62fb7c9f4eb3c1923eb6.tar.gz
kernel-qcow2-util-linux-1742c8d84c8cdba817eb62fb7c9f4eb3c1923eb6.tar.xz
kernel-qcow2-util-linux-1742c8d84c8cdba817eb62fb7c9f4eb3c1923eb6.zip
lib/pwdutils: add xgetlogin()
Signed-off-by: Karel Zak <kzak@redhat.com>
Diffstat (limited to 'lib/pwdutils.c')
-rw-r--r--lib/pwdutils.c38
1 files changed, 35 insertions, 3 deletions
diff --git a/lib/pwdutils.c b/lib/pwdutils.c
index 58e75a45b..25b4daed0 100644
--- a/lib/pwdutils.c
+++ b/lib/pwdutils.c
@@ -36,11 +36,39 @@ failed:
return NULL;
}
+char *xgetlogin(void)
+{
+ struct passwd *pw = NULL;
+ uid_t ruid;
+ char *user;
+
+ user = getlogin();
+ if (user)
+ return xstrdup(user);
+
+ /* GNU Hurd implementation has an extension where a process can exist in a
+ * non-conforming environment, and thus be outside the realms of POSIX
+ * process identifiers; on this platform, getuid() fails with a status of
+ * (uid_t)(-1) and sets errno if a program is run from a non-conforming
+ * environment.
+ *
+ * http://austingroupbugs.net/view.php?id=511
+ */
+ errno = 0;
+ ruid = getuid();
+
+ if (errno == 0)
+ pw = getpwuid(ruid);
+ if (pw && pw->pw_name && *pw->pw_name)
+ return xstrdup(pw->pw_name);
+
+ return NULL;
+}
#ifdef TEST_PROGRAM
int main(int argc, char *argv[])
{
- char *pwdbuf = NULL;
+ char *buf = NULL;
struct passwd *pwd = NULL;
if (argc != 2) {
@@ -48,7 +76,7 @@ int main(int argc, char *argv[])
return EXIT_FAILURE;
}
- pwd = xgetpwnam(argv[1], &pwdbuf);
+ pwd = xgetpwnam(argv[1], &buf);
if (!pwd)
err(EXIT_FAILURE, "failed to get %s pwd entry", argv[1]);
@@ -58,7 +86,11 @@ int main(int argc, char *argv[])
printf("GECO: %s\n", pwd->pw_gecos);
free(pwd);
- free(pwdbuf);
+ free(buf);
+
+ printf("Current: %s\n", (buf = xgetlogin()));
+ free(buf);
+
return EXIT_SUCCESS;
}
#endif /* TEST_PROGRAM */