Sometimes it is necessary to ask the operating system what
the current user name is and the domain that the user resides within.
bool
GetDomainAndUserName( CString& csDomainUIDNode )
{
bool bReturn = FALSE;
HANDLE hToken = 0;
do {
// Try to get a thread token. If that fails then try for
// one from the process. If that fails then we can't continue.
if(!OpenThreadToken( GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken ))
{
if( GetLastError() != ERROR_NO_TOKEN )
break;
if(!OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken ))
break;
}
// Extract the information from the token that we care about.
#define MY_BUFSIZE 512 // highly unlikely to exceed 512 bytes
UCHAR InfoBuffer[ MY_BUFSIZE ];
DWORD cbInfoBuffer = MY_BUFSIZE;
bReturn = GetTokenInformation( hToken,
TokenUser,
InfoBuffer,
cbInfoBuffer,
&cbInfoBuffer ) ? true : false;
if(!bReturn)
break;
// Convert into human readable format.
CString csDomain;
CString csUID;
unsigned long cchDomainName = 512;
unsigned long cchUserName = 512;
SID_NAME_USE snu;
bReturn = LookupAccountSid( NULL,
((PTOKEN_USER)InfoBuffer)->User.Sid,
csUID.GetBuffer( 512 ),
&cchUserName,
csDomain.GetBuffer( 512 ),
&cchDomainName,
&snu) ? true : false;
csDomain.ReleaseBuffer();
csUID.ReleaseBuffer();
if (!bReturn)
break;
// Get the machine's name.
CString csComputerName = _tgetenv( _T("COMPUTERNAME") );
// Combine all of the individual bits into our return string.
csDomainUIDNode.Format( _T("\\\\%s\\%s on '%s'"),
csDomain,
csUID,
sComputerName );
} while (false);
if ( hToken )
CloseHandle( hToken );
return bReturn;
}