jsonpath scanner: reentrant scanner
[pgsql.git] / src / common / username.c
blobacaeb13d2e69619ca38952f31b55e0ff1cff8a54
1 /*-------------------------------------------------------------------------
3 * username.c
4 * get user name
6 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * IDENTIFICATION
10 * src/common/username.c
12 *-------------------------------------------------------------------------
15 #ifndef FRONTEND
16 #include "postgres.h"
17 #else
18 #include "postgres_fe.h"
19 #endif
21 #include <pwd.h>
22 #include <unistd.h>
24 #include "common/username.h"
27 * Returns the current user name in a static buffer
28 * On error, returns NULL and sets *errstr to point to a palloc'd message
30 const char *
31 get_user_name(char **errstr)
33 #ifndef WIN32
34 struct passwd *pw;
35 uid_t user_id = geteuid();
37 *errstr = NULL;
39 errno = 0; /* clear errno before call */
40 pw = getpwuid(user_id);
41 if (!pw)
43 *errstr = psprintf(_("could not look up effective user ID %ld: %s"),
44 (long) user_id,
45 errno ? strerror(errno) : _("user does not exist"));
46 return NULL;
49 return pw->pw_name;
50 #else
51 /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
52 /* "static" variable remains after function exit */
53 static char username[256 + 1];
54 DWORD len = sizeof(username);
56 *errstr = NULL;
58 if (!GetUserName(username, &len))
60 *errstr = psprintf(_("user name lookup failure: error code %lu"),
61 GetLastError());
62 return NULL;
65 return username;
66 #endif
71 * Returns the current user name in a static buffer or exits
73 const char *
74 get_user_name_or_exit(const char *progname)
76 const char *user_name;
77 char *errstr;
79 user_name = get_user_name(&errstr);
81 if (!user_name)
83 fprintf(stderr, "%s: %s\n", progname, errstr);
84 exit(1);
86 return user_name;