]> granicus.if.org Git - postgresql/blob - src/common/username.c
C comments: remove odd blank lines after #ifdef WIN32 lines
[postgresql] / src / common / username.c
1 /*-------------------------------------------------------------------------
2  *
3  * username.c
4  *        get user name
5  *
6  * Portions Copyright (c) 1996-2014, 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, or NULL on error and
30  * sets errstr
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(_("failed to 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         /* UNLEN = 256, 'static' variable remains after function exit */
54         static char username[256 + 1];
55         DWORD           len = sizeof(username) - 1;
56
57         if (!GetUserName(username, &len))
58         {
59                 *errstr = psprintf(_("user name lookup failure: %s"), strerror(errno));
60                 return NULL;
61         }
62
63         return username;
64 #endif
65 }
66
67
68 /*
69  * Returns the current user name in a static buffer or exits
70  */
71 const char *
72 get_user_name_or_exit(const char *progname)
73 {
74         const char *user_name;
75         char       *errstr;
76
77         user_name = get_user_name(&errstr);
78
79         if (!user_name)
80         {
81                 fprintf(stderr, "%s: %s\n", progname, errstr);
82                 exit(1);
83         }
84         return user_name;
85 }