]> granicus.if.org Git - postgresql/blob - src/common/username.c
Unlink static libraries before rebuilding them.
[postgresql] / src / common / username.c
1 /*-------------------------------------------------------------------------
2  *
3  * username.c
4  *        get user name
5  *
6  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        src/common/username.c
11  *
12  *-------------------------------------------------------------------------
13  */
14
15 #ifndef FRONTEND
16 #include "postgres.h"
17 #else
18 #include "postgres_fe.h"
19 #endif
20
21 #include <errno.h>
22 #include <pwd.h>
23 #include <unistd.h>
24 #include <sys/types.h>
25
26 #include "common/username.h"
27
28 /*
29  * Returns the current user name in a static buffer
30  * On error, returns NULL and sets *errstr to point to a palloc'd message
31  */
32 const char *
33 get_user_name(char **errstr)
34 {
35 #ifndef WIN32
36         struct passwd *pw;
37         uid_t           user_id = geteuid();
38
39         *errstr = NULL;
40
41         errno = 0;                                      /* clear errno before call */
42         pw = getpwuid(user_id);
43         if (!pw)
44         {
45                 *errstr = psprintf(_("could not look up effective user ID %ld: %s"),
46                                                    (long) user_id,
47                                                  errno ? strerror(errno) : _("user does not exist"));
48                 return NULL;
49         }
50
51         return pw->pw_name;
52 #else
53         /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
54         /* "static" variable remains after function exit */
55         static char username[256 + 1];
56         DWORD           len = sizeof(username);
57
58         *errstr = NULL;
59
60         if (!GetUserName(username, &len))
61         {
62                 *errstr = psprintf(_("user name lookup failure: error code %lu"),
63                                                    GetLastError());
64                 return NULL;
65         }
66
67         return username;
68 #endif
69 }
70
71
72 /*
73  * Returns the current user name in a static buffer or exits
74  */
75 const char *
76 get_user_name_or_exit(const char *progname)
77 {
78         const char *user_name;
79         char       *errstr;
80
81         user_name = get_user_name(&errstr);
82
83         if (!user_name)
84         {
85                 fprintf(stderr, "%s: %s\n", progname, errstr);
86                 exit(1);
87         }
88         return user_name;
89 }