2013-12-18 18:16:16 +01:00
|
|
|
/*-------------------------------------------------------------------------
|
|
|
|
*
|
|
|
|
* username.c
|
|
|
|
* get user name
|
|
|
|
*
|
2014-01-07 22:05:30 +01:00
|
|
|
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
|
2013-12-18 18:16:16 +01:00
|
|
|
* Portions Copyright (c) 1994, Regents of the University of California
|
|
|
|
*
|
|
|
|
* IDENTIFICATION
|
2014-01-11 00:03:28 +01:00
|
|
|
* src/common/username.c
|
2013-12-18 18:16:16 +01:00
|
|
|
*
|
|
|
|
*-------------------------------------------------------------------------
|
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef FRONTEND
|
|
|
|
#include "postgres.h"
|
|
|
|
#else
|
|
|
|
#include "postgres_fe.h"
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#include <errno.h>
|
|
|
|
#include <pwd.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
|
2014-01-11 00:03:28 +01:00
|
|
|
#include "common/username.h"
|
2013-12-18 18:16:16 +01:00
|
|
|
|
|
|
|
/*
|
|
|
|
* 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;
|
2014-01-30 02:03:57 +01:00
|
|
|
uid_t user_id = geteuid();
|
2013-12-18 18:16:16 +01:00
|
|
|
|
|
|
|
*errstr = NULL;
|
|
|
|
|
2014-01-30 02:03:57 +01:00
|
|
|
errno = 0; /* clear errno before call */
|
2013-12-18 18:16:16 +01:00
|
|
|
pw = getpwuid(user_id);
|
|
|
|
if (!pw)
|
|
|
|
{
|
2014-01-30 02:03:57 +01:00
|
|
|
*errstr = psprintf(_("failed to look up effective user id %ld: %s"),
|
|
|
|
(long) user_id,
|
|
|
|
errno ? strerror(errno) : _("user does not exist"));
|
2013-12-18 18:16:16 +01:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
return pw->pw_name;
|
|
|
|
#else
|
|
|
|
/* UNLEN = 256, 'static' variable remains after function exit */
|
2013-12-28 01:51:49 +01:00
|
|
|
static char username[256 + 1];
|
2013-12-18 18:16:16 +01:00
|
|
|
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;
|
2013-12-27 05:51:56 +01:00
|
|
|
char *errstr;
|
2013-12-18 18:16:16 +01:00
|
|
|
|
|
|
|
user_name = get_user_name(&errstr);
|
|
|
|
|
|
|
|
if (!user_name)
|
|
|
|
{
|
|
|
|
fprintf(stderr, "%s: %s\n", progname, errstr);
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
return user_name;
|
|
|
|
}
|