Use getlogin_r() in GetUserName and map errno

This commit is contained in:
Andrew Schwartzmeyer
2015-08-03 12:53:39 -07:00
committed by Andrew Schwartzmeyer
parent f676c77a8e
commit b80da9ab4d
2 changed files with 52 additions and 0 deletions
+47
View File
@@ -12,6 +12,13 @@ const string utf8 = "UTF-8";
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724432(v=vs.85).aspx
// Sets errno to:
// ERROR_BAD_ENVIRONMENT - locale is not UTF-8
// ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files
// ERROR_NO_ASSOCIATION - calling process has no controlling terminal
// ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string
// ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file
// ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure
// ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal
// ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code
//
// Returns:
// 1 - succeeded
@@ -28,6 +35,46 @@ BOOL GetUserName(WCHAR_T* lpBuffer, LPDWORD lpnSize)
return 0;
}
// Get username from system in a thread-safe manner
char userName[*lpnSize];
int err = getlogin_r(userName, *lpnSize);
// Map errno to Win32 Error Codes
if (err != 0) {
switch (errno) {
case EMFILE:
case ENFILE:
errno = ERROR_TOO_MANY_OPEN_FILES;
break;
case ENXIO:
errno = ERROR_NO_ASSOCIATION;
break;
case ERANGE:
errno = ERROR_INSUFFICIENT_BUFFER;
break;
case ENOENT:
errno = ERROR_NO_SUCH_USER;
break;
case ENOMEM:
errno = ERROR_OUTOFMEMORY;
break;
case ENOTTY:
errno = ERROR_NO_ASSOCIATION;
break;
default:
errno = ERROR_INVALID_FUNCTION;
}
return 0;
}
// TODO: Convert to char* to wchar* (UTF-8 to UTF-16 LE w/o BOM)
// Unfortunately codecvt is not yet supported by G++, othwerise:
// wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> conversion;
// TODO: Use PAL's Unicode converters
// TODO: set the lpnSize to the userName length (see msdn)
return 1;
}
+5
View File
@@ -72,6 +72,11 @@
#define ERROR_INVALID_PARAMETER 87
#define ERROR_OUTOFMEMORY 14
#define ERROR_BAD_ENVIRONMENT 0x0000000A
#define ERROR_TOO_MANY_OPEN_FILES 0x00000004
#define ERROR_INSUFFICIENT_BUFFER 0x0000007A
#define ERROR_NO_ASSOCIATION 0x00000483
#define ERROR_NO_SUCH_USER 0x00000525
#define ERROR_INVALID_FUNCTION 0x00000001
#define MAX_PATH 0x00000104
typedef unsigned long long uint64;
#endif