| 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. |
| 2 | |
| 3 | #include "precomp.h" |
| 4 | |
| 5 | HRESULT GetDomainFromServerName( |
| 6 | __deref_out_z LPWSTR* ppwzDomainName, |
| 7 | __in_z LPCWSTR wzServerName, |
| 8 | __in DWORD dwFlags |
| 9 | ) |
| 10 | { |
| 11 | HRESULT hr = S_OK; |
| 12 | DWORD er = ERROR_SUCCESS; |
| 13 | PDOMAIN_CONTROLLER_INFOW pDomainControllerInfo = NULL; |
| 14 | LPCWSTR wz = wzServerName ? wzServerName : L""; // initialize the domain to the provided server name (or empty string). |
| 15 | |
| 16 | // If the server name was not empty, try to get the domain name out of it. |
| 17 | if (*wz) |
| 18 | { |
| 19 | er = ::DsGetDcNameW(NULL, wz, NULL, NULL, dwFlags, &pDomainControllerInfo); |
| 20 | if (RPC_S_SERVER_UNAVAILABLE == er) |
| 21 | { |
| 22 | // MSDN says, if we get the above error code, try again with the "DS_FORCE_REDISCOVERY" flag. |
| 23 | er = ::DsGetDcNameW(NULL, wz, NULL, NULL, dwFlags | DS_FORCE_REDISCOVERY, &pDomainControllerInfo); |
| 24 | } |
| 25 | ExitOnWin32Error(er, hr, "Could not get domain name from server name: %ls", wz); |
| 26 | |
| 27 | if (pDomainControllerInfo->DomainControllerName) |
| 28 | { |
| 29 | // Skip the \\ prefix if present. |
| 30 | if ('\\' == *pDomainControllerInfo->DomainControllerName && '\\' == *(pDomainControllerInfo->DomainControllerName + 1)) |
| 31 | { |
| 32 | wz = pDomainControllerInfo->DomainControllerName + 2; |
| 33 | } |
| 34 | else |
| 35 | { |
| 36 | wz = pDomainControllerInfo->DomainControllerName; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | LExit: |
| 42 | // Note: we overwrite the error code here as failure to contact domain controller above is not a fatal error. |
| 43 | if (wz && *wz) |
| 44 | { |
| 45 | hr = StrAllocString(ppwzDomainName, wz, 0); |
| 46 | } |
| 47 | else // return NULL the server name ended up empty. |
| 48 | { |
| 49 | ReleaseNullStr(*ppwzDomainName); |
| 50 | hr = S_OK; |
| 51 | } |
| 52 | |
| 53 | if (pDomainControllerInfo) |
| 54 | { |
| 55 | ::NetApiBufferFree((LPVOID)pDomainControllerInfo); |
| 56 | } |
| 57 | |
| 58 | return hr; |
| 59 | } |