diff options
| author | Bruce Momjian | 2014-01-10 23:03:28 +0000 |
|---|---|---|
| committer | Bruce Momjian | 2014-01-10 23:03:28 +0000 |
| commit | 111022eac64579cc12d20e33146ce01717562b29 (patch) | |
| tree | b09e0eef58f48860ca2e97a10ca6f9260f4fb706 /src/common | |
| parent | 423e1211a86df0d0dd8914223137edbfd4d52400 (diff) | |
Move username lookup functions from /port to /common
Per suggestion from Peter E and Alvaro
Diffstat (limited to 'src/common')
| -rw-r--r-- | src/common/Makefile | 2 | ||||
| -rw-r--r-- | src/common/username.c | 85 |
2 files changed, 86 insertions, 1 deletions
diff --git a/src/common/Makefile b/src/common/Makefile index 62ca8ab0c35..7edbaaa2c1a 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -23,7 +23,7 @@ include $(top_builddir)/src/Makefile.global override CPPFLAGS := -DFRONTEND $(CPPFLAGS) LIBS += $(PTHREAD_LIBS) -OBJS_COMMON = exec.o pgfnames.o psprintf.o relpath.o rmtree.o wait_error.o +OBJS_COMMON = exec.o pgfnames.o psprintf.o relpath.o rmtree.o username.o wait_error.o OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o diff --git a/src/common/username.c b/src/common/username.c new file mode 100644 index 00000000000..c6812ddd9d1 --- /dev/null +++ b/src/common/username.c @@ -0,0 +1,85 @@ +/*------------------------------------------------------------------------- + * + * 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 %d: %s"), + (int) 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; + + 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; +} |
