* pg_fe_getauthname * * Returns a pointer to malloc'd space containing whatever name the user * has authenticated to the system. If there is an error, return NULL, * and append a suitable error message to *errorMessage if that's not NULL. */
| 1080 | * and append a suitable error message to *errorMessage if that's not NULL. |
| 1081 | */ |
| 1082 | char * |
| 1083 | pg_fe_getauthname(PQExpBuffer errorMessage) |
| 1084 | { |
| 1085 | char *result = NULL; |
| 1086 | const char *name = NULL; |
| 1087 | |
| 1088 | #ifdef WIN32 |
| 1089 | /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */ |
| 1090 | char username[256 + 1]; |
| 1091 | DWORD namesize = sizeof(username); |
| 1092 | #else |
| 1093 | uid_t user_id = geteuid(); |
| 1094 | char pwdbuf[BUFSIZ]; |
| 1095 | struct passwd pwdstr; |
| 1096 | struct passwd *pw = NULL; |
| 1097 | int pwerr; |
| 1098 | #endif |
| 1099 | |
| 1100 | /* |
| 1101 | * Some users are using configure --enable-thread-safety-force, so we |
| 1102 | * might as well do the locking within our library to protect |
| 1103 | * pqGetpwuid(). In fact, application developers can use getpwuid() in |
| 1104 | * their application if they use the locking call we provide, or install |
| 1105 | * their own locking function using PQregisterThreadLock(). |
| 1106 | */ |
| 1107 | pglock_thread(); |
| 1108 | |
| 1109 | #ifdef WIN32 |
| 1110 | if (GetUserName(username, &namesize)) |
| 1111 | name = username; |
| 1112 | else if (errorMessage) |
| 1113 | appendPQExpBuffer(errorMessage, |
| 1114 | libpq_gettext("user name lookup failure: error code %lu\n"), |
| 1115 | GetLastError()); |
| 1116 | #else |
| 1117 | pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw); |
| 1118 | if (pw != NULL) |
| 1119 | name = pw->pw_name; |
| 1120 | else if (errorMessage) |
| 1121 | { |
| 1122 | if (pwerr != 0) |
| 1123 | appendPQExpBuffer(errorMessage, |
| 1124 | libpq_gettext("could not look up local user ID %d: %s\n"), |
| 1125 | (int) user_id, |
| 1126 | strerror_r(pwerr, pwdbuf, sizeof(pwdbuf))); |
| 1127 | else |
| 1128 | appendPQExpBuffer(errorMessage, |
| 1129 | libpq_gettext("local user with ID %d does not exist\n"), |
| 1130 | (int) user_id); |
| 1131 | } |
| 1132 | #endif |
| 1133 | |
| 1134 | if (name) |
| 1135 | { |
| 1136 | result = strdup(name); |
| 1137 | if (result == NULL && errorMessage) |
| 1138 | appendPQExpBufferStr(errorMessage, |
| 1139 | libpq_gettext("out of memory\n")); |
no test coverage detected