1
0
mirror of https://github.com/postgres/postgres.git synced 2025-12-09 02:08:45 +03:00
Files
postgres/src/common/username.c
Tom Lane 9e3755ecb2 Remove useless duplicate inclusions of system header files.
c.h #includes a number of core libc header files, such as <stdio.h>.
There's no point in re-including these after having read postgres.h,
postgres_fe.h, or c.h; so remove code that did so.

While at it, also fix some places that were ignoring our standard pattern
of "include postgres[_fe].h, then system header files, then other Postgres
header files".  While there's not any great magic in doing it that way
rather than system headers last, it's silly to have just a few files
deviating from the general pattern.  (But I didn't attempt to enforce this
globally, only in files I was touching anyway.)

I'd be the first to say that this is mostly compulsive neatnik-ism,
but over time it might save enough compile cycles to be useful.
2017-02-25 16:12:55 -05:00

88 lines
1.7 KiB
C

/*-------------------------------------------------------------------------
*
* username.c
* get user name
*
* Portions Copyright (c) 1996-2017, 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 <pwd.h>
#include <unistd.h>
#include "common/username.h"
/*
* Returns the current user name in a static buffer
* On error, returns NULL and sets *errstr to point to a palloc'd message
*/
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(_("could not look up effective user ID %ld: %s"),
(long) user_id,
errno ? strerror(errno) : _("user does not exist"));
return NULL;
}
return pw->pw_name;
#else
/* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
/* "static" variable remains after function exit */
static char username[256 + 1];
DWORD len = sizeof(username);
*errstr = NULL;
if (!GetUserName(username, &len))
{
*errstr = psprintf(_("user name lookup failure: error code %lu"),
GetLastError());
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;
}