summaryrefslogtreecommitdiff
path: root/src/common/username.c
diff options
context:
space:
mode:
authorPavan Deolasee2015-05-05 09:19:18 +0000
committerPavan Deolasee2015-05-05 09:19:18 +0000
commit73fa25c67cbfa24c03e28c96bf356f2592671730 (patch)
tree10ded7e26abd78d93658cb72fc5cb9d4672eff2a /src/common/username.c
parentda4d108859bcd7a308ca75aba54281e32968822c (diff)
parent4a9ab6d8619817f9e3989c99b65140e19041dab7 (diff)
Merge branch 'XL_MASTER_MERGE_9_4' into XL_NEW_MASTER
Conflicts: src/test/regress/expected/aggregates.out src/test/regress/expected/create_index.out src/test/regress/expected/inherit.out src/test/regress/expected/join.out src/test/regress/expected/window.out src/test/regress/expected/with.out
Diffstat (limited to 'src/common/username.c')
-rw-r--r--src/common/username.c87
1 files changed, 87 insertions, 0 deletions
diff --git a/src/common/username.c b/src/common/username.c
new file mode 100644
index 0000000000..24c5b47627
--- /dev/null
+++ b/src/common/username.c
@@ -0,0 +1,87 @@
+/*-------------------------------------------------------------------------
+ *
+ * username.c
+ * get user name
+ *
+ * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/common/username.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef FRONTEND
+#include "postgres.h"
+#else
+#include "postgres_fe.h"
+#endif
+
+#include <errno.h>
+#include <pwd.h>
+#include <unistd.h>
+#include <sys/types.h>
+
+#include "common/username.h"
+
+/*
+ * Returns the current user name in a static buffer, or NULL on error and
+ * sets errstr
+ */
+const char *
+get_user_name(char **errstr)
+{
+#ifndef WIN32
+ struct passwd *pw;
+ uid_t user_id = geteuid();
+
+ *errstr = NULL;
+
+ errno = 0; /* clear errno before call */
+ pw = getpwuid(user_id);
+ if (!pw)
+ {
+ *errstr = psprintf(_("failed to look up effective user id %ld: %s"),
+ (long) user_id,
+ errno ? strerror(errno) : _("user does not exist"));
+ return NULL;
+ }
+
+ return pw->pw_name;
+#else
+ /* UNLEN = 256, 'static' variable remains after function exit */
+ static char username[256 + 1];
+ DWORD len = sizeof(username) - 1;
+
+ *errstr = NULL;
+
+ if (!GetUserName(username, &len))
+ {
+ *errstr = psprintf(_("user name lookup failure: %s"), strerror(errno));
+ return NULL;
+ }
+
+ return username;
+#endif
+}
+
+
+/*
+ * Returns the current user name in a static buffer or exits
+ */
+const char *
+get_user_name_or_exit(const char *progname)
+{
+ const char *user_name;
+ char *errstr;
+
+ user_name = get_user_name(&errstr);
+
+ if (!user_name)
+ {
+ fprintf(stderr, "%s: %s\n", progname, errstr);
+ exit(1);
+ }
+ return user_name;
+}