Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7819 lines
218 KiB

  1. //*************************************************************
  2. //
  3. // Utility functions
  4. //
  5. // Microsoft Confidential
  6. // Copyright (c) Microsoft Corporation 1995
  7. // All rights reserved
  8. //
  9. //*************************************************************
  10. #include "uenv.h"
  11. #include <iphlpapi.h>
  12. #include <winsock2.h>
  13. #include <mswsock.h>
  14. #include <Aclapi.h>
  15. #include <windns.h>
  16. #include "strsafe.h"
  17. #define PCOMMON_IMPL
  18. #include "pcommon.h"
  19. #define NETWORK_PROVIDER L"System\\CurrentControlSet\\Services\\lanmanworkstation\\NetworkProvider"
  20. #define PROVIDER_NAME L"Name"
  21. INT g_iMachineRole = -1;
  22. LPVOID g_lpTestData = NULL;
  23. CRITICAL_SECTION *g_PingCritSec;
  24. LPCTSTR c_szUNCFilePrefix = TEXT("\\\\?\\UNC\\");
  25. LPCTSTR c_szLocalFilePrefix = TEXT("\\\\?\\");
  26. const DWORD c_dwLocalFilePrefixLen = sizeof(c_szLocalFilePrefix) / sizeof(TCHAR); // Length of szLocalFilePrefix in unit of TCHAR.
  27. //
  28. // Local function proto-types
  29. //
  30. DWORD IsSlowLink (HKEY hKeyRoot, LPTSTR lpDCAddress, BOOL *bSlow, DWORD* pdwAdapterIndex );
  31. DWORD GetNetworkProvider(NETRESOURCE *psNR);
  32. #ifdef __cplusplus
  33. extern "C" {
  34. #endif
  35. DWORD APIENTRY
  36. NPAddConnection3ForCSCAgent(
  37. HWND hwndOwner,
  38. LPNETRESOURCE lpNetResource,
  39. LPTSTR pszPassword,
  40. LPTSTR pszUserName,
  41. DWORD dwFlags,
  42. BOOL *lpfIsDfsConnect
  43. );
  44. DWORD APIENTRY
  45. NPCancelConnectionForCSCAgent (
  46. LPCTSTR szName,
  47. BOOL fForce
  48. );
  49. #ifdef __cplusplus
  50. }
  51. #endif
  52. DWORD
  53. GetGroupPolicyNetworkName( LPWSTR szNetworkName, LPDWORD pdwByteCount )
  54. {
  55. HKEY hKey;
  56. DWORD dwError = ERROR_SUCCESS;
  57. dwError = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
  58. L"Software\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\History",
  59. 0,
  60. KEY_READ,
  61. &hKey );
  62. if ( dwError == ERROR_SUCCESS )
  63. {
  64. DWORD dwType = REG_SZ;
  65. dwError = RegQueryValueEx( hKey,
  66. L"NetworkName",
  67. 0,
  68. &dwType,
  69. (LPBYTE) szNetworkName,
  70. pdwByteCount );
  71. RegCloseKey (hKey);
  72. }
  73. return dwError;
  74. }
  75. int
  76. GetNetworkName( LPWSTR* pszName, DWORD dwAdapterIndex )
  77. {
  78. int iError;
  79. WSAQUERYSET restrictions;
  80. GUID WsMobilityServiceClassGuid = NLA_SERVICE_CLASS_GUID;
  81. WSADATA wsaData;
  82. HANDLE hQuery;
  83. PWSAQUERYSET pResult = 0;
  84. DWORD length;
  85. BOOL bFinish = FALSE;
  86. PWS2_32_API pWS2_32 = Loadws2_32Api();
  87. PIPHLPAPI_API pIpHlpApi = LoadIpHlpApi();
  88. if ( !pWS2_32 )
  89. {
  90. return GetLastError();
  91. }
  92. if ( !pIpHlpApi )
  93. {
  94. return GetLastError();
  95. }
  96. //
  97. // Initialize Winsock
  98. //
  99. iError = pWS2_32->pfnWSAStartup( MAKEWORD(2, 2), &wsaData );
  100. if ( iError )
  101. {
  102. return iError;
  103. }
  104. //
  105. // Initialize the query for network names
  106. //
  107. ZeroMemory(&restrictions, sizeof(restrictions));
  108. restrictions.dwSize = sizeof(restrictions);
  109. restrictions.lpServiceClassId = &WsMobilityServiceClassGuid;
  110. restrictions.dwNameSpace = NS_NLA;
  111. //
  112. // Make sure we do not ask for the blobs that take a long time to get
  113. //
  114. if ( pWS2_32->pfnWSALookupServiceBegin( &restrictions, LUP_NOCONTAINERS, &hQuery ) )
  115. {
  116. iError = pWS2_32->pfnWSAGetLastError();
  117. pWS2_32->pfnWSACleanup();
  118. return iError;
  119. }
  120. //
  121. // Start loop of getting network names
  122. //
  123. while ( !bFinish )
  124. {
  125. int error;
  126. length = 0;
  127. //
  128. // Do call twice, first to get size of buffer for second call
  129. //
  130. error = pWS2_32->pfnWSALookupServiceNext( hQuery, 0, &length, 0 );
  131. iError = pWS2_32->pfnWSAGetLastError();
  132. if ( iError != WSAEFAULT && iError != WSA_E_NO_MORE )
  133. {
  134. break;
  135. }
  136. pResult = (PWSAQUERYSET) LocalAlloc( LPTR, length );
  137. if ( !pResult )
  138. {
  139. iError = GetLastError();
  140. break;
  141. }
  142. //
  143. // Get a network name
  144. //
  145. if ( !pWS2_32->pfnWSALookupServiceNext( hQuery, 0, &length, pResult ) )
  146. {
  147. if ( pResult->lpBlob )
  148. {
  149. int next;
  150. NLA_BLOB *blob = (NLA_BLOB *)pResult->lpBlob->pBlobData;
  151. do {
  152. //
  153. // We are looking for the blob containing the network GUID
  154. //
  155. if ( blob->header.type == NLA_INTERFACE )
  156. {
  157. //
  158. // "\\DEVICE\\TCPIP_" + "{GUID"
  159. //
  160. WCHAR szAdapter[64];
  161. DWORD dwAdapter;
  162. WCHAR* szEnd = NULL;
  163. size_t cchRemain = 0;
  164. HRESULT hr = E_FAIL;
  165. //
  166. // Convert guid to device name
  167. //
  168. StringCchCopyExW( szAdapter,
  169. ARRAYSIZE(szAdapter),
  170. L"\\DEVICE\\TCPIP_",
  171. &szEnd,
  172. &cchRemain,
  173. 0);
  174. if (MultiByteToWideChar(CP_ACP,
  175. 0,
  176. (LPCSTR)blob->data.interfaceData.adapterName,
  177. -1,
  178. szEnd,
  179. cchRemain))
  180. {
  181. //
  182. // Get the index for the network
  183. //
  184. if ( pIpHlpApi->pfnGetAdapterIndex( szAdapter, &dwAdapter ) == NO_ERROR )
  185. {
  186. //
  187. // Is it the index we are after
  188. //
  189. if ( dwAdapterIndex == dwAdapter && pResult->lpszServiceInstanceName )
  190. {
  191. //
  192. // Yes, copy the network name into the buffer
  193. //
  194. DWORD dwSize = sizeof( WCHAR ) * ( wcslen(pResult->lpszServiceInstanceName) + 1 );
  195. *pszName = (LPWSTR) LocalAlloc( LPTR, dwSize );
  196. if ( !*pszName )
  197. {
  198. iError = GetLastError();
  199. }
  200. else
  201. {
  202. StringCbCopyW( *pszName, dwSize, pResult->lpszServiceInstanceName );
  203. bFinish = TRUE;
  204. iError = 0;
  205. }
  206. }
  207. }
  208. }
  209. else
  210. {
  211. iError = GetLastError();
  212. }
  213. }
  214. //
  215. // There maybe multiple blobs for each interface so make sure we find them all
  216. //
  217. next = blob->header.nextOffset;
  218. blob = (NLA_BLOB *)(((char *)blob) + next);
  219. } while ( next );
  220. }
  221. LocalFree( pResult );
  222. }
  223. else
  224. {
  225. iError = pWS2_32->pfnWSAGetLastError();
  226. if ( iError == WSA_E_NO_MORE )
  227. {
  228. iError = 0;
  229. }
  230. LocalFree( pResult );
  231. break;
  232. }
  233. }
  234. //
  235. // tidy up
  236. //
  237. pWS2_32->pfnWSALookupServiceEnd( hQuery );
  238. pWS2_32->pfnWSACleanup();
  239. return iError;
  240. }
  241. //*************************************************************
  242. //
  243. // ProduceWFromA()
  244. //
  245. // Purpose: Creates a buffer for a Unicode string and copies
  246. // the ANSI text into it (converting in the process)
  247. //
  248. // Parameters: pszA - ANSI string
  249. //
  250. //
  251. // Return: Unicode pointer if successful
  252. // NULL if an error occurs
  253. //
  254. // Comments: The caller needs to free this pointer.
  255. //
  256. //
  257. // History: Date Author Comment
  258. // 5/24/95 ericflo Ported
  259. //
  260. //*************************************************************
  261. LPWSTR ProduceWFromA(LPCSTR pszA)
  262. {
  263. LPWSTR pszW;
  264. int cch;
  265. if (!pszA)
  266. return (LPWSTR)pszA;
  267. cch = MultiByteToWideChar(CP_ACP, 0, pszA, -1, NULL, 0);
  268. if (cch == 0)
  269. cch = 1;
  270. pszW = LocalAlloc(LPTR, cch * sizeof(WCHAR));
  271. if (pszW) {
  272. if (!MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszA, -1, pszW, cch)) {
  273. LocalFree(pszW);
  274. pszW = NULL;
  275. }
  276. }
  277. return pszW;
  278. }
  279. //*************************************************************
  280. //
  281. // ProduceAFromW()
  282. //
  283. // Purpose: Creates a buffer for an ANSI string and copies
  284. // the Unicode text into it (converting in the process)
  285. //
  286. // Parameters: pszW - Unicode string
  287. //
  288. //
  289. // Return: ANSI pointer if successful
  290. // NULL if an error occurs
  291. //
  292. // Comments: The caller needs to free this pointer.
  293. //
  294. //
  295. // History: Date Author Comment
  296. // 5/24/95 ericflo Ported
  297. //
  298. //*************************************************************
  299. LPSTR ProduceAFromW(LPCWSTR pszW)
  300. {
  301. LPSTR pszA;
  302. int cch;
  303. if (!pszW)
  304. return (LPSTR)pszW;
  305. cch = WideCharToMultiByte(CP_ACP, 0, pszW, -1, NULL, 0, NULL, NULL);
  306. if (cch == 0)
  307. cch = 1;
  308. pszA = LocalAlloc(LPTR, cch * sizeof(char));
  309. if (pszA) {
  310. if (!WideCharToMultiByte(CP_ACP, 0, pszW, -1, pszA, cch, NULL, NULL)) {
  311. LocalFree(pszA);
  312. pszA = NULL;
  313. }
  314. }
  315. return pszA;
  316. }
  317. //*************************************************************
  318. //
  319. // CheckSlash()
  320. //
  321. // Purpose: Checks for an ending slash and adds one if
  322. // it is missing.
  323. //
  324. // Parameters: lpDir - directory
  325. //
  326. // Return: Pointer to the end of the string
  327. //
  328. // Comments:
  329. //
  330. // History: Date Author Comment
  331. // 6/19/95 ericflo Created
  332. //
  333. //*************************************************************
  334. LPTSTR CheckSlash (LPTSTR lpDir)
  335. {
  336. LPTSTR lpEnd;
  337. lpEnd = lpDir + lstrlen(lpDir);
  338. if (*(lpEnd - 1) != TEXT('\\')) {
  339. *lpEnd = TEXT('\\');
  340. lpEnd++;
  341. *lpEnd = TEXT('\0');
  342. }
  343. return lpEnd;
  344. }
  345. //*************************************************************
  346. //
  347. // CheckSlashEx()
  348. //
  349. // Purpose: Checks for an ending slash and adds one if
  350. // it is missing. It will take the buffer size
  351. // to make it safe (not overflow the buffer).
  352. //
  353. // Parameters: lpDir - directory
  354. // cchBuffer - buffer size
  355. // pcchRemain - buffer remained after patch '\'
  356. // can be NULL if not needed.
  357. //
  358. // Return: Pointer to the end of the string, NULL for
  359. // overflowed buffer.
  360. //
  361. // Comments:
  362. //
  363. // History: Date Author Comment
  364. // 06/19/95 ericflo Created
  365. // 02/11/02 mingzhu Make it safe
  366. //
  367. //*************************************************************
  368. LPTSTR CheckSlashEx(LPTSTR lpDir, UINT cchBuffer, UINT* pcchRemain )
  369. {
  370. LPTSTR lpEnd = NULL;
  371. UINT cchLen = lstrlen(lpDir);
  372. if (cchLen >= cchBuffer - 1) // Overflowed or full buffer
  373. {
  374. DmAssert(cchLen == cchBuffer - 1); // Should never happen
  375. if (pcchRemain)
  376. *pcchRemain = 0;
  377. lpEnd = NULL;
  378. }
  379. else
  380. {
  381. lpEnd = lpDir + cchLen;
  382. if (pcchRemain)
  383. *pcchRemain = cchBuffer - 1 - cchLen;
  384. if (*(lpEnd - 1) != TEXT('\\'))
  385. {
  386. *lpEnd = TEXT('\\');
  387. lpEnd++;
  388. *lpEnd = TEXT('\0');
  389. if (pcchRemain)
  390. (*pcchRemain) --;
  391. }
  392. }
  393. return lpEnd;
  394. }
  395. //*************************************************************
  396. //
  397. // CheckSemicolon()
  398. //
  399. // Purpose: Checks for an ending slash and adds one if
  400. // it is missing.
  401. //
  402. // Parameters: lpDir - directory
  403. //
  404. // Return: Pointer to the end of the string
  405. //
  406. // Comments:
  407. //
  408. // History: Date Author Comment
  409. // 6/19/95 ericlfo Created
  410. //
  411. //*************************************************************
  412. LPTSTR CheckSemicolon (LPTSTR lpDir)
  413. {
  414. LPTSTR lpEnd;
  415. lpEnd = lpDir + lstrlen(lpDir);
  416. if (*(lpEnd - 1) != TEXT(';')) {
  417. *lpEnd = TEXT(';');
  418. lpEnd++;
  419. *lpEnd = TEXT('\0');
  420. }
  421. return lpEnd;
  422. }
  423. //*************************************************************
  424. //
  425. // Delnode_Recurse()
  426. //
  427. // Purpose: Recursive delete function for Delnode
  428. //
  429. // Parameters: lpDir - Full Directory Path.
  430. // dwSize - Allocated size of the working buffer
  431. //
  432. // Return: TRUE if successful
  433. // FALSE if an error occurs
  434. //
  435. // Comments:
  436. //
  437. // History: Date Author Comment
  438. // 8/10/95 ericflo Created
  439. // 04/08/2002 mingzhu Added functionality to take ownership
  440. //
  441. // Notes:
  442. // This function modifies the working buffer.
  443. // This doesn't maintain the right error code. It ignores all
  444. // errors and tries to delete as much as possible..
  445. //
  446. //*************************************************************
  447. BOOL Delnode_Recurse (LPTSTR lpDir, DWORD dwSize)
  448. {
  449. BOOL bOwn = FALSE, bRetVal = FALSE;
  450. LPTSTR lpEnd = NULL, lpWrkDir = NULL;
  451. WIN32_FIND_DATA* pfd = NULL;
  452. HANDLE hFile;
  453. DWORD dwWrkDirSize;
  454. DWORD cchEnd; // buffer size for lpEnd
  455. HRESULT hr;
  456. BOOL bDeleteSuccess;
  457. //
  458. // Verbose output
  459. //
  460. DebugMsg((DM_VERBOSE, TEXT("Delnode_Recurse: Entering, lpDir = <%s>"), lpDir));
  461. //
  462. // Each filename or a directory has to be less than MAX_PATH in the worst case.
  463. // So make sure that we have at least MAX_PATH + 2 (for a slash and '\0'
  464. // space left in the working buffer case.
  465. //
  466. // In the normal case, when we have a path of length ~MAX_PATH it will do only
  467. // 1 allocation
  468. //
  469. if ((DWORD)(lstrlen(lpDir) + MAX_PATH+2) > (dwSize)) {
  470. dwWrkDirSize = dwSize+2*MAX_PATH;
  471. lpWrkDir = (LPTSTR)LocalAlloc(LPTR, dwWrkDirSize*sizeof(TCHAR));
  472. if (!lpWrkDir) {
  473. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: Couldn't allocate memory for working buffer. Error - %d"), GetLastError()));
  474. goto Exit;
  475. }
  476. StringCchCopy(lpWrkDir, dwWrkDirSize, lpDir);
  477. bOwn = TRUE;
  478. }
  479. else {
  480. lpWrkDir = lpDir;
  481. dwWrkDirSize = dwSize;
  482. }
  483. //
  484. // append "*.*" to the directory name
  485. //
  486. lpEnd = CheckSlashEx(lpWrkDir, dwWrkDirSize, &cchEnd);
  487. StringCchCopy(lpEnd, cchEnd, c_szStarDotStar);
  488. //
  489. // Allocate fd in the heap, reduce stack usage
  490. //
  491. pfd = (WIN32_FIND_DATA*) LocalAlloc(LPTR, sizeof(WIN32_FIND_DATA));
  492. if (!pfd)
  493. {
  494. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: Couldn't allocate memory for WIN32_FIND_DATA. Error - %d"), GetLastError()));
  495. goto Exit;
  496. }
  497. //
  498. // Find the first file
  499. //
  500. hFile = FindFirstFile(lpWrkDir, pfd);
  501. if (hFile == INVALID_HANDLE_VALUE) {
  502. if ((GetLastError() == ERROR_FILE_NOT_FOUND) || (GetLastError() == ERROR_PATH_NOT_FOUND))
  503. {
  504. bRetVal = TRUE;
  505. goto Exit;
  506. }
  507. else if ((GetLastError() == ERROR_ACCESS_DENIED))
  508. {
  509. //
  510. // Now we got an access denied, we will try to take the ownership of the directory and
  511. // add admin full access to it so that we can recurse into it and delete it.This only
  512. // works when the caller is an admin.
  513. //
  514. *lpEnd = TEXT('\0'); // Restore the original name
  515. hr = TakeOwnership(lpWrkDir);
  516. if (FAILED(hr))
  517. {
  518. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: TakeOwnership failed. Error = 0x%08X"), hr));
  519. goto Exit;
  520. }
  521. hr = AddAdminAccess(lpWrkDir);
  522. if (FAILED(hr))
  523. {
  524. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: AddAdminAccess failed. Error = 0x%08X"), hr));
  525. goto Exit;
  526. }
  527. // Append "*.*" and try again
  528. StringCchCopy(lpEnd, cchEnd, c_szStarDotStar);
  529. hFile = FindFirstFile(lpWrkDir, pfd);
  530. if (hFile == INVALID_HANDLE_VALUE)
  531. {
  532. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: FindFirstFile failed. Error = %d"), GetLastError()));
  533. goto Exit;
  534. }
  535. }
  536. else {
  537. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: FindFirstFile failed. Error = %d"), GetLastError()));
  538. goto Exit;
  539. }
  540. }
  541. do {
  542. //
  543. // Check for "." and ".."
  544. //
  545. if (!lstrcmpi(pfd->cFileName, c_szDot)) {
  546. continue;
  547. }
  548. if (!lstrcmpi(pfd->cFileName, c_szDotDot)) {
  549. continue;
  550. }
  551. //
  552. // Verbose output
  553. //
  554. DebugMsg((DM_VERBOSE, TEXT("Delnode_Recurse: FindFile found: <%s>"), pfd->cFileName));
  555. // Note that fd.cFileName will not exceed MAX_PATH, so the buffer is
  556. // always large enough to hold it in this algorithm.
  557. StringCchCopy(lpEnd, cchEnd, pfd->cFileName);
  558. if (pfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  559. //
  560. // Found a directory.
  561. //
  562. if (pfd->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  563. {
  564. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: Found a reparse point <%s>, Will not recurse into it!"), lpWrkDir));
  565. }
  566. else
  567. {
  568. Delnode_Recurse(lpWrkDir, dwWrkDirSize);
  569. // ignore errors and go ahead..
  570. StringCchCopy(lpEnd, cchEnd, pfd->cFileName);
  571. }
  572. if (pfd->dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
  573. pfd->dwFileAttributes &= ~FILE_ATTRIBUTE_READONLY;
  574. SetFileAttributes (lpWrkDir, pfd->dwFileAttributes);
  575. }
  576. if (!RemoveDirectory (lpWrkDir))
  577. {
  578. bDeleteSuccess = FALSE;
  579. if (GetLastError() == ERROR_ACCESS_DENIED)
  580. {
  581. if ( SUCCEEDED(TakeOwnership(lpWrkDir)) &&
  582. SUCCEEDED(AddAdminAccess(lpWrkDir)) &&
  583. RemoveDirectory(lpWrkDir) )
  584. {
  585. bDeleteSuccess = TRUE;
  586. }
  587. }
  588. if (!bDeleteSuccess)
  589. {
  590. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: Failed to delete directory <%s>. Error = %d"),
  591. lpWrkDir, GetLastError()));
  592. }
  593. }
  594. } else {
  595. //
  596. // We found a file. Set the file attributes,
  597. // and try to delete it.
  598. //
  599. if ((pfd->dwFileAttributes & FILE_ATTRIBUTE_READONLY) ||
  600. (pfd->dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)) {
  601. SetFileAttributes (lpWrkDir, FILE_ATTRIBUTE_NORMAL);
  602. }
  603. if (!DeleteFile (lpWrkDir))
  604. {
  605. bDeleteSuccess = FALSE;
  606. if (GetLastError() == ERROR_ACCESS_DENIED)
  607. {
  608. if ( SUCCEEDED(TakeOwnership(lpWrkDir)) &&
  609. SUCCEEDED(AddAdminAccess(lpWrkDir)) &&
  610. DeleteFile(lpWrkDir) )
  611. {
  612. bDeleteSuccess = TRUE;
  613. }
  614. }
  615. if (!bDeleteSuccess)
  616. {
  617. DebugMsg((DM_WARNING, TEXT("Delnode_Recurse: Failed to delete <%s>. Error = %d"),
  618. pfd->cFileName, GetLastError()));
  619. }
  620. }
  621. }
  622. //
  623. // Find the next entry
  624. //
  625. } while (FindNextFile(hFile, pfd));
  626. //
  627. // Close the search handle
  628. //
  629. FindClose(hFile);
  630. //
  631. // Success.
  632. //
  633. DebugMsg((DM_VERBOSE, TEXT("Delnode_Recurse: Leaving <%s>"), lpDir));
  634. bRetVal = TRUE;
  635. Exit:
  636. if (bOwn)
  637. LocalFree(lpWrkDir);
  638. if (pfd)
  639. LocalFree(pfd);
  640. return bRetVal;
  641. }
  642. //*************************************************************
  643. //
  644. // Delnode()
  645. //
  646. // Purpose: Recursive function that deletes files and
  647. // directories.
  648. //
  649. // Parameters: lpDir - Directory
  650. //
  651. // Return: TRUE if successful
  652. // FALSE if an error occurs
  653. //
  654. // Comments:
  655. //
  656. // History: Date Author Comment
  657. // 6/23/95 ericflo Created
  658. // 6/27/00 santanuc modified to allow deletion of file with path length > MAX_PATH
  659. //
  660. //*************************************************************
  661. BOOL Delnode (LPTSTR lpDir)
  662. {
  663. LPTSTR lpWrkDir = NULL;
  664. DWORD dwWrkDirSize;
  665. BOOL bRetVal = FALSE;
  666. lpWrkDir = SupportLongFileName(lpDir, &dwWrkDirSize);
  667. if (!lpWrkDir) {
  668. DebugMsg((DM_WARNING, TEXT("Delnode: Failed to Allocate memory. Error = %d"),
  669. GetLastError()));
  670. goto Exit;
  671. }
  672. if (!Delnode_Recurse (lpWrkDir, dwWrkDirSize)) {
  673. DebugMsg((DM_WARNING, TEXT("Delnode: Delnode recurse failed with error %d"),
  674. GetLastError()));
  675. }
  676. if (!RemoveDirectory (lpDir)) {
  677. DWORD dwError;
  678. dwError = GetLastError();
  679. if ((dwError != ERROR_FILE_NOT_FOUND) &&
  680. (dwError != ERROR_PATH_NOT_FOUND)) {
  681. DebugMsg((DM_VERBOSE, TEXT("Delnode: Failed to delete directory <%s>. Error = %d"),
  682. lpDir, dwError));
  683. }
  684. goto Exit;
  685. }
  686. bRetVal = TRUE;
  687. DebugMsg((DM_VERBOSE, TEXT("Delnode: Deleted directory <%s> successfully."), lpDir));
  688. Exit:
  689. if (lpWrkDir) {
  690. LocalFree(lpWrkDir);
  691. }
  692. return bRetVal;
  693. }
  694. //*************************************************************
  695. //
  696. // CreateSystemDirectory()
  697. //
  698. // Purpose: A directory with system bit turned on can be created using
  699. // CreateSystemDirectory.
  700. //
  701. // This API causes a system directory with the specified pathname to be
  702. // created. If the underlying file system supports security on files
  703. // and directories, then the SecurityDescriptor argument is applied to
  704. // the new directory.
  705. //
  706. // This call is similar to DOS (int 21h, function 39h) and OS/2's
  707. // DosCreateDir.
  708. //
  709. //
  710. // Parameters: lpPathName - Supplies the pathname of the system directory to be created.
  711. // lpSecurityAttributes - An optional parameter that, if present, and
  712. // supported on the target file system supplies a security
  713. // descriptor for the new directory.
  714. //
  715. //
  716. // Return: TRUE - The operation was successful.
  717. // FALSE/NULL - The operation failed. Extended error status is available
  718. // using GetLastError.
  719. //
  720. // Comments: This function is exactly same as CreateDirectory API with the exception
  721. // that the directory is created using attribute FILE_ATTRIBUTE_SYSTEM.
  722. // This allows newly created directory to not inherit the encryption property
  723. // from parent directory if the parent directory is encrypted.
  724. //
  725. // History: Date Author Comments
  726. // 07/18/00 santanuc To avoid deadlock situation when Documents and Settings
  727. // directory is encrypted.
  728. //
  729. //*************************************************************
  730. BOOL CreateSystemDirectory(LPCTSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
  731. {
  732. NTSTATUS Status;
  733. OBJECT_ATTRIBUTES Obja;
  734. HANDLE Handle;
  735. UNICODE_STRING FileName;
  736. IO_STATUS_BLOCK IoStatusBlock;
  737. BOOLEAN TranslationStatus;
  738. RTL_RELATIVE_NAME_U RelativeName;
  739. PVOID FreeBuffer;
  740. ULONG dwErrorCode;
  741. // Note : ANSI version may cause error calling the following
  742. TranslationStatus = RtlDosPathNameToRelativeNtPathName_U( lpPathName,
  743. &FileName,
  744. NULL,
  745. &RelativeName);
  746. if ( !TranslationStatus ) {
  747. SetLastError(ERROR_PATH_NOT_FOUND);
  748. return FALSE;
  749. }
  750. //
  751. // dont create a directory unless there is room in the directory for
  752. // at least an 8.3 name. This way everyone will be able to delete all
  753. // files in the directory by using del *.* which expands to path+\*.*
  754. //
  755. if ( FileName.Length > ((MAX_PATH-12)<<1) ) {
  756. DWORD L;
  757. LPWSTR lp;
  758. if ( !(lpPathName[0] == TEXT('\\') && lpPathName[1] == TEXT('\\') &&
  759. lpPathName[2] == TEXT('?') && lpPathName[3] == TEXT('\\')) ) {
  760. L = GetFullPathNameW(lpPathName,0,NULL,&lp);
  761. if ( !L || L+12 > MAX_PATH ) {
  762. RtlReleaseRelativeName(&RelativeName);
  763. RtlFreeHeap(RtlProcessHeap(), 0,FileName.Buffer);
  764. SetLastError(ERROR_FILENAME_EXCED_RANGE);
  765. return FALSE;
  766. }
  767. }
  768. }
  769. FreeBuffer = FileName.Buffer;
  770. if ( RelativeName.RelativeName.Length ) {
  771. FileName = RelativeName.RelativeName;
  772. }
  773. else {
  774. RelativeName.ContainingDirectory = NULL;
  775. }
  776. InitializeObjectAttributes( &Obja,
  777. &FileName,
  778. OBJ_CASE_INSENSITIVE,
  779. RelativeName.ContainingDirectory,
  780. NULL );
  781. if ( ARGUMENT_PRESENT(lpSecurityAttributes) ) {
  782. Obja.SecurityDescriptor = lpSecurityAttributes->lpSecurityDescriptor;
  783. }
  784. // Creating the directory with attribute FILE_ATTRIBUTE_SYSTEM to avoid inheriting encryption
  785. // property from parent directory
  786. Status = NtCreateFile( &Handle,
  787. FILE_LIST_DIRECTORY | SYNCHRONIZE,
  788. &Obja,
  789. &IoStatusBlock,
  790. NULL,
  791. FILE_ATTRIBUTE_SYSTEM,
  792. FILE_SHARE_READ | FILE_SHARE_WRITE,
  793. FILE_CREATE,
  794. FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT,
  795. NULL,
  796. 0L );
  797. RtlReleaseRelativeName(&RelativeName);
  798. RtlFreeHeap(RtlProcessHeap(), 0,FreeBuffer);
  799. if ( NT_SUCCESS(Status) ) {
  800. NtClose(Handle);
  801. return TRUE;
  802. }
  803. else {
  804. if ( RtlIsDosDeviceName_U((LPWSTR)lpPathName) ) {
  805. Status = STATUS_NOT_A_DIRECTORY;
  806. }
  807. // Since RtlNtStatusToDosError function can't convert STATUS_TIMEOUT, we have to
  808. // do it explicitly
  809. if (Status == STATUS_TIMEOUT) {
  810. SetLastError(ERROR_TIMEOUT);
  811. }
  812. else {
  813. dwErrorCode = RtlNtStatusToDosError( Status );
  814. SetLastError( dwErrorCode );
  815. }
  816. return FALSE;
  817. }
  818. }
  819. //*************************************************************
  820. //
  821. // CreateNestedDirectory()
  822. //
  823. // Purpose: Creates a subdirectory and all it's parents
  824. // if necessary using CreateNestedDirectoryEx.
  825. //
  826. // Parameters: lpDirectory - Directory name
  827. // lpSecurityAttributes - Security Attributes
  828. //
  829. // Return: > 0 if successful
  830. // 0 if an error occurs
  831. //
  832. // Comments:
  833. //
  834. // History: Date Author Comment
  835. // 7/18/00 santanuc Created
  836. //
  837. //*************************************************************
  838. UINT CreateNestedDirectory(LPCTSTR lpDirectory, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
  839. {
  840. // Call CreateNestedDirectoryEx with inherit encryption property
  841. return CreateNestedDirectoryEx(lpDirectory, lpSecurityAttributes, TRUE);
  842. }
  843. //*************************************************************
  844. //
  845. // CreateNestedDirectoryEx()
  846. //
  847. // Purpose: Creates a subdirectory and all it's parents
  848. // if necessary.
  849. //
  850. // Parameters: lpDirectory - Directory name
  851. // lpSecurityAttributes - Security Attributes
  852. // bInheritEncryption - Flag indicating whether newly created directory should inherit
  853. // encryption property from parent directory.
  854. //
  855. // Return: > 0 if successful
  856. // 0 if an error occurs
  857. //
  858. // Comments:
  859. //
  860. // History: Date Author Comment
  861. // 8/08/95 ericflo Created
  862. // 7/18/00 santanuc added a new flag bInheritEncryption to avoid deadlock when
  863. // Documents and Settings directory is encrypted.
  864. //
  865. //*************************************************************
  866. UINT CreateNestedDirectoryEx(LPCTSTR lpDirectory, LPSECURITY_ATTRIBUTES lpSecurityAttributes, BOOL bInheritEncryption)
  867. {
  868. TCHAR szDirectory[2*MAX_PATH];
  869. LPTSTR lpEnd;
  870. WIN32_FILE_ATTRIBUTE_DATA fad;
  871. //
  872. // Check for NULL pointer
  873. //
  874. if (!lpDirectory || !(*lpDirectory)) {
  875. DebugMsg((DM_WARNING, TEXT("CreateNestedDirectory: Received a NULL pointer.")));
  876. return 0;
  877. }
  878. //
  879. // Test if the directory exists already
  880. //
  881. if (GetFileAttributesEx (lpDirectory, GetFileExInfoStandard, &fad)) {
  882. if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  883. return ERROR_ALREADY_EXISTS;
  884. } else {
  885. SetLastError(ERROR_ACCESS_DENIED);
  886. return 0;
  887. }
  888. }
  889. //
  890. // First, see if we can create the directory without having
  891. // to build parent directories.
  892. //
  893. if ( bInheritEncryption ) {
  894. if (CreateDirectory (lpDirectory, lpSecurityAttributes))
  895. return 1;
  896. }
  897. else {
  898. if (CreateSystemDirectory (lpDirectory, lpSecurityAttributes)) {
  899. SetFileAttributes(lpDirectory, FILE_ATTRIBUTE_NORMAL); // turn off the system attribute
  900. return 1;
  901. }
  902. }
  903. //
  904. // No luck, copy the string to a buffer we can munge
  905. //
  906. StringCchCopy(szDirectory, ARRAYSIZE(szDirectory), lpDirectory);
  907. //
  908. // Find the first subdirectory name
  909. //
  910. lpEnd = szDirectory;
  911. if (szDirectory[1] == TEXT(':')) {
  912. lpEnd += 3;
  913. } else if (szDirectory[1] == TEXT('\\')) {
  914. //
  915. // Skip the first two slashes
  916. //
  917. lpEnd += 2;
  918. //
  919. // Find the slash between the server name and
  920. // the share name.
  921. //
  922. while (*lpEnd && *lpEnd != TEXT('\\')) {
  923. lpEnd++;
  924. }
  925. if (!(*lpEnd)) {
  926. return 0;
  927. }
  928. //
  929. // Skip the slash, and find the slash between
  930. // the share name and the directory name.
  931. //
  932. lpEnd++;
  933. while (*lpEnd && *lpEnd != TEXT('\\')) {
  934. lpEnd++;
  935. }
  936. if (!(*lpEnd)) {
  937. return 0;
  938. }
  939. //
  940. // Leave pointer at the beginning of the directory.
  941. //
  942. lpEnd++;
  943. } else if (szDirectory[0] == TEXT('\\')) {
  944. lpEnd++;
  945. }
  946. while (*lpEnd) {
  947. while (*lpEnd && *lpEnd != TEXT('\\')) {
  948. lpEnd++;
  949. }
  950. if (*lpEnd == TEXT('\\')) {
  951. *lpEnd = TEXT('\0');
  952. if (!GetFileAttributesEx (szDirectory, GetFileExInfoStandard, &fad)) {
  953. if ( bInheritEncryption ) {
  954. if (!CreateDirectory (szDirectory, lpSecurityAttributes)) {
  955. DebugMsg((DM_WARNING, TEXT("CreateNestedDirectory: CreateDirectory failed with %d."), GetLastError()));
  956. return 0;
  957. }
  958. }
  959. else {
  960. if (!CreateSystemDirectory (szDirectory, lpSecurityAttributes)) {
  961. DebugMsg((DM_WARNING, TEXT("CreateNestedDirectory: CreateDirectory failed with %d."), GetLastError()));
  962. return 0;
  963. }
  964. else
  965. SetFileAttributes(szDirectory, FILE_ATTRIBUTE_NORMAL); // turn off the system attribute
  966. }
  967. }
  968. *lpEnd = TEXT('\\');
  969. lpEnd++;
  970. }
  971. }
  972. //
  973. // Create the final directory
  974. //
  975. if ( bInheritEncryption ) {
  976. if (CreateDirectory (lpDirectory, lpSecurityAttributes))
  977. return 1;
  978. }
  979. else {
  980. if (CreateSystemDirectory (lpDirectory, lpSecurityAttributes)) {
  981. SetFileAttributes(lpDirectory, FILE_ATTRIBUTE_NORMAL); // turn off the system attribute
  982. return 1;
  983. }
  984. }
  985. if (GetLastError() == ERROR_ALREADY_EXISTS) {
  986. return ERROR_ALREADY_EXISTS;
  987. }
  988. //
  989. // Failed
  990. //
  991. DebugMsg((DM_VERBOSE, TEXT("CreateNestedDirectory: Failed to create the directory with error %d."), GetLastError()));
  992. return 0;
  993. }
  994. //*************************************************************
  995. //
  996. // GetProfilesDirectory()
  997. //
  998. // Purpose: Returns the location of the "profiles" directory
  999. //
  1000. // Parameters: lpProfilesDir - Buffer to write result to
  1001. // lpcchSize - Size of the buffer in chars.
  1002. //
  1003. // Return: TRUE if successful
  1004. // FALSE if an error occurs
  1005. //
  1006. // Comments: If false is returned, lpcchSize holds the number of
  1007. // characters needed.
  1008. //
  1009. // History: Date Author Comment
  1010. // 9/18/95 ericflo Created
  1011. //
  1012. //*************************************************************
  1013. BOOL WINAPI GetProfilesDirectory(LPTSTR lpProfilesDir, LPDWORD lpcchSize)
  1014. {
  1015. return GetProfilesDirectoryEx (lpProfilesDir, lpcchSize, TRUE);
  1016. }
  1017. //*************************************************************
  1018. //
  1019. // GetProfilesDirectoryEx()
  1020. //
  1021. // Purpose: Returns the location of the "profiles" directory
  1022. //
  1023. // Parameters: lpProfilesDir - Buffer to write result to
  1024. // lpcchSize - Size of the buffer in chars.
  1025. // bExpand - Expand directory name
  1026. //
  1027. // Return: TRUE if successful
  1028. // FALSE if an error occurs
  1029. //
  1030. // Comments: If false is returned, lpcchSize holds the number of
  1031. // characters needed.
  1032. //
  1033. // History: Date Author Comment
  1034. // 12/15/97 ericflo Created
  1035. //
  1036. //*************************************************************
  1037. BOOL GetProfilesDirectoryEx(LPTSTR lpProfilesDir, LPDWORD lpcchSize, BOOL bExpand)
  1038. {
  1039. TCHAR szDirectory[MAX_PATH];
  1040. TCHAR szTemp[MAX_PATH];
  1041. DWORD dwLength;
  1042. HKEY hKey = INVALID_HANDLE_VALUE;
  1043. LONG lResult;
  1044. DWORD dwSize, dwType;
  1045. BOOL bRetVal = FALSE;
  1046. //
  1047. // Arg check
  1048. //
  1049. if (!lpcchSize) {
  1050. SetLastError (ERROR_INVALID_PARAMETER);
  1051. return FALSE;
  1052. }
  1053. szDirectory[0] = TEXT('\0');
  1054. szTemp[0] = TEXT('\0');
  1055. lResult = RegOpenKeyEx (HKEY_LOCAL_MACHINE, PROFILE_LIST_PATH, 0, KEY_READ,
  1056. &hKey);
  1057. if (lResult == ERROR_SUCCESS) {
  1058. dwSize = sizeof(szTemp);
  1059. lResult = RegQueryValueEx (hKey, PROFILES_DIRECTORY, NULL, &dwType,
  1060. (LPBYTE) szTemp, &dwSize);
  1061. if (lResult == ERROR_SUCCESS) {
  1062. if ((dwType == REG_EXPAND_SZ) || (dwType == REG_SZ)) {
  1063. if (bExpand && (dwType == REG_EXPAND_SZ)) {
  1064. if((dwLength = ExpandEnvironmentStrings(szTemp, szDirectory, MAX_PATH)) == 0) {
  1065. goto Exit;
  1066. }
  1067. else if(dwLength > MAX_PATH) {
  1068. SetLastError(ERROR_BAD_PATHNAME);
  1069. goto Exit;
  1070. }
  1071. } else {
  1072. StringCchCopy (szDirectory, ARRAYSIZE(szDirectory), szTemp);
  1073. }
  1074. }
  1075. }
  1076. RegCloseKey (hKey);
  1077. hKey = INVALID_HANDLE_VALUE;
  1078. }
  1079. if (szDirectory[0] == TEXT('\0')) {
  1080. LoadString (g_hDllInstance, IDS_PROFILES_ROOT, szTemp, ARRAYSIZE(szTemp));
  1081. if (bExpand) {
  1082. if((dwLength = ExpandEnvironmentStrings(szTemp, szDirectory, MAX_PATH)) == 0) {
  1083. goto Exit;
  1084. }
  1085. else if(dwLength > MAX_PATH) {
  1086. SetLastError(ERROR_BAD_PATHNAME);
  1087. goto Exit;
  1088. }
  1089. } else {
  1090. StringCchCopy (szDirectory, ARRAYSIZE(szDirectory), szTemp);
  1091. }
  1092. }
  1093. dwLength = lstrlen(szDirectory) + 1;
  1094. if (lpProfilesDir) {
  1095. if (*lpcchSize >= dwLength) {
  1096. StringCchCopy (lpProfilesDir, *lpcchSize, szDirectory);
  1097. bRetVal = TRUE;
  1098. } else {
  1099. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1100. }
  1101. } else {
  1102. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1103. }
  1104. *lpcchSize = dwLength;
  1105. Exit:
  1106. if(hKey != INVALID_HANDLE_VALUE) {
  1107. RegCloseKey(hKey);
  1108. }
  1109. return bRetVal;
  1110. }
  1111. //*************************************************************
  1112. //
  1113. // GetDefaultUserProfileDirectory()
  1114. //
  1115. // Purpose: Returns the location of the Default User's profile
  1116. //
  1117. // Parameters: lpProfileDir - Buffer to write result to
  1118. // lpcchSize - Size of the buffer in chars.
  1119. //
  1120. // Return: TRUE if successful
  1121. // FALSE if an error occurs
  1122. //
  1123. // Comments: If false is returned, lpcchSize holds the number of
  1124. // characters needed.
  1125. //
  1126. // History: Date Author Comment
  1127. // 12/8/97 ericflo Created
  1128. //
  1129. //*************************************************************
  1130. BOOL WINAPI GetDefaultUserProfileDirectory(LPTSTR lpProfileDir, LPDWORD lpcchSize)
  1131. {
  1132. return GetDefaultUserProfileDirectoryEx(lpProfileDir, lpcchSize, TRUE);
  1133. }
  1134. //*************************************************************
  1135. //
  1136. // GetDefaultUserProfileDirectoryEx()
  1137. //
  1138. // Purpose: Returns the location of the Default User's profile
  1139. //
  1140. // Parameters: lpProfileDir - Buffer to write result to
  1141. // lpcchSize - Size of the buffer in chars.
  1142. // bExpand - Expand the path or not
  1143. //
  1144. // Return: TRUE if successful
  1145. // FALSE if an error occurs
  1146. //
  1147. // Comments: If false is returned, lpcchSize holds the number of
  1148. // characters needed.
  1149. //
  1150. // History: Date Author Comment
  1151. // 12/8/97 ericflo Created
  1152. //
  1153. //*************************************************************
  1154. BOOL WINAPI GetDefaultUserProfileDirectoryEx(LPTSTR lpProfileDir,
  1155. LPDWORD lpcchSize, BOOL bExpand)
  1156. {
  1157. TCHAR szDirectory[MAX_PATH];
  1158. TCHAR szProfileName[MAX_PATH];
  1159. LPTSTR lpEnd;
  1160. int cchEnd;
  1161. DWORD dwSize, dwLength, dwType;
  1162. BOOL bRetVal = FALSE;
  1163. LONG lResult;
  1164. HKEY hKey;
  1165. //
  1166. // Arg check
  1167. //
  1168. if (!lpcchSize) {
  1169. SetLastError (ERROR_INVALID_PARAMETER);
  1170. return FALSE;
  1171. }
  1172. //
  1173. // Get the profiles root
  1174. //
  1175. szDirectory[0] = TEXT('\0');
  1176. dwSize = ARRAYSIZE(szDirectory);
  1177. if (!GetProfilesDirectoryEx(szDirectory, &dwSize, bExpand)) {
  1178. DebugMsg((DM_WARNING, TEXT("GetDefaultUserProfileDirectory: Failed to get profiles root.")));
  1179. *lpcchSize = 0;
  1180. return FALSE;
  1181. }
  1182. //
  1183. // Query for the Default User profile name
  1184. //
  1185. lResult = RegOpenKeyEx (HKEY_LOCAL_MACHINE, PROFILE_LIST_PATH,
  1186. 0, KEY_READ, &hKey);
  1187. if (lResult != ERROR_SUCCESS) {
  1188. DebugMsg((DM_WARNING, TEXT("GetDefaultUserProfileDirectoryEx: Failed to open profile list key with %d."),
  1189. lResult));
  1190. SetLastError(lResult);
  1191. return FALSE;
  1192. }
  1193. dwSize = sizeof(szProfileName);
  1194. lResult = RegQueryValueEx (hKey, DEFAULT_USER_PROFILE, NULL, &dwType,
  1195. (LPBYTE) szProfileName, &dwSize);
  1196. if (lResult != ERROR_SUCCESS) {
  1197. StringCchCopy (szProfileName, ARRAYSIZE(szProfileName), DEFAULT_USER);
  1198. }
  1199. RegCloseKey (hKey);
  1200. //
  1201. // Put them together
  1202. //
  1203. lpEnd = CheckSlashEx (szDirectory, ARRAYSIZE(szDirectory), &cchEnd);
  1204. if (cchEnd < lstrlen(szProfileName) + 1)
  1205. {
  1206. DebugMsg((DM_WARNING, TEXT("GetDefaultUserProfileDirectory: path > MAX_PATH.")));
  1207. SetLastError(ERROR_BAD_PATHNAME);
  1208. return FALSE;
  1209. }
  1210. StringCchCopy (lpEnd, cchEnd, szProfileName);
  1211. //
  1212. // Save the result if possible
  1213. dwLength = lstrlen(szDirectory) + 1;
  1214. if (lpProfileDir) {
  1215. if (*lpcchSize >= dwLength) {
  1216. StringCchCopy (lpProfileDir, *lpcchSize, szDirectory);
  1217. bRetVal = TRUE;
  1218. } else {
  1219. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1220. }
  1221. } else {
  1222. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1223. }
  1224. *lpcchSize = dwLength;
  1225. return bRetVal;
  1226. }
  1227. //*************************************************************
  1228. //
  1229. // GetAllUsersProfileDirectory()
  1230. //
  1231. // Purpose: Returns the location of the All Users profile
  1232. //
  1233. // Parameters: lpProfileDir - Buffer to write result to
  1234. // lpcchSize - Size of the buffer in chars.
  1235. //
  1236. // Return: TRUE if successful
  1237. // FALSE if an error occurs
  1238. //
  1239. // Comments: If false is returned, lpcchSize holds the number of
  1240. // characters needed.
  1241. //
  1242. // History: Date Author Comment
  1243. // 12/8/97 ericflo Created
  1244. //
  1245. //*************************************************************
  1246. BOOL WINAPI GetAllUsersProfileDirectory(LPTSTR lpProfileDir, LPDWORD lpcchSize)
  1247. {
  1248. return GetAllUsersProfileDirectoryEx(lpProfileDir, lpcchSize, TRUE);
  1249. }
  1250. //*************************************************************
  1251. //
  1252. // GetAllUsersProfileDirectoryEx()
  1253. //
  1254. // Purpose: Returns the location of the All Users profile
  1255. //
  1256. // Parameters: lpProfileDir - Buffer to write result to
  1257. // lpcchSize - Size of the buffer in chars.
  1258. // bExpand - Expand the path or not
  1259. //
  1260. // Return: TRUE if successful
  1261. // FALSE if an error occurs
  1262. //
  1263. // Comments: If false is returned, lpcchSize holds the number of
  1264. // characters needed.
  1265. //
  1266. // History: Date Author Comment
  1267. // 12/8/97 ericflo Created
  1268. //
  1269. //*************************************************************
  1270. BOOL GetAllUsersProfileDirectoryEx (LPTSTR lpProfileDir,
  1271. LPDWORD lpcchSize, BOOL bExpand)
  1272. {
  1273. TCHAR szDirectory[MAX_PATH];
  1274. TCHAR szProfileName[MAX_PATH];
  1275. LPTSTR lpEnd;
  1276. int cchEnd;
  1277. DWORD dwSize, dwLength, dwType;
  1278. BOOL bRetVal = FALSE;
  1279. LONG lResult;
  1280. HKEY hKey;
  1281. //
  1282. // Arg check
  1283. //
  1284. if (!lpcchSize) {
  1285. SetLastError (ERROR_INVALID_PARAMETER);
  1286. return FALSE;
  1287. }
  1288. //
  1289. // Get the profiles root
  1290. //
  1291. szDirectory[0] = TEXT('\0');
  1292. dwSize = ARRAYSIZE(szDirectory);
  1293. if (!GetProfilesDirectoryEx(szDirectory, &dwSize, bExpand)) {
  1294. DebugMsg((DM_WARNING, TEXT("GetAllUsersProfileDirectoryEx: Failed to get profiles root.")));
  1295. *lpcchSize = 0;
  1296. return FALSE;
  1297. }
  1298. //
  1299. // Query for the All Users profile name
  1300. //
  1301. lResult = RegOpenKeyEx (HKEY_LOCAL_MACHINE, PROFILE_LIST_PATH,
  1302. 0, KEY_READ, &hKey);
  1303. if (lResult != ERROR_SUCCESS) {
  1304. DebugMsg((DM_WARNING, TEXT("GetAllUsersProfileDirectoryEx: Failed to open profile list key with %d."),
  1305. lResult));
  1306. SetLastError(lResult);
  1307. return FALSE;
  1308. }
  1309. dwSize = sizeof(szProfileName);
  1310. lResult = RegQueryValueEx (hKey, ALL_USERS_PROFILE, NULL, &dwType,
  1311. (LPBYTE) szProfileName, &dwSize);
  1312. if (lResult != ERROR_SUCCESS) {
  1313. StringCchCopy(szProfileName, ARRAYSIZE(szProfileName), ALL_USERS);
  1314. }
  1315. RegCloseKey (hKey);
  1316. //
  1317. // Put them together
  1318. //
  1319. lpEnd = CheckSlashEx (szDirectory, ARRAYSIZE(szDirectory), &cchEnd);
  1320. if (cchEnd < lstrlen(szProfileName) + 1)
  1321. {
  1322. DebugMsg((DM_WARNING, TEXT("GetDefaultUserProfileDirectory: path > MAX_PATH.")));
  1323. SetLastError(ERROR_BAD_PATHNAME);
  1324. return FALSE;
  1325. }
  1326. StringCchCopy (lpEnd, cchEnd, szProfileName);
  1327. //
  1328. // Save the result if possible
  1329. dwLength = lstrlen(szDirectory) + 1;
  1330. if (lpProfileDir) {
  1331. if (*lpcchSize >= dwLength) {
  1332. StringCchCopy (lpProfileDir, *lpcchSize, szDirectory);
  1333. bRetVal = TRUE;
  1334. } else {
  1335. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1336. }
  1337. } else {
  1338. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1339. }
  1340. *lpcchSize = dwLength;
  1341. return bRetVal;
  1342. }
  1343. //*************************************************************
  1344. //
  1345. // GetProfileListKeyName()
  1346. //
  1347. // Purpose: Returns the key name for a specific user under ProfileList.
  1348. // Using safe string functions
  1349. //
  1350. // Parameters: szKeyName - Buffer of the returned name
  1351. // cchKeyName - size of the buffer
  1352. // szSidString - sid string for a specific user
  1353. //
  1354. // Return: S_OK if successful
  1355. // Error Code if an error occurs
  1356. //
  1357. // Comments: If error code is returned, content of szKeyName may
  1358. // change.
  1359. //
  1360. // History: Date Author Comment
  1361. // 02/21/2002 mingzhu Created
  1362. //
  1363. //*************************************************************
  1364. HRESULT GetProfileListKeyName(LPTSTR szKeyName, DWORD cchKeyName, LPTSTR szSidString)
  1365. {
  1366. HRESULT hr;
  1367. hr = StringCchCopy(szKeyName, cchKeyName, PROFILE_LIST_PATH);
  1368. if (SUCCEEDED(hr))
  1369. {
  1370. hr = StringCchCat(szKeyName, cchKeyName, TEXT("\\"));
  1371. if (SUCCEEDED(hr))
  1372. {
  1373. hr = StringCchCat(szKeyName, cchKeyName, szSidString);
  1374. }
  1375. }
  1376. return hr;
  1377. }
  1378. //*************************************************************
  1379. //
  1380. // GetKeyNameForUser()
  1381. //
  1382. // Purpose: Returns the user's key name in for specific user.
  1383. // Using safe string functions
  1384. //
  1385. // Parameters: szKeyName - Buffer of the returned name
  1386. // cchKeyName - size of the buffer
  1387. // szSidString - sid string for a specific user
  1388. // szSubKey - subkey name under the key's hive
  1389. //
  1390. // Return: S_OK if successful
  1391. // Error Code if an error occurs
  1392. //
  1393. // Comments: If error code is returned, content of szKeyName may
  1394. // change.
  1395. //
  1396. // History: Date Author Comment
  1397. // 02/21/2002 mingzhu Created
  1398. //
  1399. //*************************************************************
  1400. HRESULT GetKeyNameForUser(LPTSTR szKeyName, DWORD cchKeyName, LPTSTR szSidString, LPTSTR szSubKey)
  1401. {
  1402. HRESULT hr;
  1403. hr = StringCchCopy(szKeyName, cchKeyName, szSidString);
  1404. if (SUCCEEDED(hr))
  1405. {
  1406. hr = StringCchCat(szKeyName, cchKeyName, TEXT("\\"));
  1407. if (SUCCEEDED(hr))
  1408. {
  1409. hr = StringCchCat(szKeyName, cchKeyName, szSubKey);
  1410. }
  1411. }
  1412. return hr;
  1413. }
  1414. //*************************************************************
  1415. //
  1416. // SafeExpandEnvironmentStrings()
  1417. //
  1418. // Purpose: a wrapper of ExpandEnvironmentStrings() to
  1419. // handle small buffer errors more explictly.
  1420. //
  1421. // Parameters: lpSrc - Src string contains the env var
  1422. // lpDst - Output buffer
  1423. // nSize - Size of output buffer
  1424. //
  1425. // Return: S_OK if successful
  1426. // else if an error occurs
  1427. //
  1428. // History: Date Author Comment
  1429. // 02/21/2002 mingzhu Created
  1430. //
  1431. //*************************************************************
  1432. HRESULT SafeExpandEnvironmentStrings(LPCTSTR lpSrc, LPTSTR lpDst, DWORD nSize)
  1433. {
  1434. DWORD dwErr;
  1435. HRESULT hr;
  1436. dwErr = ExpandEnvironmentStrings(lpSrc, lpDst, nSize);
  1437. if (dwErr == 0)
  1438. hr = HRESULT_FROM_WIN32(GetLastError());
  1439. else if (dwErr > nSize)
  1440. hr = STRSAFE_E_INSUFFICIENT_BUFFER;
  1441. else
  1442. hr = S_OK;
  1443. return hr;
  1444. }
  1445. //*************************************************************
  1446. //
  1447. // AppendName()
  1448. //
  1449. // Purpose: append a file name to a folder name, or append a subkey name
  1450. // to a parent key name, add a slash if neccesory.
  1451. //
  1452. // Parameters: lpBuffer - output buffer to hold the appended path
  1453. // cchBuffer - size of the output buffer
  1454. // lpParent - path/parent key name to append to
  1455. // lpChild - file/subkey name to append
  1456. // lppEnd - optional returned pointer to the end of the slash of lpParent,
  1457. // can be used to further append other children to the same parent
  1458. // pcchEnd - optional returned pointer to the buffer size pointered by *lppEnd
  1459. //
  1460. // Return: S_OK if successful
  1461. // else if an error occurs
  1462. //
  1463. // History: Date Author Comment
  1464. // 03/05/2002 mingzhu Created
  1465. //
  1466. //*************************************************************
  1467. HRESULT AppendName(
  1468. LPTSTR lpBuffer,
  1469. UINT cchBuffer,
  1470. LPCTSTR lpParent,
  1471. LPCTSTR lpChild,
  1472. LPTSTR* lppEnd,
  1473. UINT* pcchEnd)
  1474. {
  1475. HRESULT hr;
  1476. LPTSTR lpEnd;
  1477. UINT cchEnd;
  1478. hr = StringCchCopy(lpBuffer, cchBuffer, lpParent);
  1479. if (SUCCEEDED(hr))
  1480. {
  1481. lpEnd = CheckSlashEx(lpBuffer, cchBuffer, &cchEnd);
  1482. if (!lpEnd)
  1483. {
  1484. hr = STRSAFE_E_INSUFFICIENT_BUFFER;
  1485. }
  1486. else
  1487. {
  1488. hr = StringCchCopy(lpEnd, cchEnd, lpChild);
  1489. }
  1490. }
  1491. if (SUCCEEDED(hr))
  1492. {
  1493. if (lppEnd)
  1494. *lppEnd = lpEnd;
  1495. if (pcchEnd)
  1496. *pcchEnd = cchEnd;
  1497. }
  1498. return hr;
  1499. }
  1500. //*************************************************************
  1501. //
  1502. // GetUserProfileDirectory()
  1503. //
  1504. // Purpose: Returns the root of the user's profile directory.
  1505. //
  1506. // Parameters: hToken - User's token
  1507. // lpProfileDir - Output buffer
  1508. // lpcchSize - Size of output buffer
  1509. //
  1510. // Return: TRUE if successful
  1511. // FALSE if an error occurs
  1512. //
  1513. // Comments: If false is returned, lpcchSize holds the number of
  1514. // characters needed.
  1515. //
  1516. // History: Date Author Comment
  1517. // 9/18/95 ericflo Created
  1518. //
  1519. //*************************************************************
  1520. BOOL WINAPI GetUserProfileDirectory(HANDLE hToken, LPTSTR lpProfileDir,
  1521. LPDWORD lpcchSize)
  1522. {
  1523. DWORD dwLength = MAX_PATH * sizeof(TCHAR);
  1524. DWORD dwType;
  1525. BOOL bRetVal = FALSE;
  1526. LPTSTR lpSidString;
  1527. TCHAR szBuffer[MAX_PATH];
  1528. TCHAR szDirectory[MAX_PATH];
  1529. HKEY hKey;
  1530. LONG lResult;
  1531. HRESULT hr;
  1532. //
  1533. // Parameter check
  1534. //
  1535. if (!hToken) {
  1536. SetLastError(ERROR_INVALID_HANDLE);
  1537. return FALSE;
  1538. }
  1539. if (!lpcchSize) {
  1540. SetLastError (ERROR_INVALID_PARAMETER);
  1541. return FALSE;
  1542. }
  1543. //
  1544. // Retrieve the user's sid string
  1545. //
  1546. lpSidString = GetSidString(hToken);
  1547. if (!lpSidString) {
  1548. SetLastError(ERROR_INVALID_HANDLE);
  1549. return FALSE;
  1550. }
  1551. //
  1552. // Check the registry
  1553. //
  1554. hr = GetProfileListKeyName(szBuffer, ARRAYSIZE(szBuffer), lpSidString);
  1555. if (FAILED(hr))
  1556. {
  1557. DeleteSidString(lpSidString);
  1558. SetLastError(HRESULT_CODE(hr));
  1559. return FALSE;
  1560. }
  1561. lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szBuffer, 0, KEY_READ, &hKey);
  1562. if (lResult != ERROR_SUCCESS) {
  1563. DeleteSidString(lpSidString);
  1564. SetLastError(lResult);
  1565. return FALSE;
  1566. }
  1567. lResult = RegQueryValueEx(hKey,
  1568. PROFILE_IMAGE_VALUE_NAME,
  1569. NULL,
  1570. &dwType,
  1571. (LPBYTE) szBuffer,
  1572. &dwLength);
  1573. if (lResult != ERROR_SUCCESS) {
  1574. RegCloseKey (hKey);
  1575. DeleteSidString(lpSidString);
  1576. SetLastError(lResult);
  1577. return FALSE;
  1578. }
  1579. //
  1580. // Clean up
  1581. //
  1582. RegCloseKey(hKey);
  1583. DeleteSidString(lpSidString);
  1584. //
  1585. // Expand and get the length of string
  1586. //
  1587. hr = SafeExpandEnvironmentStrings(szBuffer, szDirectory, ARRAYSIZE(szDirectory));
  1588. if (FAILED(hr))
  1589. {
  1590. SetLastError(HRESULT_CODE(hr));
  1591. return FALSE;
  1592. }
  1593. dwLength = lstrlen(szDirectory) + 1;
  1594. //
  1595. // Save the string if appropriate
  1596. //
  1597. if (lpProfileDir) {
  1598. if (*lpcchSize >= dwLength) {
  1599. StringCchCopy (lpProfileDir, *lpcchSize, szDirectory);
  1600. bRetVal = TRUE;
  1601. } else {
  1602. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1603. }
  1604. }
  1605. else {
  1606. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1607. }
  1608. *lpcchSize = dwLength;
  1609. return bRetVal;
  1610. }
  1611. //*************************************************************
  1612. //
  1613. // GetUserProfileDirFromSid()
  1614. //
  1615. // Purpose: Returns the root of the user's profile directory.
  1616. //
  1617. // Parameters: pSid - User's SID
  1618. // lpProfileDir - Output buffer
  1619. // lpcchSize - Size of output buffer
  1620. //
  1621. // Return: TRUE if successful
  1622. // FALSE if an error occurs
  1623. //
  1624. // Comments: If false is returned, lpcchSize holds the number of
  1625. // characters needed.
  1626. //
  1627. // History: Date Author Comment
  1628. // 03/08/01 santanuc Created
  1629. //
  1630. //*************************************************************
  1631. BOOL WINAPI GetUserProfileDirFromSid(PSID pSid, LPTSTR lpProfileDir,
  1632. LPDWORD lpcchSize)
  1633. {
  1634. DWORD dwLength = MAX_PATH * sizeof(TCHAR);
  1635. DWORD dwType;
  1636. BOOL bRetVal = FALSE;
  1637. UNICODE_STRING UnicodeString;
  1638. TCHAR szBuffer[MAX_PATH];
  1639. TCHAR szDirectory[MAX_PATH];
  1640. HKEY hKey;
  1641. LONG lResult;
  1642. NTSTATUS NtStatus;
  1643. HRESULT hr;
  1644. //
  1645. // Parameter check
  1646. //
  1647. if (!pSid) {
  1648. SetLastError(ERROR_INVALID_HANDLE);
  1649. return FALSE;
  1650. }
  1651. if (!lpcchSize) {
  1652. SetLastError (ERROR_INVALID_PARAMETER);
  1653. return FALSE;
  1654. }
  1655. //
  1656. // Retrieve the user's sid string
  1657. //
  1658. NtStatus = RtlConvertSidToUnicodeString(
  1659. &UnicodeString,
  1660. pSid,
  1661. (BOOLEAN)TRUE // Allocate memory
  1662. );
  1663. //
  1664. // See if the conversion to a string worked
  1665. //
  1666. if (!NT_SUCCESS(NtStatus)) {
  1667. SetLastError(RtlNtStatusToDosError(NtStatus));
  1668. DebugMsg((DM_WARNING, TEXT("GetUserProfileDirFromSid: RtlConvertSidToUnicodeString failed, status = 0x%x"),
  1669. NtStatus));
  1670. return FALSE;
  1671. }
  1672. //
  1673. // Check the registry
  1674. //
  1675. hr = GetProfileListKeyName(szBuffer, ARRAYSIZE(szBuffer), UnicodeString.Buffer);
  1676. if (FAILED(hr))
  1677. {
  1678. RtlFreeUnicodeString(&UnicodeString);
  1679. SetLastError(HRESULT_CODE(hr));
  1680. return FALSE;
  1681. }
  1682. lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szBuffer, 0, KEY_READ,
  1683. &hKey);
  1684. if (lResult != ERROR_SUCCESS) {
  1685. RtlFreeUnicodeString(&UnicodeString);
  1686. SetLastError(lResult);
  1687. return FALSE;
  1688. }
  1689. lResult = RegQueryValueEx(hKey,
  1690. PROFILE_IMAGE_VALUE_NAME,
  1691. NULL,
  1692. &dwType,
  1693. (LPBYTE) szBuffer,
  1694. &dwLength);
  1695. if (lResult != ERROR_SUCCESS) {
  1696. RegCloseKey (hKey);
  1697. RtlFreeUnicodeString(&UnicodeString);
  1698. SetLastError(lResult);
  1699. return FALSE;
  1700. }
  1701. //
  1702. // Clean up
  1703. //
  1704. RegCloseKey(hKey);
  1705. RtlFreeUnicodeString(&UnicodeString);
  1706. //
  1707. // Expand and get the length of string
  1708. //
  1709. hr = SafeExpandEnvironmentStrings(szBuffer, szDirectory, ARRAYSIZE(szDirectory));
  1710. if (FAILED(hr))
  1711. {
  1712. SetLastError(HRESULT_CODE(hr));
  1713. return FALSE;
  1714. }
  1715. dwLength = lstrlen(szDirectory) + 1;
  1716. //
  1717. // Save the string if appropriate
  1718. //
  1719. if (lpProfileDir) {
  1720. if (*lpcchSize >= dwLength) {
  1721. StringCchCopy (lpProfileDir, *lpcchSize, szDirectory);
  1722. bRetVal = TRUE;
  1723. } else {
  1724. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1725. }
  1726. }
  1727. else {
  1728. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1729. }
  1730. *lpcchSize = dwLength;
  1731. return bRetVal;
  1732. }
  1733. //*************************************************************
  1734. //
  1735. // GetUserAppDataPath()
  1736. //
  1737. // Purpose: Returns the path for user's Appdata.
  1738. //
  1739. // Parameters: hToken - User's token
  1740. // lpFolderPath - Output buffer
  1741. //
  1742. // Return: ERROR_SUCCESS if successful
  1743. // otherwise the error code
  1744. //
  1745. // Comments: If error occurs then lpFolderPath set to empty.
  1746. // Used by Crypto guys to avoid calling SHGetFolderPath.
  1747. //
  1748. // History: Date Author Comment
  1749. //
  1750. //*************************************************************
  1751. DWORD WINAPI
  1752. GetUserAppDataPath(
  1753. HANDLE hToken,
  1754. BOOL fLocalAppData,
  1755. LPTSTR lpFolderPath
  1756. )
  1757. {
  1758. DWORD dwSize, dwType;
  1759. LPTSTR lpSidString = NULL;
  1760. DWORD dwError = ERROR_SUCCESS;
  1761. HKEY hKey = NULL;
  1762. TCHAR szBuffer[MAX_PATH];
  1763. HRESULT hr;
  1764. //
  1765. // Parameter check
  1766. //
  1767. if (!hToken) {
  1768. dwError = ERROR_INVALID_HANDLE;
  1769. goto Exit;
  1770. }
  1771. if (!lpFolderPath) {
  1772. dwError = ERROR_INVALID_PARAMETER;
  1773. goto Exit;
  1774. }
  1775. else {
  1776. *lpFolderPath = TEXT('\0');
  1777. }
  1778. //
  1779. // Retrieve the user's sid string
  1780. //
  1781. lpSidString = GetSidString(hToken);
  1782. if (!lpSidString) {
  1783. dwError = ERROR_INVALID_HANDLE;
  1784. goto Exit;
  1785. }
  1786. //
  1787. // Check the registry
  1788. //
  1789. hr = GetKeyNameForUser(szBuffer, ARRAYSIZE(szBuffer), lpSidString, USER_SHELL_FOLDERS);
  1790. if (FAILED(hr))
  1791. {
  1792. dwError = HRESULT_CODE(hr);
  1793. goto Exit;
  1794. }
  1795. dwError = RegOpenKeyEx(HKEY_USERS, szBuffer, 0, KEY_READ, &hKey);
  1796. if (dwError != ERROR_SUCCESS) {
  1797. goto Exit;
  1798. }
  1799. dwSize = MAX_PATH * sizeof(TCHAR);
  1800. dwError = RegQueryValueEx(hKey,
  1801. fLocalAppData ? TEXT("Local AppData") : TEXT("AppData"),
  1802. NULL,
  1803. &dwType,
  1804. (LPBYTE) szBuffer,
  1805. &dwSize);
  1806. if (ERROR_SUCCESS == dwError) {
  1807. dwSize = MAX_PATH;
  1808. if (!ExpandEnvironmentStringsForUser(hToken, szBuffer, lpFolderPath, dwSize)) {
  1809. dwError = GetLastError();
  1810. }
  1811. }
  1812. Exit:
  1813. //
  1814. // Clean up
  1815. //
  1816. if (lpSidString) {
  1817. DeleteSidString(lpSidString);
  1818. }
  1819. if (hKey) {
  1820. RegCloseKey(hKey);
  1821. }
  1822. SetLastError(dwError);
  1823. return dwError;
  1824. }
  1825. //*************************************************************
  1826. //
  1827. // StringToInt()
  1828. //
  1829. // Purpose: Converts a string to an integer
  1830. //
  1831. // Parameters: lpNum - Number to convert
  1832. //
  1833. // Return: The number
  1834. //
  1835. // Comments:
  1836. //
  1837. // History: Date Author Comment
  1838. // 10/3/95 ericflo Created
  1839. //
  1840. //*************************************************************
  1841. int StringToInt(LPTSTR lpNum)
  1842. {
  1843. int i = 0;
  1844. BOOL bNeg = FALSE;
  1845. if (*lpNum == TEXT('-')) {
  1846. bNeg = TRUE;
  1847. lpNum++;
  1848. }
  1849. while (*lpNum >= TEXT('0') && *lpNum <= TEXT('9')) {
  1850. i *= 10;
  1851. i += (int)(*lpNum-TEXT('0'));
  1852. lpNum++;
  1853. }
  1854. if (bNeg) {
  1855. i *= -1;
  1856. }
  1857. return(i);
  1858. }
  1859. //*************************************************************
  1860. //
  1861. // HexStringToInt()
  1862. //
  1863. // Purpose: Converts a hex string to an integer, stops
  1864. // on first invalid character
  1865. //
  1866. // Parameters: lpNum - Number to convert
  1867. //
  1868. // Return: The number
  1869. //
  1870. // Comments: Originally for use in "ExtractCSIDL" tested
  1871. // exclusively with 0x0000 numbers format
  1872. //
  1873. // History: Date Author Comment
  1874. // 6/9/98 stephstm Created
  1875. //
  1876. //*************************************************************
  1877. unsigned int HexStringToUInt(LPCTSTR lpcNum)
  1878. {
  1879. unsigned int i = 0;
  1880. while (1)
  1881. {
  1882. if(*lpcNum != TEXT('x') && *lpcNum != TEXT('X') )
  1883. {
  1884. if(*lpcNum >= TEXT('0') && *lpcNum <= TEXT('9'))
  1885. {
  1886. i *= 16;
  1887. i += (unsigned int)(*lpcNum-TEXT('0'));
  1888. }
  1889. else
  1890. {
  1891. if(*lpcNum >= TEXT('a') && *lpcNum <= TEXT('f'))
  1892. {
  1893. i *= 16;
  1894. i += (unsigned int)(*lpcNum-TEXT('a')) + 10;
  1895. }
  1896. else
  1897. {
  1898. if(*lpcNum >= TEXT('A') && *lpcNum <= TEXT('F'))
  1899. {
  1900. i *= 16;
  1901. i += (unsigned int)(*lpcNum-TEXT('A')) + 10;
  1902. }
  1903. else
  1904. break;
  1905. }
  1906. }
  1907. }
  1908. lpcNum++;
  1909. }
  1910. return(i);
  1911. }
  1912. //*************************************************************
  1913. //
  1914. // RegRenameKey()
  1915. //
  1916. // Purpose: Renames a registry key
  1917. //
  1918. // Parameters: hKeyRoot - Root key
  1919. // lpSubKey1 - SubKey to rename from
  1920. // lpSubKey2 - SubKey to rename to
  1921. //
  1922. // Return: TRUE if successful
  1923. // FALSE if an error occurs
  1924. //
  1925. // Comments:
  1926. //
  1927. // History: Date Author Comment
  1928. // 20/9/99 ushaji created
  1929. // 05/02/2002 mingzhu Make this function support subkeys (recursive)
  1930. //
  1931. //*************************************************************
  1932. LONG RegRenameKey(HKEY hKeyRoot, LPTSTR lpSrcKey, LPTSTR lpDestKey)
  1933. {
  1934. HKEY hSrcKey=NULL, hDestKey=NULL;
  1935. LONG lResult;
  1936. DWORD dwDisposition;
  1937. DWORD dwValues, dwMaxValueNameLen, dwMaxValueLen, dwType;
  1938. DWORD dwMaxValueNameLenLocal, dwMaxValueLenLocal, i, dwSDSize;
  1939. DWORD dwSrcSubkeyLen, dwDestSubkeyLen, dwSubkeyLen;
  1940. DWORD dwSubkeys, dwMaxSubkeyNameLen, dwMaxSubkeyNameLenLocal;
  1941. LPTSTR lpSrcSubkey = NULL;
  1942. LPTSTR lpDestSubkey = NULL;
  1943. LPTSTR lpSubkey = NULL;
  1944. LPTSTR lpValueName=NULL;
  1945. LPBYTE lpData=NULL;
  1946. PSECURITY_DESCRIPTOR pSD = NULL;
  1947. HRESULT hr;
  1948. //
  1949. // Verbose Debug Message
  1950. //
  1951. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: renaming %s to %s"), lpSrcKey, lpDestKey));
  1952. if (!lpSrcKey || !lpDestKey)
  1953. return ERROR_INVALID_PARAMETER;
  1954. lResult = RegOpenKeyEx(hKeyRoot, lpSrcKey, 0, KEY_ALL_ACCESS, &hSrcKey);
  1955. if (lResult != ERROR_SUCCESS) {
  1956. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot open src key %s with error %d"), lpSrcKey, lResult));
  1957. goto Exit;
  1958. }
  1959. if (RegDelnode(hKeyRoot, lpDestKey) != ERROR_SUCCESS) {
  1960. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot delete dest key %s."), lpDestKey));
  1961. goto Exit;
  1962. }
  1963. lResult = RegQueryInfoKey(hSrcKey, NULL, NULL, NULL, &dwSubkeys, &dwMaxSubkeyNameLen, NULL,
  1964. &dwValues, &dwMaxValueNameLen, &dwMaxValueLen,
  1965. &dwSDSize, NULL);
  1966. if (lResult != ERROR_SUCCESS) {
  1967. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot query src key %s with error %d"), lpSrcKey, lResult));
  1968. goto Exit;
  1969. }
  1970. pSD = LocalAlloc(LPTR, sizeof(BYTE)*dwSDSize);
  1971. if (!pSD) {
  1972. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot allocate memory error")));
  1973. lResult = GetLastError();
  1974. goto Exit;
  1975. }
  1976. lResult = RegGetKeySecurity(hSrcKey, DACL_SECURITY_INFORMATION, pSD, &dwSDSize);
  1977. if (lResult != ERROR_SUCCESS) {
  1978. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot get sd with error %d"), lResult));
  1979. goto Exit;
  1980. }
  1981. lResult = RegCreateKeyEx(hKeyRoot, lpDestKey, 0, L"", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hDestKey,
  1982. &dwDisposition);
  1983. if (lResult != ERROR_SUCCESS) {
  1984. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot open dest key %s with error %d"), lpDestKey, lResult));
  1985. goto Exit;
  1986. }
  1987. lResult = RegSetKeySecurity(hDestKey, DACL_SECURITY_INFORMATION, pSD);
  1988. if (lResult != ERROR_SUCCESS) {
  1989. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot get sd with error %d"), lResult));
  1990. goto Exit;
  1991. }
  1992. lpValueName = (LPTSTR) LocalAlloc(LPTR, sizeof(TCHAR)*(dwMaxValueNameLen+1));
  1993. if (!lpValueName) {
  1994. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot allocate memory for valuename")));
  1995. lResult = GetLastError();
  1996. goto Exit;
  1997. }
  1998. lpData = (LPBYTE) LocalAlloc(LPTR, sizeof(BYTE)*dwMaxValueLen);
  1999. if (!lpData) {
  2000. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot allocate memory for lpData")));
  2001. lResult = GetLastError();
  2002. goto Exit;
  2003. }
  2004. for (i = 0; i < dwValues; i++) {
  2005. dwMaxValueNameLenLocal = dwMaxValueNameLen+1;
  2006. dwMaxValueLenLocal = dwMaxValueLen;
  2007. lResult = RegEnumValue(hSrcKey, i, lpValueName, &dwMaxValueNameLenLocal, NULL, &dwType, lpData, &dwMaxValueLenLocal);
  2008. if (lResult != ERROR_SUCCESS) {
  2009. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot enum src key value with error %d"), lResult));
  2010. goto Exit;
  2011. }
  2012. lResult = RegSetValueEx(hDestKey, lpValueName, 0, dwType, lpData, dwMaxValueLenLocal);
  2013. if (lResult != ERROR_SUCCESS) {
  2014. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot set dest value %s with error %d"), lpValueName, lResult));
  2015. goto Exit;
  2016. }
  2017. }
  2018. //
  2019. // Allocate buffer for local, src and dest subkeys
  2020. //
  2021. lpSubkey = (LPTSTR) LocalAlloc(LPTR, sizeof(TCHAR)*(dwMaxSubkeyNameLen + 1));
  2022. if (!lpSubkey) {
  2023. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot allocate memory for subkey")));
  2024. lResult = GetLastError();
  2025. goto Exit;
  2026. }
  2027. dwSrcSubkeyLen = lstrlen(lpSrcKey) + dwMaxSubkeyNameLen + 2;
  2028. lpSrcSubkey = (LPTSTR) LocalAlloc(LPTR, sizeof(TCHAR)*(dwSrcSubkeyLen));
  2029. if (!lpSrcSubkey) {
  2030. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot allocate memory for src subkey")));
  2031. lResult = GetLastError();
  2032. goto Exit;
  2033. }
  2034. dwDestSubkeyLen = lstrlen(lpDestKey) + dwMaxSubkeyNameLen + 2;
  2035. lpDestSubkey = (LPTSTR) LocalAlloc(LPTR, sizeof(TCHAR)*(dwDestSubkeyLen));
  2036. if (!lpDestSubkey) {
  2037. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot allocate memory for dest subkey")));
  2038. lResult = GetLastError();
  2039. goto Exit;
  2040. }
  2041. //
  2042. // Enumerate subkeys and call this function recursively
  2043. //
  2044. for (i = 0; i < dwSubkeys; i++) {
  2045. // Enumerate local subkey
  2046. dwMaxSubkeyNameLenLocal = dwMaxSubkeyNameLen + 1;
  2047. lResult = RegEnumKeyEx(hSrcKey, i, lpSubkey, &dwMaxSubkeyNameLenLocal, NULL, NULL, NULL, NULL);
  2048. if (lResult != ERROR_SUCCESS) {
  2049. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: Couldnot enum sub key value with error %d"), lResult));
  2050. goto Exit;
  2051. }
  2052. // Construct the src and dest subkey
  2053. hr = StringCchPrintf(lpSrcSubkey, dwSrcSubkeyLen, TEXT("%s\\%s"), lpSrcKey, lpSubkey);
  2054. if (FAILED(hr)) {
  2055. lResult = HRESULT_CODE(hr);
  2056. goto Exit;
  2057. }
  2058. hr = StringCchPrintf(lpDestSubkey, dwDestSubkeyLen, TEXT("%s\\%s"), lpDestKey, lpSubkey);
  2059. if (FAILED(hr)) {
  2060. lResult = HRESULT_CODE(hr);
  2061. goto Exit;
  2062. }
  2063. // Call this function recursively
  2064. lResult = RegRenameKey(hKeyRoot, lpSrcSubkey, lpDestSubkey);
  2065. if (lResult != ERROR_SUCCESS) {
  2066. DebugMsg((DM_VERBOSE, TEXT("RegRenameKey: failed to rename %s to %s, error = %d"), lpSrcSubkey, lpDestSubkey, lResult));
  2067. goto Exit;
  2068. }
  2069. }
  2070. Exit:
  2071. if (lpSubkey)
  2072. LocalFree(lpSubkey);
  2073. if (lpSrcSubkey)
  2074. LocalFree(lpSrcSubkey);
  2075. if (lpDestSubkey)
  2076. LocalFree(lpDestSubkey);
  2077. if (hSrcKey)
  2078. RegCloseKey(hSrcKey);
  2079. if (hDestKey)
  2080. RegCloseKey(hDestKey);
  2081. if (lpData)
  2082. LocalFree(lpData);
  2083. if (lpValueName)
  2084. LocalFree(lpValueName);
  2085. if (pSD)
  2086. LocalFree(pSD);
  2087. if (lResult == ERROR_SUCCESS)
  2088. lResult = RegDelnode(hKeyRoot, lpSrcKey);
  2089. else
  2090. RegDelnode(hKeyRoot, lpDestKey);
  2091. return lResult;
  2092. }
  2093. //*************************************************************
  2094. //
  2095. // CreateSecureAdminDirectory()
  2096. //
  2097. // Purpose: Creates a secure directory that only the Administrator
  2098. // and system have access to.
  2099. //
  2100. // Parameters: lpDirectory - Directory Name
  2101. //
  2102. // Return: TRUE if successful
  2103. // FALSE if an error occurs
  2104. //
  2105. // Comments:
  2106. //
  2107. // History: Date Author Comment
  2108. // 7/20/95 ericflo Created
  2109. //
  2110. //*************************************************************
  2111. BOOL CreateSecureAdminDirectory (LPTSTR lpDirectory, DWORD dwOtherSids)
  2112. {
  2113. //
  2114. // Attempt to create the directory
  2115. //
  2116. if (!CreateNestedDirectory(lpDirectory, NULL)) {
  2117. return FALSE;
  2118. }
  2119. //
  2120. // Set the security
  2121. //
  2122. if (!MakeFileSecure (lpDirectory, dwOtherSids)) {
  2123. RemoveDirectory(lpDirectory);
  2124. return FALSE;
  2125. }
  2126. return TRUE;
  2127. }
  2128. //*************************************************************
  2129. //
  2130. // DeleteAllValues ()
  2131. //
  2132. // Purpose: Deletes all values under specified key
  2133. //
  2134. // Parameters: hKey - Key to delete values from
  2135. //
  2136. // Return:
  2137. //
  2138. // Comments:
  2139. //
  2140. // History: Date Author Comment
  2141. // 9/14/95 ericflo Ported
  2142. //
  2143. //*************************************************************
  2144. BOOL DeleteAllValues(HKEY hKey)
  2145. {
  2146. TCHAR ValueName[MAX_PATH+1];
  2147. DWORD dwSize = MAX_PATH+1;
  2148. LONG lResult;
  2149. while (RegEnumValue(hKey, 0, ValueName, &dwSize,
  2150. NULL, NULL, NULL, NULL) == ERROR_SUCCESS) {
  2151. lResult = RegDeleteValue(hKey, ValueName);
  2152. if (lResult != ERROR_SUCCESS) {
  2153. DebugMsg((DM_WARNING, TEXT("DeleteAllValues: Failed to delete value <%s> with %d."), ValueName, lResult));
  2154. return FALSE;
  2155. } else {
  2156. DebugMsg((DM_VERBOSE, TEXT("DeleteAllValues: Deleted <%s>"), ValueName));
  2157. }
  2158. dwSize = MAX_PATH+1;
  2159. }
  2160. return TRUE;
  2161. }
  2162. //*************************************************************
  2163. //
  2164. // MakeFileSecure()
  2165. //
  2166. // Purpose: Sets the attributes on the file so only Administrators
  2167. // and the OS can delete it. Authenticated Users have read
  2168. // permission only.
  2169. //
  2170. // Parameters: lpFile - File to set security on
  2171. //
  2172. // Return: (BOOL) TRUE if successful
  2173. // FALSE if an error occurs
  2174. //
  2175. // Comments:
  2176. //
  2177. // History: Date Author Comment
  2178. // 11/6/95 ericflo Created
  2179. // 2/16/99 ushaji Added everyone, pweruser
  2180. //
  2181. //*************************************************************
  2182. BOOL MakeFileSecure (LPTSTR lpFile, DWORD dwOtherSids)
  2183. {
  2184. SECURITY_DESCRIPTOR sd;
  2185. SECURITY_ATTRIBUTES sa;
  2186. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  2187. SID_IDENTIFIER_AUTHORITY authWORLD = SECURITY_WORLD_SID_AUTHORITY;
  2188. PACL pAcl = NULL;
  2189. PSID psidSystem = NULL, psidAdmin = NULL, psidUsers = NULL, psidPowerUsers = NULL;
  2190. PSID psidEveryOne = NULL;
  2191. DWORD cbAcl, aceIndex;
  2192. ACE_HEADER * lpAceHeader;
  2193. BOOL bRetVal = FALSE;
  2194. BOOL bAddPowerUsersAce=TRUE;
  2195. BOOL bAddEveryOneAce=FALSE;
  2196. DWORD dwAccMask;
  2197. //
  2198. // Get the system sid
  2199. //
  2200. if (!AllocateAndInitializeSid(&authNT, 1, SECURITY_LOCAL_SYSTEM_RID,
  2201. 0, 0, 0, 0, 0, 0, 0, &psidSystem)) {
  2202. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to initialize system sid. Error = %d"), GetLastError()));
  2203. goto Exit;
  2204. }
  2205. //
  2206. // Get the Admin sid
  2207. //
  2208. if (!AllocateAndInitializeSid(&authNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
  2209. DOMAIN_ALIAS_RID_ADMINS, 0, 0,
  2210. 0, 0, 0, 0, &psidAdmin)) {
  2211. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to initialize admin sid. Error = %d"), GetLastError()));
  2212. goto Exit;
  2213. }
  2214. //
  2215. // Get the users sid
  2216. //
  2217. if (!AllocateAndInitializeSid(&authNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
  2218. DOMAIN_ALIAS_RID_USERS,
  2219. 0, 0, 0, 0, 0, 0, &psidUsers)) {
  2220. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to initialize authenticated users sid. Error = %d"), GetLastError()));
  2221. goto Exit;
  2222. }
  2223. //
  2224. // Allocate space for the ACL
  2225. //
  2226. cbAcl = (2 * GetLengthSid (psidSystem)) +
  2227. (2 * GetLengthSid (psidAdmin)) +
  2228. (2 * GetLengthSid (psidUsers)) +
  2229. sizeof(ACL) +
  2230. (6 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)));
  2231. //
  2232. // Get the power users sid, if required.
  2233. // Don't fail if you don't get because it might not be available on DCs??
  2234. //
  2235. bAddPowerUsersAce = TRUE;
  2236. if (!AllocateAndInitializeSid(&authNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
  2237. DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, 0, &psidPowerUsers)) {
  2238. DebugMsg((DM_WARNING, TEXT("AddPowerUserAce: Failed to initialize power users sid. Error = %d"), GetLastError()));
  2239. bAddPowerUsersAce = FALSE;
  2240. }
  2241. if (bAddPowerUsersAce)
  2242. cbAcl += (2 * GetLengthSid (psidPowerUsers)) + (2 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)));
  2243. //
  2244. // Get the EveryOne sid, if required.
  2245. //
  2246. if (dwOtherSids & OTHERSIDS_EVERYONE) {
  2247. bAddEveryOneAce = TRUE;
  2248. if (!AllocateAndInitializeSid(&authWORLD, 1, SECURITY_WORLD_RID,
  2249. 0, 0, 0, 0, 0, 0, 0, &psidEveryOne)) {
  2250. DebugMsg((DM_WARNING, TEXT("AddPowerUserAce: Failed to initialize everyone sid. Error = %d"), GetLastError()));
  2251. goto Exit;
  2252. }
  2253. }
  2254. if (bAddEveryOneAce)
  2255. cbAcl += (2 * GetLengthSid (psidEveryOne)) + (2 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)));
  2256. pAcl = (PACL) GlobalAlloc(GMEM_FIXED, cbAcl);
  2257. if (!pAcl) {
  2258. goto Exit;
  2259. }
  2260. if (!InitializeAcl(pAcl, cbAcl, ACL_REVISION)) {
  2261. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to initialize acl. Error = %d"), GetLastError()));
  2262. goto Exit;
  2263. }
  2264. //
  2265. // Add Aces. Non-inheritable ACEs first
  2266. //
  2267. aceIndex = 0;
  2268. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, FILE_ALL_ACCESS, psidSystem)) {
  2269. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2270. goto Exit;
  2271. }
  2272. aceIndex++;
  2273. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, FILE_ALL_ACCESS, psidAdmin)) {
  2274. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2275. goto Exit;
  2276. }
  2277. aceIndex++;
  2278. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_READ | GENERIC_EXECUTE, psidUsers)) {
  2279. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2280. goto Exit;
  2281. }
  2282. if (bAddPowerUsersAce) {
  2283. //
  2284. // By default give read permissions, otherwise give modify permissions
  2285. //
  2286. dwAccMask = (dwOtherSids & OTHERSIDS_POWERUSERS) ? (FILE_ALL_ACCESS ^ (WRITE_DAC | WRITE_OWNER)):
  2287. (GENERIC_READ | GENERIC_EXECUTE);
  2288. aceIndex++;
  2289. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, dwAccMask, psidPowerUsers)) {
  2290. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2291. goto Exit;
  2292. }
  2293. }
  2294. if (bAddEveryOneAce) {
  2295. aceIndex++;
  2296. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_READ | GENERIC_EXECUTE, psidEveryOne)) {
  2297. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2298. goto Exit;
  2299. }
  2300. }
  2301. //
  2302. // Now the inheritable ACEs
  2303. //
  2304. aceIndex++;
  2305. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, psidSystem)) {
  2306. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2307. goto Exit;
  2308. }
  2309. if (!GetAce(pAcl, aceIndex, &lpAceHeader)) {
  2310. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to get ace (%d). Error = %d"), aceIndex, GetLastError()));
  2311. goto Exit;
  2312. }
  2313. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  2314. aceIndex++;
  2315. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, psidAdmin)) {
  2316. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2317. goto Exit;
  2318. }
  2319. if (!GetAce(pAcl, aceIndex, &lpAceHeader)) {
  2320. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to get ace (%d). Error = %d"), aceIndex, GetLastError()));
  2321. goto Exit;
  2322. }
  2323. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  2324. aceIndex++;
  2325. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_READ | GENERIC_EXECUTE, psidUsers)) {
  2326. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2327. goto Exit;
  2328. }
  2329. if (!GetAce(pAcl, aceIndex, &lpAceHeader)) {
  2330. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to get ace (%d). Error = %d"), aceIndex, GetLastError()));
  2331. goto Exit;
  2332. }
  2333. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  2334. if (bAddPowerUsersAce) {
  2335. aceIndex++;
  2336. dwAccMask = (dwOtherSids & OTHERSIDS_POWERUSERS) ? (FILE_ALL_ACCESS ^ (WRITE_DAC | WRITE_OWNER)):
  2337. (GENERIC_READ | GENERIC_EXECUTE);
  2338. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, dwAccMask, psidPowerUsers)) {
  2339. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2340. goto Exit;
  2341. }
  2342. if (!GetAce(pAcl, aceIndex, &lpAceHeader)) {
  2343. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to get ace (%d). Error = %d"), aceIndex, GetLastError()));
  2344. goto Exit;
  2345. }
  2346. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  2347. }
  2348. if (bAddEveryOneAce) {
  2349. aceIndex++;
  2350. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_READ | GENERIC_EXECUTE, psidEveryOne)) {
  2351. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to add ace (%d). Error = %d"), aceIndex, GetLastError()));
  2352. goto Exit;
  2353. }
  2354. if (!GetAce(pAcl, aceIndex, &lpAceHeader)) {
  2355. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to get ace (%d). Error = %d"), aceIndex, GetLastError()));
  2356. goto Exit;
  2357. }
  2358. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  2359. }
  2360. //
  2361. // Put together the security descriptor
  2362. //
  2363. if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
  2364. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to initialize security descriptor. Error = %d"), GetLastError()));
  2365. goto Exit;
  2366. }
  2367. if (!SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE)) {
  2368. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: Failed to set security descriptor dacl. Error = %d"), GetLastError()));
  2369. goto Exit;
  2370. }
  2371. //
  2372. // Set the security
  2373. //
  2374. if (SetFileSecurity (lpFile, DACL_SECURITY_INFORMATION, &sd)) {
  2375. bRetVal = TRUE;
  2376. } else {
  2377. DebugMsg((DM_WARNING, TEXT("MakeFileSecure: SetFileSecurity failed. Error = %d"), GetLastError()));
  2378. }
  2379. Exit:
  2380. if (psidSystem) {
  2381. FreeSid(psidSystem);
  2382. }
  2383. if (psidAdmin) {
  2384. FreeSid(psidAdmin);
  2385. }
  2386. if (psidUsers) {
  2387. FreeSid(psidUsers);
  2388. }
  2389. if ((bAddPowerUsersAce) && (psidPowerUsers)) {
  2390. FreeSid(psidPowerUsers);
  2391. }
  2392. if ((bAddEveryOneAce) && (psidEveryOne)) {
  2393. FreeSid(psidEveryOne);
  2394. }
  2395. if (pAcl) {
  2396. GlobalFree (pAcl);
  2397. }
  2398. return bRetVal;
  2399. }
  2400. //*************************************************************
  2401. //
  2402. // GetSpecialFolderPath()
  2403. //
  2404. // Purpose: Gets the path to the requested special folder
  2405. //
  2406. // Parameters: csid - CSIDL of the special folder
  2407. // lpPath - Path to place result in
  2408. // assumed to be MAX_PATH in size
  2409. //
  2410. // Return: TRUE if successful
  2411. // FALSE if an error occurs
  2412. //
  2413. //*************************************************************
  2414. BOOL GetSpecialFolderPath (INT csidl, LPTSTR lpPath)
  2415. {
  2416. BOOL bResult = FALSE;
  2417. PSHELL32_API pShell32Api = NULL;
  2418. HRESULT hr = E_FAIL;
  2419. if (SUCCEEDED(hr = HRESULT_FROM_WIN32(LoadShell32Api( &pShell32Api ))))
  2420. {
  2421. //
  2422. // Ask the shell for the folder location
  2423. //
  2424. bResult = pShell32Api->pfnShGetSpecialFolderPath (NULL, lpPath, csidl, TRUE);
  2425. if (!bResult)
  2426. {
  2427. hr = HRESULT_FROM_WIN32(GetLastError());
  2428. }
  2429. }
  2430. if (!bResult)
  2431. {
  2432. DebugMsg((DM_WARNING, TEXT("GetSpecialFolderPath : ShGetSpecialFolderPath failed, hr = %08X\n"), hr));
  2433. }
  2434. return bResult;
  2435. }
  2436. //*************************************************************
  2437. //
  2438. // GetFolderPath()
  2439. //
  2440. // Purpose: Gets the path to the requested special folder
  2441. //
  2442. // Parameters: csidl - CSIDL of the special folder
  2443. // lpPath - Path to place result in
  2444. // assumed to be MAX_PATH in size
  2445. //
  2446. // Return: TRUE if successful
  2447. // FALSE if an error occurs
  2448. //
  2449. //*************************************************************
  2450. BOOL GetFolderPath (INT csidl, HANDLE hToken, LPTSTR lpPath)
  2451. {
  2452. BOOL bResult = FALSE;
  2453. PSHELL32_API pShell32Api = NULL;
  2454. HRESULT hr = E_FAIL;
  2455. if (SUCCEEDED(hr = HRESULT_FROM_WIN32(LoadShell32Api( &pShell32Api ))))
  2456. {
  2457. //
  2458. // Ask the shell for the folder location
  2459. //
  2460. hr = pShell32Api->pfnShGetFolderPath (NULL,
  2461. csidl | CSIDL_FLAG_CREATE,
  2462. hToken,
  2463. 0,
  2464. lpPath);
  2465. bResult = SUCCEEDED ( hr );
  2466. }
  2467. if (!bResult)
  2468. {
  2469. DebugMsg((DM_WARNING, TEXT("GetFolderPath : ShGetFolderPath failed, hr = %08X\n"), hr));
  2470. }
  2471. return bResult;
  2472. }
  2473. //*************************************************************
  2474. //
  2475. // SetFolderPath()
  2476. //
  2477. // Purpose: Sets the path to the requested special folder
  2478. //
  2479. // Parameters: csidl - CSIDL of the special folder
  2480. // lpPath - Path
  2481. // assumed to be MAX_PATH in size
  2482. //
  2483. // Return: TRUE if successful
  2484. // FALSE if an error occurs
  2485. //
  2486. //*************************************************************
  2487. BOOL SetFolderPath (INT csidl, HANDLE hToken, LPTSTR lpPath)
  2488. {
  2489. BOOL bResult = FALSE;
  2490. PSHELL32_API pShell32Api = NULL;
  2491. HRESULT hr = E_FAIL;
  2492. if (SUCCEEDED(hr = HRESULT_FROM_WIN32(LoadShell32Api( &pShell32Api ))))
  2493. {
  2494. //
  2495. // Set the shell folder location
  2496. //
  2497. hr = pShell32Api->pfnShSetFolderPath (
  2498. csidl | CSIDL_FLAG_DONT_UNEXPAND,
  2499. hToken,
  2500. 0,
  2501. lpPath);
  2502. bResult = SUCCEEDED ( hr );
  2503. }
  2504. if (!bResult)
  2505. {
  2506. DebugMsg((DM_WARNING, TEXT("SetFolderPath : ShSetFolderPath failed, hr = %08X\n"), hr));
  2507. }
  2508. return bResult;
  2509. }
  2510. //*************************************************************
  2511. //
  2512. // CenterWindow()
  2513. //
  2514. // Purpose: Centers a window on the screen
  2515. //
  2516. // Parameters: hwnd - window handle to center
  2517. //
  2518. // Return: void
  2519. //
  2520. // Comments:
  2521. //
  2522. // History: Date Author Comment
  2523. // 2/21/96 ericflo Ported
  2524. //
  2525. //*************************************************************
  2526. void CenterWindow (HWND hwnd)
  2527. {
  2528. RECT rect;
  2529. LONG dx, dy;
  2530. LONG dxParent, dyParent;
  2531. LONG Style;
  2532. // Get window rect
  2533. GetWindowRect(hwnd, &rect);
  2534. dx = rect.right - rect.left;
  2535. dy = rect.bottom - rect.top;
  2536. // Get parent rect
  2537. Style = GetWindowLong(hwnd, GWL_STYLE);
  2538. if ((Style & WS_CHILD) == 0) {
  2539. // Return the desktop windows size (size of main screen)
  2540. dxParent = GetSystemMetrics(SM_CXSCREEN);
  2541. dyParent = GetSystemMetrics(SM_CYSCREEN);
  2542. } else {
  2543. HWND hwndParent;
  2544. RECT rectParent;
  2545. hwndParent = GetParent(hwnd);
  2546. if (hwndParent == NULL) {
  2547. hwndParent = GetDesktopWindow();
  2548. }
  2549. GetWindowRect(hwndParent, &rectParent);
  2550. dxParent = rectParent.right - rectParent.left;
  2551. dyParent = rectParent.bottom - rectParent.top;
  2552. }
  2553. // Centre the child in the parent
  2554. rect.left = (dxParent - dx) / 2;
  2555. rect.top = (dyParent - dy) / 3;
  2556. // Move the child into position
  2557. SetWindowPos(hwnd, HWND_TOP, rect.left, rect.top, 0, 0, SWP_NOSIZE);
  2558. }
  2559. //*************************************************************
  2560. //
  2561. // UnExpandSysRoot()
  2562. //
  2563. // Purpose: Unexpands the given path/filename to have %systemroot%
  2564. // if appropriate
  2565. //
  2566. // Parameters: lpFile - File to check
  2567. // lpResult - Result buffer
  2568. // cchResult - Result buffer size
  2569. //
  2570. // Return: TRUE if successful
  2571. // FALSE if an error occurs
  2572. //
  2573. // Comments:
  2574. //
  2575. // History: Date Author Comment
  2576. // 2/23/96 ericflo Created
  2577. //
  2578. //*************************************************************
  2579. BOOL UnExpandSysRoot(LPCTSTR lpFile, LPTSTR lpResult, DWORD cchResult)
  2580. {
  2581. TCHAR szSysRoot[MAX_PATH];
  2582. LPTSTR lpFileName;
  2583. DWORD dwSysLen;
  2584. HRESULT hr;
  2585. //
  2586. // Verbose Output
  2587. //
  2588. DebugMsg((DM_VERBOSE, TEXT("UnExpandSysRoot: Entering with <%s>"),
  2589. lpFile ? lpFile : TEXT("NULL")));
  2590. if (!lpFile || !*lpFile) {
  2591. DebugMsg((DM_VERBOSE, TEXT("UnExpandSysRoot: lpFile is NULL, setting lpResult to a null string")));
  2592. *lpResult = TEXT('\0');
  2593. return TRUE;
  2594. }
  2595. //
  2596. // If the first part of lpFile is the expanded value of %SystemRoot%
  2597. // then we want to un-expand the environment variable.
  2598. //
  2599. hr = SafeExpandEnvironmentStrings (TEXT("%SystemRoot%"), szSysRoot, ARRAYSIZE(szSysRoot));
  2600. if (FAILED(hr)) {
  2601. DebugMsg((DM_VERBOSE, TEXT("UnExpandSysRoot: ExpandEnvironmentString failed with error %d, setting szSysRoot to %systemroot% "), GetLastError()));
  2602. StringCchCopy(lpResult, cchResult, lpFile);
  2603. return FALSE;
  2604. }
  2605. dwSysLen = lstrlen(szSysRoot);
  2606. //
  2607. // Make sure the source is long enough
  2608. //
  2609. if ((DWORD)lstrlen(lpFile) < dwSysLen) {
  2610. StringCchCopy (lpResult, cchResult, lpFile);
  2611. return TRUE;
  2612. }
  2613. if (CompareString (LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
  2614. szSysRoot, dwSysLen,
  2615. lpFile, dwSysLen) == CSTR_EQUAL) {
  2616. //
  2617. // The szReturn buffer starts with %systemroot%.
  2618. // Actually insert %systemroot% in the result buffer.
  2619. //
  2620. StringCchCopy (lpResult, cchResult, TEXT("%SystemRoot%"));
  2621. StringCchCat (lpResult, cchResult, (lpFile + dwSysLen));
  2622. } else {
  2623. //
  2624. // The szReturn buffer does not start with %systemroot%
  2625. // just copy in the original string.
  2626. //
  2627. StringCchCopy (lpResult, cchResult, lpFile);
  2628. }
  2629. DebugMsg((DM_VERBOSE, TEXT("UnExpandSysRoot: Leaving with <%s>"), lpResult));
  2630. return TRUE;
  2631. }
  2632. //*************************************************************
  2633. //
  2634. // AllocAndExpandEnvironmentStrings()
  2635. //
  2636. // Purpose: Allocates memory for and returns pointer to buffer containing
  2637. // the passed string expanded.
  2638. //
  2639. // Parameters: lpszSrc - unexpanded string
  2640. //
  2641. // Return: Pointer to expanded string
  2642. // NULL if an error occurs
  2643. //
  2644. // Comments:
  2645. //
  2646. // History: Date Author Comment
  2647. // 6/21/96 ericflo Ported
  2648. //
  2649. //*************************************************************
  2650. LPTSTR AllocAndExpandEnvironmentStrings(LPCTSTR lpszSrc)
  2651. {
  2652. LPTSTR String, Temp;
  2653. LONG LengthAllocated;
  2654. LONG LengthCopied;
  2655. //
  2656. // Pick a random buffer length, if it's not big enough reallocate
  2657. // it and try again until it is.
  2658. //
  2659. LengthAllocated = lstrlen(lpszSrc) + 60;
  2660. String = LocalAlloc(LPTR, LengthAllocated * sizeof(TCHAR));
  2661. if (String == NULL) {
  2662. DebugMsg((DM_WARNING, TEXT("AllocAndExpandEnvironmentStrings: Failed to allocate %d bytes for string"), LengthAllocated * sizeof(TCHAR)));
  2663. return(NULL);
  2664. }
  2665. while (TRUE) {
  2666. LengthCopied = ExpandEnvironmentStrings( lpszSrc,
  2667. String,
  2668. LengthAllocated
  2669. );
  2670. if (LengthCopied == 0) {
  2671. DebugMsg((DM_WARNING, TEXT("AllocAndExpandEnvironmentStrings: ExpandEnvironmentStrings failed, error = %d"), GetLastError()));
  2672. LocalFree(String);
  2673. String = NULL;
  2674. break;
  2675. }
  2676. //
  2677. // If the buffer was too small, make it bigger and try again
  2678. //
  2679. if (LengthCopied > LengthAllocated) {
  2680. Temp = LocalReAlloc(String, LengthCopied * sizeof(TCHAR), LMEM_MOVEABLE);
  2681. if (Temp == NULL) {
  2682. DebugMsg((DM_WARNING, TEXT("AllocAndExpandEnvironmentStrings: Failed to reallocate %d bytes for string"), LengthAllocated * sizeof(TCHAR)));
  2683. LocalFree(String);
  2684. String = NULL;
  2685. break;
  2686. }
  2687. LengthAllocated = LengthCopied;
  2688. String = Temp;
  2689. //
  2690. // Go back and try to expand the string again
  2691. //
  2692. } else {
  2693. //
  2694. // Success!
  2695. //
  2696. break;
  2697. }
  2698. }
  2699. return(String);
  2700. }
  2701. //*************************************************************
  2702. //
  2703. // IntToString
  2704. //
  2705. // Purpose: TCHAR version of itoa
  2706. //
  2707. // Parameters: INT i - integer to convert
  2708. // LPTSTR sz - pointer where to put the result
  2709. //
  2710. // Return: void
  2711. //
  2712. //*************************************************************
  2713. void IntToString( INT i, LPTSTR sz) {
  2714. TCHAR szTemp[CCH_MAX_DEC];
  2715. int iChr;
  2716. iChr = 0;
  2717. do {
  2718. szTemp[iChr++] = TEXT('0') + (i % 10);
  2719. i = i / 10;
  2720. } while (i != 0);
  2721. do {
  2722. iChr--;
  2723. *sz++ = szTemp[iChr];
  2724. } while (iChr != 0);
  2725. *sz++ = TEXT('\0');
  2726. }
  2727. //*************************************************************
  2728. //
  2729. // IsUserAGuest()
  2730. //
  2731. // Purpose: Determines if the user is a member of the guest group.
  2732. //
  2733. // Parameters: hToken - User's token
  2734. //
  2735. // Return: TRUE if user is a guest
  2736. // FALSE if not
  2737. // Comments:
  2738. //
  2739. // History: Date Author Comment
  2740. // 7/25/95 ericflo Created
  2741. //
  2742. //*************************************************************
  2743. BOOL IsUserAGuest(HANDLE hToken)
  2744. {
  2745. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  2746. NTSTATUS Status;
  2747. BOOL FoundGuests=FALSE;
  2748. PSID pGuestSid=NULL, pDomainGuestSid=NULL, psidUser=NULL;
  2749. HANDLE hImpToken = NULL;
  2750. //
  2751. // Create Guests sid.
  2752. //
  2753. Status = RtlAllocateAndInitializeSid(
  2754. &authNT,
  2755. 2,
  2756. SECURITY_BUILTIN_DOMAIN_RID,
  2757. DOMAIN_ALIAS_RID_GUESTS,
  2758. 0, 0, 0, 0, 0, 0,
  2759. &pGuestSid
  2760. );
  2761. if (Status != STATUS_SUCCESS) {
  2762. DebugMsg((DM_WARNING, TEXT("IsUserAGuest: RtlAllocateAndInitializeSid failed with error 0x%x"), Status));
  2763. goto Exit;
  2764. }
  2765. if (!DuplicateTokenEx(hToken, TOKEN_IMPERSONATE | TOKEN_QUERY,
  2766. NULL, SecurityImpersonation, TokenImpersonation,
  2767. &hImpToken)) {
  2768. DebugMsg((DM_WARNING, TEXT("IsUserAGuest: DuplicateTokenEx failed with error %d"), GetLastError()));
  2769. hImpToken = NULL;
  2770. goto Exit;
  2771. }
  2772. if (!CheckTokenMembership(hImpToken, pGuestSid, &FoundGuests)) {
  2773. DebugMsg((DM_WARNING, TEXT("IsUserAGuest: CheckTokenMembership failed for GuestSid with error %d"), GetLastError()));
  2774. }
  2775. if (!FoundGuests) {
  2776. //
  2777. // Get the user's sid
  2778. //
  2779. psidUser = GetUserSid(hToken);
  2780. if (!psidUser) {
  2781. DebugMsg((DM_WARNING, TEXT("MakeRegKeySecure: Failed to get user sid")));
  2782. goto Exit;
  2783. }
  2784. //
  2785. // Create Domain Guests sid.
  2786. //
  2787. Status = GetDomainSidFromDomainRid(
  2788. psidUser,
  2789. DOMAIN_GROUP_RID_GUESTS,
  2790. &pDomainGuestSid);
  2791. if (Status != STATUS_SUCCESS) {
  2792. DebugMsg((DM_WARNING, TEXT("IsUserAGuest: GetDomainSidFromDomainRid failed with error 0x%x"), Status));
  2793. goto Exit;
  2794. }
  2795. if (!CheckTokenMembership(hImpToken, pDomainGuestSid, &FoundGuests)) {
  2796. DebugMsg((DM_WARNING, TEXT("IsUserAGuest: CheckTokenMembership failed for DomainGuestSid with error %d"), GetLastError()));
  2797. }
  2798. }
  2799. //
  2800. // Tidy up
  2801. //
  2802. Exit:
  2803. if (pGuestSid)
  2804. RtlFreeSid(pGuestSid);
  2805. if (pDomainGuestSid)
  2806. RtlFreeSid(pDomainGuestSid);
  2807. if (psidUser)
  2808. DeleteUserSid (psidUser);
  2809. if (hImpToken)
  2810. CloseHandle(hImpToken);
  2811. return(FoundGuests);
  2812. }
  2813. //*************************************************************
  2814. //
  2815. // IsUserAnAdminMember()
  2816. //
  2817. // Purpose: Determines if the user is a member of the administrators group.
  2818. //
  2819. // Parameters: hToken - User's token
  2820. //
  2821. // Return: TRUE if user is a admin
  2822. // FALSE if not
  2823. // Comments:
  2824. //
  2825. // History: Date Author Comment
  2826. // 7/25/95 ericflo Created
  2827. //
  2828. //*************************************************************
  2829. BOOL IsUserAnAdminMember(HANDLE hToken)
  2830. {
  2831. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  2832. NTSTATUS Status;
  2833. BOOL FoundAdmins = FALSE;
  2834. PSID AdminsDomainSid=NULL;
  2835. HANDLE hImpToken = NULL;
  2836. //
  2837. // Create Admins domain sid.
  2838. //
  2839. Status = RtlAllocateAndInitializeSid(
  2840. &authNT,
  2841. 2,
  2842. SECURITY_BUILTIN_DOMAIN_RID,
  2843. DOMAIN_ALIAS_RID_ADMINS,
  2844. 0, 0, 0, 0, 0, 0,
  2845. &AdminsDomainSid
  2846. );
  2847. if (Status == STATUS_SUCCESS) {
  2848. //
  2849. // Test if user is in the Admins domain
  2850. //
  2851. if (!DuplicateTokenEx(hToken, TOKEN_IMPERSONATE | TOKEN_QUERY,
  2852. NULL, SecurityImpersonation, TokenImpersonation,
  2853. &hImpToken)) {
  2854. DebugMsg((DM_WARNING, TEXT("IsUserAnAdminMember: DuplicateTokenEx failed with error %d"), GetLastError()));
  2855. FoundAdmins = FALSE;
  2856. hImpToken = NULL;
  2857. goto Exit;
  2858. }
  2859. if (!CheckTokenMembership(hImpToken, AdminsDomainSid, &FoundAdmins)) {
  2860. DebugMsg((DM_WARNING, TEXT("IsUserAnAdminmember: CheckTokenMembership failed for AdminsDomainSid with error %d"), GetLastError()));
  2861. FoundAdmins = FALSE;
  2862. }
  2863. }
  2864. //
  2865. // Tidy up
  2866. //
  2867. Exit:
  2868. if (hImpToken)
  2869. CloseHandle(hImpToken);
  2870. if (AdminsDomainSid)
  2871. RtlFreeSid(AdminsDomainSid);
  2872. return(FoundAdmins);
  2873. }
  2874. //*************************************************************
  2875. //
  2876. // IsUserALocalSystemMember()
  2877. //
  2878. // Purpose: Determines if the user is a member of the Local system group.
  2879. //
  2880. // Parameters: hToken - User's token
  2881. //
  2882. // Return: TRUE if user is a local system
  2883. // FALSE if not
  2884. // Comments:
  2885. //
  2886. // History: Date Author Comment
  2887. // 9/22/00 santanuc created
  2888. //
  2889. //*************************************************************
  2890. BOOL IsUserALocalSystemMember(HANDLE hToken)
  2891. {
  2892. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  2893. NTSTATUS Status;
  2894. BOOL FoundLocalSystem = FALSE;
  2895. PSID LocalSystemSid=NULL;
  2896. HANDLE hImpToken = NULL;
  2897. //
  2898. // Create Local system sid.
  2899. //
  2900. Status = RtlAllocateAndInitializeSid(
  2901. &authNT,
  2902. 1,
  2903. SECURITY_LOCAL_SYSTEM_RID,
  2904. 0, 0, 0, 0, 0, 0, 0,
  2905. &LocalSystemSid
  2906. );
  2907. if (Status == STATUS_SUCCESS) {
  2908. //
  2909. // Test if user is in the Local system
  2910. //
  2911. if (!DuplicateTokenEx(hToken, TOKEN_IMPERSONATE | TOKEN_QUERY,
  2912. NULL, SecurityImpersonation, TokenImpersonation,
  2913. &hImpToken)) {
  2914. DebugMsg((DM_WARNING, TEXT("IsUserAGuest: DuplicateTokenEx failed with error %d"), GetLastError()));
  2915. FoundLocalSystem = FALSE;
  2916. hImpToken = NULL;
  2917. goto Exit;
  2918. }
  2919. if (!CheckTokenMembership(hImpToken, LocalSystemSid, &FoundLocalSystem)) {
  2920. DebugMsg((DM_WARNING, TEXT("IsUserAnAdminmember: CheckTokenMembership failed for LocalSystemSid with error %d"), GetLastError()));
  2921. FoundLocalSystem = FALSE;
  2922. }
  2923. }
  2924. //
  2925. // Tidy up
  2926. //
  2927. Exit:
  2928. if (hImpToken)
  2929. CloseHandle(hImpToken);
  2930. if (LocalSystemSid)
  2931. RtlFreeSid(LocalSystemSid);
  2932. return(FoundLocalSystem);
  2933. }
  2934. //*************************************************************
  2935. //
  2936. // IsUserAnInteractiveUser()
  2937. //
  2938. // Purpose: Determines if the user is interactively logged on.
  2939. //
  2940. // Parameters: hToken - User's token
  2941. //
  2942. // Return: TRUE if user is logged on interactively
  2943. // FALSE if not
  2944. // Comments:
  2945. //
  2946. //*************************************************************
  2947. BOOL IsUserAnInteractiveUser(HANDLE hToken)
  2948. {
  2949. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  2950. BOOL bInteractive = FALSE;
  2951. PSID pInteractiveSid=NULL;
  2952. HANDLE hImpToken = NULL;
  2953. //
  2954. // Create Admins domain sid.
  2955. //
  2956. if (AllocateAndInitializeSid(&authNT, 1, SECURITY_INTERACTIVE_RID,
  2957. 0, 0, 0, 0, 0, 0, 0, &pInteractiveSid)) {
  2958. //
  2959. // Test if user is interactive
  2960. //
  2961. if (!DuplicateTokenEx(hToken, TOKEN_IMPERSONATE | TOKEN_QUERY,
  2962. NULL, SecurityImpersonation, TokenImpersonation,
  2963. &hImpToken)) {
  2964. DebugMsg((DM_WARNING, TEXT("IsUserAnInteractiveUser: DuplicateTokenEx failed with error %d"), GetLastError()));
  2965. bInteractive = FALSE;
  2966. hImpToken = NULL;
  2967. goto Exit;
  2968. }
  2969. if (!CheckTokenMembership(hImpToken, pInteractiveSid, &bInteractive)) {
  2970. DebugMsg((DM_WARNING, TEXT("IsUserAnInteractiveUser: CheckTokenMembership failed for InteractiveSid with error %d"), GetLastError()));
  2971. bInteractive = FALSE;
  2972. }
  2973. }
  2974. else {
  2975. DebugMsg((DM_WARNING, TEXT("IsUserAnInteractiveUser: AllocateAndInitializeSid failed for InteractiveSid with error %d"), GetLastError()));
  2976. }
  2977. //
  2978. // Tidy up
  2979. //
  2980. Exit:
  2981. if (hImpToken)
  2982. CloseHandle(hImpToken);
  2983. if (pInteractiveSid)
  2984. FreeSid(pInteractiveSid);
  2985. return(bInteractive);
  2986. }
  2987. //*************************************************************
  2988. //
  2989. // CheckUserInMachineForest()
  2990. //
  2991. // Purpose: Determines if the user is from the same forest
  2992. // as the computer this code is running on.
  2993. //
  2994. // Parameters: hToken - User's token
  2995. //
  2996. // Return: ERROR_SUCCESS if successful
  2997. // <error> code if not.
  2998. // Comments:
  2999. //
  3000. //*************************************************************
  3001. DWORD CheckUserInMachineForest(HANDLE hToken, BOOL* pbInMachineForest)
  3002. {
  3003. DWORD dwResult = ERROR_SUCCESS;
  3004. HANDLE hOldToken = NULL;
  3005. LPWSTR szUserDomainName = NULL;
  3006. PDS_DOMAIN_TRUSTS pDomainTrusts = NULL;
  3007. ULONG ulDomainCount = 0;
  3008. ULONG ulCount = 0;
  3009. if ( (hToken == NULL) || (pbInMachineForest == NULL) )
  3010. {
  3011. return ERROR_INVALID_PARAMETER;
  3012. }
  3013. // Default to this
  3014. *pbInMachineForest = FALSE;
  3015. // Query for the user's domain name
  3016. if (!ImpersonateUser(hToken, &hOldToken))
  3017. {
  3018. dwResult = GetLastError();
  3019. DebugMsg((DM_WARNING, TEXT("CheckUserInMachineForest: Failed to impersonate user with %d."), dwResult));
  3020. goto Exit;
  3021. }
  3022. szUserDomainName = MyGetDomainDNSName ();
  3023. RevertToUser(&hOldToken);
  3024. if ( szUserDomainName == NULL )
  3025. {
  3026. dwResult = GetLastError();
  3027. DebugMsg((DM_WARNING, TEXT("CheckUserInMachineForest: MyGetDomainName failed with %d."), dwResult));
  3028. goto Exit;
  3029. }
  3030. // Now get the list of trusted domains for this machine
  3031. dwResult = DsEnumerateDomainTrusts( NULL, DS_DOMAIN_IN_FOREST, &pDomainTrusts, &ulDomainCount );
  3032. if ( dwResult != NO_ERROR )
  3033. {
  3034. pDomainTrusts = NULL;
  3035. DebugMsg((DM_WARNING, TEXT("CheckUserInMachineForest: Failed to enumerate forest domains with %d."), dwResult));
  3036. goto Exit;
  3037. }
  3038. dwResult = ERROR_SUCCESS;
  3039. for ( ulCount = 0; ulCount < ulDomainCount; ulCount++ )
  3040. {
  3041. if ( DnsNameCompare_W(szUserDomainName, pDomainTrusts[ulCount].DnsDomainName) )
  3042. {
  3043. *pbInMachineForest = TRUE;
  3044. goto Exit;
  3045. }
  3046. }
  3047. Exit:
  3048. if ( szUserDomainName != NULL )
  3049. {
  3050. LocalFree( szUserDomainName );
  3051. }
  3052. if ( pDomainTrusts != NULL )
  3053. {
  3054. NetApiBufferFree( pDomainTrusts );
  3055. }
  3056. return dwResult;
  3057. }
  3058. //*************************************************************
  3059. //
  3060. // MakeRegKeySecure()
  3061. //
  3062. // Purpose: Sets the security for the key give so that
  3063. // the admin and os having full control with the
  3064. // user having read / execute.
  3065. //
  3066. // Parameters: hToken - User's token or null for "everyone"
  3067. // hKeyRoot - Key to the root of the hive
  3068. // lpKeyName - Key to secure
  3069. //
  3070. // Return: TRUE if successful
  3071. // FALSE if an error occurs
  3072. //
  3073. // Comments:
  3074. //
  3075. // History: Date Author Comment
  3076. // 5/7/97 ericflo Created
  3077. //
  3078. //*************************************************************
  3079. BOOL MakeRegKeySecure(HANDLE hToken, HKEY hKeyRoot, LPTSTR lpKeyName)
  3080. {
  3081. DWORD Error, dwDisp;
  3082. HKEY hSubKey;
  3083. SECURITY_DESCRIPTOR sd;
  3084. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  3085. PACL pAcl = NULL;
  3086. PSID psidUser = NULL, psidSystem = NULL, psidAdmin = NULL;
  3087. DWORD cbAcl, AceIndex;
  3088. ACE_HEADER * lpAceHeader;
  3089. BOOL bRetVal = FALSE;
  3090. //
  3091. // Create the security descriptor that will be applied to the key
  3092. //
  3093. if (hToken) {
  3094. //
  3095. // Get the user's sid
  3096. //
  3097. psidUser = GetUserSid(hToken);
  3098. if (!psidUser) {
  3099. DebugMsg((DM_WARNING, TEXT("MakeRegKeySecure: Failed to get user sid")));
  3100. return FALSE;
  3101. }
  3102. } else {
  3103. //
  3104. // Get the authenticated users sid
  3105. //
  3106. if (!AllocateAndInitializeSid(&authNT, 1, SECURITY_AUTHENTICATED_USER_RID,
  3107. 0, 0, 0, 0, 0, 0, 0, &psidUser)) {
  3108. DebugMsg((DM_WARNING, TEXT("MakeRegKeySecure: Failed to initialize authenticated users sid. Error = %d"), GetLastError()));
  3109. return FALSE;
  3110. }
  3111. }
  3112. //
  3113. // Get the system sid
  3114. //
  3115. if (!AllocateAndInitializeSid(&authNT, 1, SECURITY_LOCAL_SYSTEM_RID,
  3116. 0, 0, 0, 0, 0, 0, 0, &psidSystem)) {
  3117. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to initialize system sid. Error = %d"), GetLastError()));
  3118. goto Exit;
  3119. }
  3120. //
  3121. // Get the admin sid
  3122. //
  3123. if (!AllocateAndInitializeSid(&authNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
  3124. DOMAIN_ALIAS_RID_ADMINS, 0, 0,
  3125. 0, 0, 0, 0, &psidAdmin)) {
  3126. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to initialize admin sid. Error = %d"), GetLastError()));
  3127. goto Exit;
  3128. }
  3129. //
  3130. // Allocate space for the ACL
  3131. //
  3132. cbAcl = (2 * GetLengthSid (psidUser)) + (2 * GetLengthSid (psidSystem)) +
  3133. (2 * GetLengthSid (psidAdmin)) + sizeof(ACL) +
  3134. (6 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)));
  3135. pAcl = (PACL) GlobalAlloc(GMEM_FIXED, cbAcl);
  3136. if (!pAcl) {
  3137. goto Exit;
  3138. }
  3139. if (!InitializeAcl(pAcl, cbAcl, ACL_REVISION)) {
  3140. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to initialize acl. Error = %d"), GetLastError()));
  3141. goto Exit;
  3142. }
  3143. //
  3144. // Add Aces for User, System, and Admin. Non-inheritable ACEs first
  3145. //
  3146. AceIndex = 0;
  3147. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, KEY_READ, psidUser)) {
  3148. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to add ace for user. Error = %d"), GetLastError()));
  3149. goto Exit;
  3150. }
  3151. AceIndex++;
  3152. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, KEY_ALL_ACCESS, psidSystem)) {
  3153. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to add ace for system. Error = %d"), GetLastError()));
  3154. goto Exit;
  3155. }
  3156. AceIndex++;
  3157. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, KEY_ALL_ACCESS, psidAdmin)) {
  3158. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to add ace for admin. Error = %d"), GetLastError()));
  3159. goto Exit;
  3160. }
  3161. //
  3162. // Now the inheritable ACEs
  3163. //
  3164. AceIndex++;
  3165. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_READ, psidUser)) {
  3166. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to add ace for user. Error = %d"), GetLastError()));
  3167. goto Exit;
  3168. }
  3169. if (!GetAce(pAcl, AceIndex, &lpAceHeader)) {
  3170. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to get ace (%d). Error = %d"), AceIndex, GetLastError()));
  3171. goto Exit;
  3172. }
  3173. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  3174. AceIndex++;
  3175. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, psidSystem)) {
  3176. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to add ace for system. Error = %d"), GetLastError()));
  3177. goto Exit;
  3178. }
  3179. if (!GetAce(pAcl, AceIndex, &lpAceHeader)) {
  3180. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to get ace (%d). Error = %d"), AceIndex, GetLastError()));
  3181. goto Exit;
  3182. }
  3183. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  3184. AceIndex++;
  3185. if (!AddAccessAllowedAce(pAcl, ACL_REVISION, GENERIC_ALL, psidAdmin)) {
  3186. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to add ace for admin. Error = %d"), GetLastError()));
  3187. goto Exit;
  3188. }
  3189. if (!GetAce(pAcl, AceIndex, &lpAceHeader)) {
  3190. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to get ace (%d). Error = %d"), AceIndex, GetLastError()));
  3191. goto Exit;
  3192. }
  3193. lpAceHeader->AceFlags |= (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE);
  3194. //
  3195. // Put together the security descriptor
  3196. //
  3197. if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
  3198. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to initialize security descriptor. Error = %d"), GetLastError()));
  3199. goto Exit;
  3200. }
  3201. if (!SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE)) {
  3202. DebugMsg((DM_VERBOSE, TEXT("MakeRegKeySecure: Failed to set security descriptor dacl. Error = %d"), GetLastError()));
  3203. goto Exit;
  3204. }
  3205. //
  3206. // Open the registry key
  3207. //
  3208. Error = RegCreateKeyEx(hKeyRoot,
  3209. lpKeyName,
  3210. 0,
  3211. NULL,
  3212. REG_OPTION_NON_VOLATILE,
  3213. WRITE_DAC,
  3214. NULL,
  3215. &hSubKey,
  3216. &dwDisp);
  3217. if (Error == ERROR_SUCCESS) {
  3218. Error = RegSetKeySecurity (hSubKey, DACL_SECURITY_INFORMATION, &sd);
  3219. if (Error == ERROR_SUCCESS) {
  3220. bRetVal = TRUE;
  3221. } else {
  3222. DebugMsg((DM_WARNING, TEXT("MakeRegKeySecure: Failed to set security, error = %d"), Error));
  3223. }
  3224. RegCloseKey(hSubKey);
  3225. } else {
  3226. DebugMsg((DM_WARNING, TEXT("MakeRegKeySecure: Failed to open registry key, error = %d"), Error));
  3227. }
  3228. Exit:
  3229. //
  3230. // Free the sids and acl
  3231. //
  3232. if (psidUser) {
  3233. if (hToken) {
  3234. DeleteUserSid (psidUser);
  3235. } else {
  3236. FreeSid (psidUser);
  3237. }
  3238. }
  3239. if (psidSystem) {
  3240. FreeSid(psidSystem);
  3241. }
  3242. if (psidAdmin) {
  3243. FreeSid(psidAdmin);
  3244. }
  3245. if (pAcl) {
  3246. GlobalFree (pAcl);
  3247. }
  3248. return(bRetVal);
  3249. }
  3250. //*************************************************************
  3251. //
  3252. // FlushSpecialFolderCache()
  3253. //
  3254. // Purpose: Flushes the special folder cache in the shell
  3255. //
  3256. // Parameters: none
  3257. //
  3258. // Comments: Shell32.dll caches the special folder pidls
  3259. // but since winlogon never goes away, it is possible
  3260. // for one user's pidls to be used for another user
  3261. //
  3262. //
  3263. // Return: TRUE if successful
  3264. // FALSE if an error occurs
  3265. //
  3266. //*************************************************************
  3267. typedef VOID (*PFNSHFLUSHSFCACHE)(VOID);
  3268. BOOL FlushSpecialFolderCache (void)
  3269. {
  3270. HINSTANCE hInstDLL;
  3271. PFNSHFLUSHSFCACHE pfnSHFlushSFCache;
  3272. BOOL bResult = FALSE;
  3273. hInstDLL = LoadLibraryA ("shell32.dll");
  3274. if (hInstDLL) {
  3275. pfnSHFlushSFCache = (PFNSHFLUSHSFCACHE)GetProcAddress (hInstDLL,
  3276. MAKEINTRESOURCEA(526));
  3277. if (pfnSHFlushSFCache) {
  3278. pfnSHFlushSFCache();
  3279. bResult = TRUE;
  3280. }
  3281. FreeLibrary (hInstDLL);
  3282. }
  3283. return bResult;
  3284. }
  3285. //*************************************************************
  3286. //
  3287. // CheckForVerbosePolicy()
  3288. //
  3289. // Purpose: Checks if the user has requested verbose
  3290. // output of policy to the eventlog
  3291. //
  3292. // Parameters: None
  3293. //
  3294. // Return: TRUE if we should be verbose
  3295. // FALSE if not
  3296. //
  3297. //*************************************************************
  3298. BOOL CheckForVerbosePolicy (void)
  3299. {
  3300. DWORD dwSize, dwType;
  3301. BOOL bVerbose = FALSE;
  3302. HKEY hKey;
  3303. LONG lResult;
  3304. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, DIAGNOSTICS_KEY,
  3305. 0, KEY_READ, &hKey) == ERROR_SUCCESS)
  3306. {
  3307. dwSize = sizeof(bVerbose);
  3308. if (RegQueryValueEx (hKey, DIAGNOSTICS_POLICY_VALUE, NULL,
  3309. &dwType, (LPBYTE) &bVerbose,
  3310. &dwSize) != ERROR_SUCCESS)
  3311. {
  3312. RegQueryValueEx (hKey, DIAGNOSTICS_GLOBAL_VALUE, NULL,
  3313. &dwType, (LPBYTE) &bVerbose, &dwSize);
  3314. }
  3315. RegCloseKey (hKey);
  3316. }
  3317. return bVerbose;
  3318. }
  3319. //*************************************************************
  3320. //
  3321. // int ExtractCSIDL()
  3322. //
  3323. // Purpose: Extract the CSIDL from the given string which
  3324. // should under the form ::0x0000::path1\path2\...\
  3325. // pathn\file.ext, where 0x0000 is any valid CSIDL
  3326. //
  3327. // Parameters: pcszPath - Path containing or not a CSIDL
  3328. // ppszUsualPath - pointer to first characvter of
  3329. // usual path
  3330. //
  3331. // Return: CSIDL if successful
  3332. // -1 if no CSIDL in path
  3333. //
  3334. // Comments: The ::0x0000:: must be at the beginning and not
  3335. // preceded by any other character and not followed
  3336. // by any either (other than the usual path)
  3337. //
  3338. // History: Date Author Comment
  3339. // 6/9/98 stephstm Created
  3340. //
  3341. //*************************************************************
  3342. int ExtractCSIDL(LPCTSTR pcszPath, LPTSTR* ppszUsualPath)
  3343. {
  3344. int nRV=-1;
  3345. if (NULL != ppszUsualPath)
  3346. {
  3347. if (TEXT(':') == *pcszPath && TEXT(':') == *(pcszPath+1) &&
  3348. TEXT(':') == *(pcszPath+8) && TEXT(':') == *(pcszPath+9))
  3349. {//looks good
  3350. //+4 to skip "::0x"
  3351. nRV = HexStringToUInt(pcszPath+4);
  3352. *ppszUsualPath = (LPTSTR)(pcszPath+10);
  3353. }
  3354. else
  3355. {//no CSIDL in this path
  3356. //the whole path is a usual path
  3357. *ppszUsualPath = (LPTSTR)pcszPath;
  3358. }
  3359. }
  3360. else
  3361. {
  3362. DebugMsg((DM_VERBOSE, TEXT("ExtractCSIDL: ppszUsualPath ptr is NULL.")));
  3363. }
  3364. return nRV;
  3365. }
  3366. //*************************************************************
  3367. //
  3368. // MyGetDomainDNSName()
  3369. //
  3370. // Purpose: Gets the user's domain dns name
  3371. //
  3372. // Parameters: void
  3373. //
  3374. // Return: lpDomain if successful
  3375. // NULL if an error occurs
  3376. //
  3377. //*************************************************************
  3378. LPTSTR MyGetDomainDNSName (VOID)
  3379. {
  3380. LPTSTR lpTemp, lpDomain;
  3381. //
  3382. // Get the username in DNS format. It will return it in
  3383. // dnsdomainname\username
  3384. //
  3385. lpDomain = MyGetUserName (NameDnsDomain);
  3386. if (!lpDomain) {
  3387. DebugMsg((DM_WARNING, TEXT("MyGetDomainName: MyGetUserName failed for dns domain name with %d"),
  3388. GetLastError()));
  3389. return NULL;
  3390. }
  3391. //
  3392. // Look for the \ between the domain and username and replace
  3393. // it with a NULL
  3394. //
  3395. lpTemp = lpDomain;
  3396. while (*lpTemp && ((*lpTemp) != TEXT('\\')))
  3397. lpTemp++;
  3398. if (*lpTemp != TEXT('\\')) {
  3399. DebugMsg((DM_WARNING, TEXT("GetUserAndDomainNames: Failed to find slash in dns style name: <%s>"),
  3400. lpDomain));
  3401. SetLastError(ERROR_INVALID_DATA);
  3402. LocalFree (lpDomain);
  3403. return NULL;
  3404. }
  3405. *lpTemp = TEXT('\0');
  3406. return lpDomain;
  3407. }
  3408. //*************************************************************
  3409. //
  3410. // MyGetUserName()
  3411. //
  3412. // Purpose: Gets the user name in the requested format
  3413. //
  3414. // Parameters: NameFormat - GetUserNameEx naming format
  3415. //
  3416. // Return: lpUserName if successful
  3417. // NULL if an error occurs
  3418. //
  3419. //*************************************************************
  3420. LPTSTR MyGetUserName (EXTENDED_NAME_FORMAT NameFormat)
  3421. {
  3422. DWORD dwCount = 0, dwError = ERROR_SUCCESS;
  3423. LPTSTR lpUserName = NULL, lpTemp;
  3424. ULONG ulUserNameSize;
  3425. PSECUR32_API pSecur32;
  3426. //
  3427. // Load secur32.dll
  3428. //
  3429. pSecur32 = LoadSecur32();
  3430. if (!pSecur32) {
  3431. DebugMsg((DM_WARNING, TEXT("MyGetUserName: Failed to load Secur32.")));
  3432. return NULL;
  3433. }
  3434. //
  3435. // Allocate a buffer for the user name
  3436. //
  3437. ulUserNameSize = 75;
  3438. if (NameFormat == NameFullyQualifiedDN) {
  3439. ulUserNameSize = 200;
  3440. }
  3441. lpUserName = LocalAlloc (LPTR, ulUserNameSize * sizeof(TCHAR));
  3442. if (!lpUserName) {
  3443. dwError = GetLastError();
  3444. DebugMsg((DM_WARNING, TEXT("MyGetUserName: Failed to allocate memory with %d"),
  3445. dwError));
  3446. goto Exit;
  3447. }
  3448. //
  3449. // Get the username in the requested format
  3450. //
  3451. while (TRUE) {
  3452. if (pSecur32->pfnGetUserNameEx (NameFormat, lpUserName, &ulUserNameSize)) {
  3453. dwError = ERROR_SUCCESS;
  3454. goto Exit;
  3455. } else {
  3456. //
  3457. // Get the error code
  3458. //
  3459. dwError = GetLastError();
  3460. //
  3461. // If the call failed due to insufficient memory, realloc
  3462. // the buffer and try again. Otherwise, check the pass
  3463. // count and retry if appropriate.
  3464. //
  3465. if ((dwError == ERROR_INSUFFICIENT_BUFFER) ||
  3466. (dwError == ERROR_MORE_DATA)) {
  3467. lpTemp = LocalReAlloc (lpUserName, (ulUserNameSize * sizeof(TCHAR)),
  3468. LMEM_MOVEABLE);
  3469. if (!lpTemp) {
  3470. dwError = GetLastError();
  3471. DebugMsg((DM_WARNING, TEXT("MyGetUserName: Failed to realloc memory with %d"),
  3472. dwError));
  3473. LocalFree (lpUserName);
  3474. lpUserName = NULL;
  3475. goto Exit;
  3476. }
  3477. lpUserName = lpTemp;
  3478. } else if ((dwError == ERROR_NONE_MAPPED) || (dwError == ERROR_NETWORK_UNREACHABLE)) {
  3479. LocalFree (lpUserName);
  3480. lpUserName = NULL;
  3481. goto Exit;
  3482. } else {
  3483. DebugMsg((DM_WARNING, TEXT("MyGetUserName: GetUserNameEx failed with %d."),
  3484. dwError));
  3485. dwCount++;
  3486. if (dwCount > 3) {
  3487. LocalFree (lpUserName);
  3488. lpUserName = NULL;
  3489. goto Exit;
  3490. }
  3491. DebugMsg((DM_VERBOSE, TEXT("MyGetUserName: Retrying call to GetUserNameEx in 1/2 second.")));
  3492. Sleep(500);
  3493. }
  3494. }
  3495. }
  3496. Exit:
  3497. SetLastError(dwError);
  3498. return lpUserName;
  3499. }
  3500. //*************************************************************
  3501. //
  3502. // MyGetUserNameEx()
  3503. //
  3504. // Purpose: Gets the user name in the requested format
  3505. //
  3506. // Parameters: NameFormat - GetUserNameEx naming format
  3507. //
  3508. // Return: lpUserName if successful
  3509. // NULL if an error occurs
  3510. //
  3511. //*************************************************************
  3512. LPTSTR MyGetUserNameEx (EXTENDED_NAME_FORMAT NameFormat)
  3513. {
  3514. DWORD dwCount = 0, dwError = ERROR_SUCCESS;
  3515. LPTSTR lpUserName = NULL, lpTemp;
  3516. ULONG ulUserNameSize;
  3517. PSECUR32_API pSecur32;
  3518. //
  3519. // Load secur32.dll
  3520. //
  3521. pSecur32 = LoadSecur32();
  3522. if (!pSecur32) {
  3523. DebugMsg((DM_WARNING, TEXT("MyGetUserNameEx: Failed to load Secur32.")));
  3524. return NULL;
  3525. }
  3526. //
  3527. // Allocate a buffer for the user name
  3528. //
  3529. ulUserNameSize = 75;
  3530. if (NameFormat == NameFullyQualifiedDN) {
  3531. ulUserNameSize = 200;
  3532. }
  3533. lpUserName = LocalAlloc (LPTR, ulUserNameSize * sizeof(TCHAR));
  3534. if (!lpUserName) {
  3535. dwError = GetLastError();
  3536. DebugMsg((DM_WARNING, TEXT("MyGetUserNameEx: Failed to allocate memory with %d"),
  3537. dwError));
  3538. goto Exit;
  3539. }
  3540. //
  3541. // Get the username in the requested format
  3542. //
  3543. if (!pSecur32->pfnGetUserNameEx (NameFormat, lpUserName, &ulUserNameSize)) {
  3544. //
  3545. // If the call failed due to insufficient memory, realloc
  3546. // the buffer and try again. Otherwise, exit now.
  3547. //
  3548. dwError = GetLastError();
  3549. if ((dwError != ERROR_INSUFFICIENT_BUFFER) && (dwError != ERROR_MORE_DATA)) {
  3550. LocalFree (lpUserName);
  3551. lpUserName = NULL;
  3552. goto Exit;
  3553. }
  3554. lpTemp = LocalReAlloc (lpUserName, (ulUserNameSize * sizeof(TCHAR)),
  3555. LMEM_MOVEABLE);
  3556. if (!lpTemp) {
  3557. dwError = GetLastError();
  3558. DebugMsg((DM_WARNING, TEXT("MyGetUserNameEx: Failed to realloc memory with %d"),
  3559. dwError));
  3560. LocalFree (lpUserName);
  3561. lpUserName = NULL;
  3562. goto Exit;
  3563. }
  3564. lpUserName = lpTemp;
  3565. if (!pSecur32->pfnGetUserNameEx (NameFormat, lpUserName, &ulUserNameSize)) {
  3566. dwError = GetLastError();
  3567. LocalFree (lpUserName);
  3568. lpUserName = NULL;
  3569. goto Exit;
  3570. }
  3571. dwError = ERROR_SUCCESS;
  3572. }
  3573. Exit:
  3574. SetLastError(dwError);
  3575. return lpUserName;
  3576. }
  3577. //*************************************************************
  3578. //
  3579. // MyGetComputerName()
  3580. //
  3581. // Purpose: Gets the computer name in the requested format
  3582. //
  3583. // Parameters: NameFormat - GetComputerObjectName naming format
  3584. //
  3585. // Return: lpComputerName if successful
  3586. // NULL if an error occurs
  3587. //
  3588. //*************************************************************
  3589. LPTSTR MyGetComputerName (EXTENDED_NAME_FORMAT NameFormat)
  3590. {
  3591. DWORD dwError = ERROR_SUCCESS;
  3592. LPTSTR lpComputerName = NULL, lpTemp;
  3593. ULONG ulComputerNameSize;
  3594. PSECUR32_API pSecur32;
  3595. //
  3596. // Load secur32.dll
  3597. //
  3598. pSecur32 = LoadSecur32();
  3599. if (!pSecur32) {
  3600. DebugMsg((DM_WARNING, TEXT("MyGetComputerName: Failed to load Secur32.")));
  3601. return NULL;
  3602. }
  3603. //
  3604. // Allocate a buffer for the computer name
  3605. //
  3606. ulComputerNameSize = 75;
  3607. if (NameFormat == NameFullyQualifiedDN) {
  3608. ulComputerNameSize = 200;
  3609. }
  3610. lpComputerName = LocalAlloc (LPTR, ulComputerNameSize * sizeof(TCHAR));
  3611. if (!lpComputerName) {
  3612. dwError = GetLastError();
  3613. DebugMsg((DM_WARNING, TEXT("MyGetComputerName: Failed to allocate memory with %d"),
  3614. dwError));
  3615. goto Exit;
  3616. }
  3617. //
  3618. // Get the computer name in the requested format
  3619. //
  3620. if (!pSecur32->pfnGetComputerObjectName (NameFormat, lpComputerName, &ulComputerNameSize)) {
  3621. //
  3622. // If the call failed due to insufficient memory, realloc
  3623. // the buffer and try again. Otherwise, exit now.
  3624. //
  3625. dwError = GetLastError();
  3626. if (dwError != ERROR_INSUFFICIENT_BUFFER) {
  3627. LocalFree (lpComputerName);
  3628. lpComputerName = NULL;
  3629. goto Exit;
  3630. }
  3631. lpTemp = LocalReAlloc (lpComputerName, (ulComputerNameSize * sizeof(TCHAR)),
  3632. LMEM_MOVEABLE);
  3633. if (!lpTemp) {
  3634. dwError = GetLastError();
  3635. DebugMsg((DM_WARNING, TEXT("MyGetComputerName: Failed to realloc memory with %d"),
  3636. dwError));
  3637. LocalFree (lpComputerName);
  3638. lpComputerName = NULL;
  3639. goto Exit;
  3640. }
  3641. lpComputerName = lpTemp;
  3642. if (!pSecur32->pfnGetComputerObjectName (NameFormat, lpComputerName, &ulComputerNameSize)) {
  3643. dwError = GetLastError();
  3644. LocalFree (lpComputerName);
  3645. lpComputerName = NULL;
  3646. goto Exit;
  3647. }
  3648. dwError = ERROR_SUCCESS;
  3649. }
  3650. Exit:
  3651. SetLastError(dwError);
  3652. return lpComputerName;
  3653. }
  3654. //*************************************************************
  3655. //
  3656. // ImpersonateUser()
  3657. //
  3658. // Purpose: Impersonates the specified user
  3659. //
  3660. // Parameters: hToken - user to impersonate
  3661. //
  3662. // Return: hToken if successful
  3663. // FALSE if an error occurs
  3664. //
  3665. //*************************************************************
  3666. BOOL ImpersonateUser (HANDLE hNewUser, HANDLE *hOldUser)
  3667. {
  3668. DWORD dwErr;
  3669. if (!OpenThreadToken (GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_READ, TRUE, hOldUser))
  3670. {
  3671. *hOldUser = NULL;
  3672. dwErr = GetLastError();
  3673. if (dwErr != ERROR_NO_TOKEN)
  3674. {
  3675. DebugMsg((DM_VERBOSE, TEXT("ImpersonateUser: Failed to open thread token with %d."), dwErr));
  3676. return FALSE;
  3677. }
  3678. }
  3679. if (!ImpersonateLoggedOnUser(hNewUser))
  3680. {
  3681. if ( *hOldUser )
  3682. {
  3683. CloseHandle( *hOldUser );
  3684. *hOldUser = NULL;
  3685. }
  3686. DebugMsg((DM_VERBOSE, TEXT("ImpersonateUser: Failed to impersonate user with %d."), GetLastError()));
  3687. return FALSE;
  3688. }
  3689. return TRUE;
  3690. }
  3691. //*************************************************************
  3692. //
  3693. // RevertToUser()
  3694. //
  3695. // Purpose: Revert back to original user
  3696. //
  3697. // Parameters: hUser - original user token
  3698. //
  3699. // Return: TRUE if successful
  3700. // FALSE if an error occurs
  3701. //
  3702. //*************************************************************
  3703. BOOL RevertToUser (HANDLE *hUser)
  3704. {
  3705. BOOL bRetVal;
  3706. bRetVal = SetThreadToken(NULL, *hUser);
  3707. if (!bRetVal)
  3708. {
  3709. DebugMsg((DM_WARNING, TEXT("RevertToUser: SetThreadToken failed with %d."), GetLastError()));
  3710. }
  3711. if (*hUser)
  3712. {
  3713. CloseHandle (*hUser);
  3714. *hUser = NULL;
  3715. }
  3716. return bRetVal;
  3717. }
  3718. //*************************************************************
  3719. //
  3720. // GuidToString, StringToGuid, ValidateGuid, CompareGuid()
  3721. //
  3722. // Purpose: Guid utility functions
  3723. //
  3724. //*************************************************************
  3725. //
  3726. // Length in chars of string form of guid {44cffeec-79d0-11d2-a89d-00c04fbbcfa2}
  3727. //
  3728. #define GUID_LENGTH 38
  3729. void GuidToStringEx( const GUID *pGuid, TCHAR * szValue, UINT cchValue)
  3730. {
  3731. StringCchPrintf( szValue, cchValue,
  3732. TEXT("{%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}"),
  3733. pGuid->Data1,
  3734. pGuid->Data2,
  3735. pGuid->Data3,
  3736. pGuid->Data4[0], pGuid->Data4[1],
  3737. pGuid->Data4[2], pGuid->Data4[3],
  3738. pGuid->Data4[4], pGuid->Data4[5],
  3739. pGuid->Data4[6], pGuid->Data4[7] );
  3740. }
  3741. void GuidToString( const GUID *pGuid, TCHAR * szValue)
  3742. {
  3743. //
  3744. // Assume the buffer is big enough (39 chars) to hold the string,
  3745. // try to use GuidToStringEx() instead!!!
  3746. //
  3747. StringCchPrintf( szValue, GUID_LENGTH + 1,
  3748. TEXT("{%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}"),
  3749. pGuid->Data1,
  3750. pGuid->Data2,
  3751. pGuid->Data3,
  3752. pGuid->Data4[0], pGuid->Data4[1],
  3753. pGuid->Data4[2], pGuid->Data4[3],
  3754. pGuid->Data4[4], pGuid->Data4[5],
  3755. pGuid->Data4[6], pGuid->Data4[7] );
  3756. }
  3757. void StringToGuid( TCHAR * szValue, GUID * pGuid )
  3758. {
  3759. WCHAR wc;
  3760. INT i;
  3761. //
  3762. // If the first character is a '{', skip it
  3763. //
  3764. if ( szValue[0] == L'{' )
  3765. szValue++;
  3766. //
  3767. // Since szValue may be used again, no permanent modification to
  3768. // it is be made.
  3769. //
  3770. wc = szValue[8];
  3771. szValue[8] = 0;
  3772. pGuid->Data1 = wcstoul( &szValue[0], 0, 16 );
  3773. szValue[8] = wc;
  3774. wc = szValue[13];
  3775. szValue[13] = 0;
  3776. pGuid->Data2 = (USHORT)wcstoul( &szValue[9], 0, 16 );
  3777. szValue[13] = wc;
  3778. wc = szValue[18];
  3779. szValue[18] = 0;
  3780. pGuid->Data3 = (USHORT)wcstoul( &szValue[14], 0, 16 );
  3781. szValue[18] = wc;
  3782. wc = szValue[21];
  3783. szValue[21] = 0;
  3784. pGuid->Data4[0] = (unsigned char)wcstoul( &szValue[19], 0, 16 );
  3785. szValue[21] = wc;
  3786. wc = szValue[23];
  3787. szValue[23] = 0;
  3788. pGuid->Data4[1] = (unsigned char)wcstoul( &szValue[21], 0, 16 );
  3789. szValue[23] = wc;
  3790. for ( i = 0; i < 6; i++ )
  3791. {
  3792. wc = szValue[26+i*2];
  3793. szValue[26+i*2] = 0;
  3794. pGuid->Data4[2+i] = (unsigned char)wcstoul( &szValue[24+i*2], 0, 16 );
  3795. szValue[26+i*2] = wc;
  3796. }
  3797. }
  3798. BOOL ValidateGuidPrefix( TCHAR *szValue)
  3799. // This function is different from ValidateGuid in only one case. szValue is checked to be prefixed with Guid.
  3800. {
  3801. //
  3802. // Check if szValue is of form {19e02dd6-79d2-11d2-a89d-00c04fbbcfa2}
  3803. //
  3804. // Fixing bug 570352
  3805. DWORD i;
  3806. if ( lstrlen(szValue) < GUID_LENGTH ) // this function is different from ValidateGuid here.
  3807. return FALSE;
  3808. if ( szValue[0] != TEXT('{')
  3809. || szValue[9] != TEXT('-')
  3810. || szValue[14] != TEXT('-')
  3811. || szValue[19] != TEXT('-')
  3812. || szValue[24] != TEXT('-')
  3813. || szValue[37] != TEXT('}') )
  3814. {
  3815. return FALSE;
  3816. }
  3817. for ( i = 0; (i <= 37); i++ )
  3818. {
  3819. if ( i != 0 && i != 9 && i != 14 && i != 19 && i != 24 && i != 37 )
  3820. {
  3821. // it shld be between 0-9 or A-F or a-f
  3822. if (szValue[i] >= L'0' && szValue[i] <= L'9')
  3823. continue;
  3824. if (szValue[i] >= L'a' && szValue[i] <= L'f')
  3825. continue;
  3826. if (szValue[i] >= L'A' && szValue[i] <= L'F')
  3827. continue;
  3828. return FALSE; // It is here because of invalid character in the string
  3829. }
  3830. }
  3831. return TRUE;
  3832. }
  3833. BOOL ValidateGuid( TCHAR *szValue )
  3834. {
  3835. //
  3836. // Check if szValue is of form {19e02dd6-79d2-11d2-a89d-00c04fbbcfa2}
  3837. //
  3838. // Fixing bug 570352
  3839. DWORD i;
  3840. if ( lstrlen(szValue) != GUID_LENGTH )
  3841. return FALSE;
  3842. return ValidateGuidPrefix(szValue);
  3843. }
  3844. INT CompareGuid( GUID * pGuid1, GUID * pGuid2 )
  3845. {
  3846. INT i;
  3847. if ( pGuid1->Data1 != pGuid2->Data1 )
  3848. return ( pGuid1->Data1 < pGuid2->Data1 ? -1 : 1 );
  3849. if ( pGuid1->Data2 != pGuid2->Data2 )
  3850. return ( pGuid1->Data2 < pGuid2->Data2 ? -1 : 1 );
  3851. if ( pGuid1->Data3 != pGuid2->Data3 )
  3852. return ( pGuid1->Data3 < pGuid2->Data3 ? -1 : 1 );
  3853. for ( i = 0; i < 8; i++ )
  3854. {
  3855. if ( pGuid1->Data4[i] != pGuid2->Data4[i] )
  3856. return ( pGuid1->Data4[i] < pGuid2->Data4[i] ? -1 : 1 );
  3857. }
  3858. return 0;
  3859. }
  3860. //*************************************************************
  3861. //
  3862. // RegCleanUpValue()
  3863. //
  3864. // Purpose: Removes the target value and if no more values / keys
  3865. // are present, removes the key. This function then
  3866. // works up the parent tree removing keys if they are
  3867. // also empty. If any parent key has a value / subkey,
  3868. // it won't be removed.
  3869. //
  3870. // Parameters: hKeyRoot - Root key
  3871. // lpSubKey - SubKey
  3872. // lpValueName - Value to remove
  3873. //
  3874. //
  3875. // Return: TRUE if successful
  3876. // FALSE if an error occurs
  3877. //
  3878. //*************************************************************
  3879. BOOL RegCleanUpValue (HKEY hKeyRoot, LPTSTR lpSubKey, LPTSTR lpValueName)
  3880. {
  3881. TCHAR szDelKey[2 * MAX_PATH];
  3882. LPTSTR lpEnd;
  3883. DWORD dwKeys, dwValues;
  3884. LONG lResult;
  3885. HKEY hKey;
  3886. //
  3887. // Make a copy of the subkey so we can write to it.
  3888. //
  3889. if (FAILED(StringCchCopy (szDelKey, ARRAYSIZE(szDelKey), lpSubKey)))
  3890. {
  3891. DebugMsg((DM_WARNING, TEXT("RegCleanUpKey: Failed to copy value name.")));
  3892. return FALSE;
  3893. }
  3894. //
  3895. // First delete the value
  3896. //
  3897. lResult = RegOpenKeyEx (hKeyRoot, szDelKey, 0, KEY_WRITE, &hKey);
  3898. if (lResult == ERROR_SUCCESS)
  3899. {
  3900. lResult = RegDeleteValue (hKey, lpValueName);
  3901. RegCloseKey (hKey);
  3902. if (lResult != ERROR_SUCCESS)
  3903. {
  3904. if (lResult != ERROR_FILE_NOT_FOUND)
  3905. {
  3906. DebugMsg((DM_WARNING, TEXT("RegCleanUpKey: Failed to delete value <%s> with %d."), lpValueName, lResult));
  3907. return FALSE;
  3908. }
  3909. }
  3910. }
  3911. //
  3912. // Now loop through each of the parents. If the parent is empty
  3913. // eg: no values and no other subkeys, then remove the parent and
  3914. // keep working up.
  3915. //
  3916. lpEnd = szDelKey + lstrlen(szDelKey) - 1;
  3917. while (lpEnd >= szDelKey)
  3918. {
  3919. //
  3920. // Find the parent key
  3921. //
  3922. while ((lpEnd > szDelKey) && (*lpEnd != TEXT('\\')))
  3923. lpEnd--;
  3924. //
  3925. // Open the key
  3926. //
  3927. lResult = RegOpenKeyEx (hKeyRoot, szDelKey, 0, KEY_READ, &hKey);
  3928. if (lResult != ERROR_SUCCESS)
  3929. {
  3930. if (lResult == ERROR_FILE_NOT_FOUND)
  3931. {
  3932. goto LoopAgain;
  3933. }
  3934. else
  3935. {
  3936. DebugMsg((DM_WARNING, TEXT("RegCleanUpKey: Failed to open key <%s> with %d."), szDelKey, lResult));
  3937. return FALSE;
  3938. }
  3939. }
  3940. //
  3941. // See if there any any values / keys
  3942. //
  3943. lResult = RegQueryInfoKey (hKey, NULL, NULL, NULL, &dwKeys, NULL, NULL,
  3944. &dwValues, NULL, NULL, NULL, NULL);
  3945. RegCloseKey (hKey);
  3946. if (lResult != ERROR_SUCCESS)
  3947. {
  3948. DebugMsg((DM_WARNING, TEXT("RegCleanUpKey: Failed to query key <%s> with %d."), szDelKey, lResult));
  3949. return FALSE;
  3950. }
  3951. //
  3952. // Exit now if this key has values or keys
  3953. //
  3954. if ((dwKeys != 0) || (dwValues != 0))
  3955. {
  3956. return TRUE;
  3957. }
  3958. RegDeleteKey (hKeyRoot, szDelKey);
  3959. LoopAgain:
  3960. //
  3961. // If we are at the beginning of the subkey, we can leave now.
  3962. //
  3963. if (lpEnd == szDelKey)
  3964. {
  3965. return TRUE;
  3966. }
  3967. //
  3968. // There is a parent key. Remove the slash and loop again.
  3969. //
  3970. if (*lpEnd == TEXT('\\'))
  3971. {
  3972. *lpEnd = TEXT('\0');
  3973. }
  3974. }
  3975. return TRUE;
  3976. }
  3977. //*************************************************************
  3978. //
  3979. // InitializePingCritSec()
  3980. //
  3981. // Purpose: Initializes a CRITICAL_SECTION for pinging
  3982. // computers
  3983. //
  3984. // Parameters: none
  3985. //
  3986. //
  3987. // Return: ERROR_SUCCESS if successful
  3988. // An error if it fails.
  3989. //
  3990. //*************************************************************
  3991. DWORD InitializePingCritSec( void )
  3992. {
  3993. CRITICAL_SECTION *pCritSec = NULL;
  3994. DWORD result = ERROR_SUCCESS;
  3995. BOOL fInitialized = FALSE;
  3996. CRITICAL_SECTION *pInitial;
  3997. // If the critical section already exists, return.
  3998. if (g_PingCritSec != NULL)
  3999. return ERROR_SUCCESS;
  4000. // Allocate memory for the critial section.
  4001. pCritSec = (CRITICAL_SECTION *) LocalAlloc( LMEM_FIXED,
  4002. sizeof(CRITICAL_SECTION) );
  4003. if (pCritSec == NULL)
  4004. {
  4005. result = ERROR_NOT_ENOUGH_MEMORY;
  4006. goto Exit;
  4007. }
  4008. // Initialize the critical section. Using the flag 0x80000000
  4009. // preallocates the event so that EnterCriticalSection can only
  4010. // throw timeout exceptions.
  4011. __try
  4012. {
  4013. if (!InitializeCriticalSectionAndSpinCount( pCritSec, 0x80000000 ))
  4014. result = GetLastError();
  4015. else
  4016. fInitialized = TRUE;
  4017. }
  4018. __except( EXCEPTION_EXECUTE_HANDLER )
  4019. {
  4020. result = GetExceptionCode();
  4021. }
  4022. if (result != ERROR_SUCCESS)
  4023. goto Exit;
  4024. // Save the critical section.
  4025. pInitial = (CRITICAL_SECTION *) InterlockedCompareExchangePointer(
  4026. (void **) &g_PingCritSec, (void *) pCritSec, NULL );
  4027. // If the InterlockedCompareExchange succeeded, don't free the
  4028. // critical section just allocated.
  4029. if (pInitial == NULL)
  4030. pCritSec = NULL;
  4031. Exit:
  4032. if (pCritSec != NULL)
  4033. {
  4034. if (fInitialized)
  4035. DeleteCriticalSection( pCritSec );
  4036. LocalFree( pCritSec );
  4037. }
  4038. return result;
  4039. }
  4040. //*************************************************************
  4041. //
  4042. // ClosePingCritSec()
  4043. //
  4044. // Purpose: Closes the CRITICAL_SECTION for pinging
  4045. // computers
  4046. //
  4047. // Parameters: none
  4048. //
  4049. //
  4050. // Return: none
  4051. //
  4052. //*************************************************************
  4053. void ClosePingCritSec( void )
  4054. {
  4055. if (g_PingCritSec != NULL)
  4056. {
  4057. DeleteCriticalSection( g_PingCritSec );
  4058. LocalFree( g_PingCritSec );
  4059. g_PingCritSec = NULL;
  4060. }
  4061. }
  4062. #define PING_BUFFER_SIZE 2048
  4063. //*************************************************************
  4064. //
  4065. // PingComputerEx()
  4066. //
  4067. // Purpose: Pings the specified computer to determine
  4068. // what the data transfer rate is
  4069. //
  4070. // Parameters: ipaddr - IP address of computer
  4071. // ulSpeed - Data transfer rate (see Notes below)
  4072. // pdwAdapterIndex - index of the adapter that services
  4073. // calls to the DC
  4074. //
  4075. // Return: ERROR_SUCCESS if successful
  4076. // Error code otherwise
  4077. //
  4078. // Notes: For fast connections (eg: LAN), it isn't possible
  4079. // to get accurate transfer rates since the response
  4080. // time from the computer is less than 10ms. In
  4081. // this case, the function returns ERROR_SUCCESS and
  4082. // ulSpeed is set to maximum speed of network interface.
  4083. //
  4084. // This function will ping the computer 3 times with
  4085. // no data and 3 times with 4K of data. If the response
  4086. // time from any of the pings is less than 10ms, the
  4087. // function assumes this is a fast link (eg: LAN) and
  4088. // returns with ulSpeed set to maximum speed of network
  4089. // interface.
  4090. //
  4091. // If the pings respond in a time greater than 10ms,
  4092. // the time of the second ping is subtracted from
  4093. // the time of the first ping to determine the amount
  4094. // of time it takes to move just the data. This
  4095. // is repeated for the 3 sets of pings. Then the
  4096. // average time is computed from the 3 sets of pings.
  4097. // From the average time, the kbps is calculated.
  4098. //
  4099. //*************************************************************
  4100. DWORD WINAPI
  4101. PingComputerEx( ULONG ipaddr, ULONG *ulSpeed, DWORD* pdwAdapterIndex )
  4102. {
  4103. DWORD dwResult = ERROR_SUCCESS;
  4104. DWORD i;
  4105. DWORD dwReplySize;
  4106. HANDLE icmpHandle = NULL;
  4107. LPBYTE lpReply = NULL;
  4108. PICMP_ECHO_REPLY pReplyStruct;
  4109. ULONG ulFirst;
  4110. ULONG ulSecond;
  4111. ULONG ulDiff;
  4112. ULONG ulTotal = 0;
  4113. ULONG ulCount = 0;
  4114. PICMP_API pIcmp;
  4115. HRSRC hJPEG;
  4116. MIB_IFROW mibIfRow;
  4117. PIPHLPAPI_API pIpHlpApi;
  4118. HGLOBAL hGlobalJPEG;
  4119. dwResult = InitializePingCritSec();
  4120. if (dwResult != ERROR_SUCCESS)
  4121. return dwResult;
  4122. EnterCriticalSection( g_PingCritSec );
  4123. //
  4124. // Load iphlpapi.dll
  4125. //
  4126. pIpHlpApi = LoadIpHlpApi();
  4127. if ( !pIpHlpApi )
  4128. {
  4129. dwResult = GetLastError();
  4130. DebugMsg((DM_WARNING, TEXT("PingComputer: iphlpapi.dll is not loaded, %d"), dwResult ));
  4131. goto Exit;
  4132. }
  4133. //
  4134. // Load the icmp api
  4135. //
  4136. dwResult = LoadIcmp( &pIcmp );
  4137. if (dwResult != ERROR_SUCCESS) {
  4138. DebugMsg((DM_WARNING, TEXT("PingComputer: Failed to load icmp api.")));
  4139. goto Exit;
  4140. }
  4141. //
  4142. // Load the slow link data if appropriate
  4143. //
  4144. if (!g_lpTestData) {
  4145. hJPEG = FindResource (g_hDllInstance, MAKEINTRESOURCE(IDB_SLOWLINK), TEXT("JPEG"));
  4146. if (hJPEG) {
  4147. hGlobalJPEG = LoadResource (g_hDllInstance, hJPEG);
  4148. if (hGlobalJPEG) {
  4149. g_lpTestData = LockResource (hGlobalJPEG);
  4150. }
  4151. }
  4152. }
  4153. if (!g_lpTestData) {
  4154. dwResult = GetLastError();
  4155. DebugMsg((DM_WARNING, TEXT("PingComputer: Failed to load slow link data.")));
  4156. goto Exit;
  4157. }
  4158. //
  4159. // Set default speed
  4160. //
  4161. ZeroMemory( &mibIfRow, sizeof( mibIfRow ) );
  4162. //
  4163. // get the interface index corr. to the interface that services traffic to ipaddr ( DC )
  4164. //
  4165. dwResult = pIpHlpApi->pfnGetBestInterface( ipaddr, &mibIfRow.dwIndex );
  4166. if ( dwResult != NO_ERROR )
  4167. {
  4168. DebugMsg((DM_WARNING, TEXT("PingComputer: GetBestInterface with %d"), dwResult));
  4169. }
  4170. else
  4171. {
  4172. //
  4173. // get information about the interface. We use the dwSpeed as the default speed of the link.
  4174. //
  4175. dwResult = pIpHlpApi->pfnGetIfEntry( &mibIfRow );
  4176. if ( dwResult != NO_ERROR )
  4177. {
  4178. DebugMsg((DM_WARNING, TEXT("PingComputer: GetIfEntry with %d"), dwResult));
  4179. }
  4180. else
  4181. {
  4182. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Adapter speed %d bps"), mibIfRow.dwSpeed));
  4183. }
  4184. }
  4185. if ( pdwAdapterIndex )
  4186. {
  4187. *pdwAdapterIndex = mibIfRow.dwIndex;
  4188. }
  4189. *ulSpeed = mibIfRow.dwSpeed/1024; // In kbps
  4190. //
  4191. // Allocate space for the receive buffer
  4192. //
  4193. dwReplySize = PING_BUFFER_SIZE + sizeof(ICMP_ECHO_REPLY) + 8;
  4194. lpReply = LocalAlloc (LPTR, dwReplySize);
  4195. if (!lpReply) {
  4196. dwResult = GetLastError();
  4197. DebugMsg((DM_WARNING, TEXT("PingComputer: Failed to allocate memory with %d"), dwResult));
  4198. goto Exit;
  4199. }
  4200. //
  4201. // Open the Icmp handle
  4202. //
  4203. icmpHandle = pIcmp->pfnIcmpCreateFile();
  4204. if (icmpHandle == INVALID_HANDLE_VALUE) {
  4205. dwResult = GetLastError();
  4206. DebugMsg((DM_WARNING, TEXT("PingComputer: Failed to open handle with %d"), dwResult));
  4207. goto Exit;
  4208. }
  4209. //
  4210. // Loop through the 3 sets of pings
  4211. //
  4212. for (i = 0; i < 3; i++) {
  4213. //
  4214. // Initialize the return value
  4215. //
  4216. dwResult = ERROR_SUCCESS;
  4217. //
  4218. // First ping with no data
  4219. //
  4220. if (pIcmp->pfnIcmpSendEcho (icmpHandle, ipaddr, g_lpTestData, 0, NULL, lpReply,
  4221. dwReplySize, 5000) == 0) {
  4222. dwResult = GetLastError();
  4223. if (dwResult == IP_DEST_HOST_UNREACHABLE) {
  4224. dwResult = ERROR_BAD_NETPATH;
  4225. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Target computer 0x%x not found"), (DWORD)ipaddr));
  4226. goto Exit;
  4227. } else {
  4228. DebugMsg((DM_VERBOSE, TEXT("PingComputer: First send 0x%x failed with %d"), (DWORD)ipaddr, dwResult));
  4229. continue;
  4230. }
  4231. }
  4232. pReplyStruct = (PICMP_ECHO_REPLY) lpReply;
  4233. if (pReplyStruct->Status != IP_SUCCESS) {
  4234. if (pReplyStruct->Status == IP_DEST_HOST_UNREACHABLE) {
  4235. dwResult = ERROR_BAD_NETPATH;
  4236. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Target computer not found")));
  4237. goto Exit;
  4238. } else {
  4239. DebugMsg((DM_VERBOSE, TEXT("PingComputer: First send has a reply buffer failure of %d"), pReplyStruct->Status));
  4240. continue;
  4241. }
  4242. }
  4243. ulFirst = pReplyStruct->RoundTripTime;
  4244. DebugMsg((DM_VERBOSE, TEXT("PingComputer: First time: %d"), ulFirst));
  4245. if (ulFirst < 10) {
  4246. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Fast link. Exiting.")));
  4247. goto Exit;
  4248. }
  4249. //
  4250. // Second ping with dwSize data
  4251. //
  4252. if (pIcmp->pfnIcmpSendEcho (icmpHandle, ipaddr, g_lpTestData, PING_BUFFER_SIZE, NULL, lpReply,
  4253. dwReplySize, 5000) == 0) {
  4254. dwResult = GetLastError();
  4255. if (dwResult == IP_DEST_HOST_UNREACHABLE) {
  4256. dwResult = ERROR_BAD_NETPATH;
  4257. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Target computer not found")));
  4258. goto Exit;
  4259. } else {
  4260. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Second send failed with %d"), dwResult));
  4261. continue;
  4262. }
  4263. }
  4264. pReplyStruct = (PICMP_ECHO_REPLY) lpReply;
  4265. if (pReplyStruct->Status != IP_SUCCESS) {
  4266. if (pReplyStruct->Status == IP_DEST_HOST_UNREACHABLE) {
  4267. dwResult = ERROR_BAD_NETPATH;
  4268. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Target computer not found")));
  4269. goto Exit;
  4270. } else {
  4271. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Second send has a reply buffer failure of %d"), pReplyStruct->Status));
  4272. continue;
  4273. }
  4274. }
  4275. ulSecond = pReplyStruct->RoundTripTime;
  4276. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Second time: %d"), ulSecond));
  4277. if (ulSecond < 10) {
  4278. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Fast link. Exiting.")));
  4279. goto Exit;
  4280. }
  4281. //
  4282. // Study the results
  4283. //
  4284. if (ulFirst > ulSecond) {
  4285. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Second time less than first time.")));
  4286. } else if (ulFirst == ulSecond) {
  4287. DebugMsg((DM_VERBOSE, TEXT("PingComputer: First and second times match.")));
  4288. } else {
  4289. ulTotal += (ulSecond - ulFirst);
  4290. ulCount++;
  4291. }
  4292. }
  4293. //
  4294. // Study the results
  4295. //
  4296. if (ulTotal > 0) {
  4297. ulTotal = (ulTotal / ulCount);
  4298. *ulSpeed = ((((PING_BUFFER_SIZE * 2) * 1000) / ulTotal) * 8) / 1024;
  4299. DebugMsg((DM_VERBOSE, TEXT("PingComputer: Transfer rate: %d Kbps Loop count: %d"),*ulSpeed, ulCount));
  4300. dwResult = ERROR_SUCCESS;
  4301. } else {
  4302. DebugMsg((DM_VERBOSE, TEXT("PingComputer: No data available")));
  4303. dwResult = ERROR_UNEXP_NET_ERR;
  4304. }
  4305. Exit:
  4306. if (icmpHandle) {
  4307. pIcmp->pfnIcmpCloseHandle (icmpHandle);
  4308. }
  4309. if (lpReply) {
  4310. LocalFree (lpReply);
  4311. }
  4312. LeaveCriticalSection( g_PingCritSec );
  4313. return dwResult;
  4314. }
  4315. DWORD WINAPI PingComputer (ULONG ipaddr, ULONG *ulSpeed)
  4316. {
  4317. return PingComputerEx( ipaddr, ulSpeed, 0 );
  4318. }
  4319. //*************************************************************
  4320. //
  4321. // GetDomainControllerInfo()
  4322. //
  4323. // Purpose: Wrapper for DsGetDcName().
  4324. //
  4325. // Parameters:
  4326. // pNetAPI32 - Net API entry points
  4327. // szDomainName - domain name
  4328. // ulFlags - flags, see DsGetDcName()
  4329. // ppInfo - see DOMAIN_CONTROLLER_INFO
  4330. // pfSlow - slow link?
  4331. //
  4332. // Comments:
  4333. //
  4334. //
  4335. // Return: NO_ERROR if successful
  4336. // Error code if an error occurs
  4337. //
  4338. //*************************************************************
  4339. DWORD GetDomainControllerInfo( PNETAPI32_API pNetAPI32,
  4340. LPTSTR szDomainName,
  4341. ULONG ulFlags,
  4342. HKEY hKeyRoot,
  4343. PDOMAIN_CONTROLLER_INFO* ppInfo,
  4344. BOOL* pfSlow,
  4345. DWORD* pdwAdapterIndex )
  4346. {
  4347. DWORD dwResult;
  4348. //
  4349. // get DC info.
  4350. //
  4351. dwResult = pNetAPI32->pfnDsGetDcName( 0,
  4352. szDomainName,
  4353. 0,
  4354. 0,
  4355. ulFlags,
  4356. ppInfo);
  4357. if ( dwResult == ERROR_SUCCESS ) {
  4358. //
  4359. // Check for slow link
  4360. //
  4361. dwResult = IsSlowLink( hKeyRoot,
  4362. (*ppInfo)->DomainControllerAddress,
  4363. pfSlow,
  4364. pdwAdapterIndex );
  4365. if ( dwResult != ERROR_SUCCESS ){
  4366. //
  4367. // force rediscovery to obtain a live DC
  4368. //
  4369. dwResult = pNetAPI32->pfnDsGetDcName( 0,
  4370. szDomainName,
  4371. 0,
  4372. 0,
  4373. ulFlags | DS_FORCE_REDISCOVERY,
  4374. ppInfo);
  4375. if ( dwResult == ERROR_SUCCESS ) {
  4376. //
  4377. // re-evaluate link speed
  4378. //
  4379. dwResult = IsSlowLink( hKeyRoot,
  4380. (*ppInfo)->DomainControllerAddress,
  4381. pfSlow,
  4382. pdwAdapterIndex );
  4383. }
  4384. }
  4385. }
  4386. return dwResult;
  4387. }
  4388. //***************************************************************************
  4389. //
  4390. // GetUserGuid
  4391. //
  4392. // Purpose: Allocates and returns a string representing the user guid of
  4393. // the current user.
  4394. //
  4395. // Parameters: hToken - user's token
  4396. //
  4397. // Return: szUserString is successful
  4398. // NULL if an error occurs
  4399. //
  4400. // Comments: Note, this only works for domain accounts. Local accounts
  4401. // do not have GUIDs.
  4402. //
  4403. // History: Date Author Comment
  4404. // 11/14/95 ushaji created
  4405. //***************************************************************************
  4406. LPTSTR GetUserGuid(HANDLE hToken)
  4407. {
  4408. LPTSTR szUserGuid=NULL;
  4409. HANDLE hOldToken;
  4410. PSID psidSystem = NULL, psidUser=NULL;
  4411. SID_IDENTIFIER_AUTHORITY authNT = SECURITY_NT_AUTHORITY;
  4412. BOOL bImpersonated = FALSE;
  4413. //
  4414. // Get the system sid
  4415. //
  4416. if (!AllocateAndInitializeSid(&authNT, 1, SECURITY_LOCAL_SYSTEM_RID,
  4417. 0, 0, 0, 0, 0, 0, 0, &psidSystem)) {
  4418. DebugMsg((DM_WARNING, TEXT("GetUserGuid: Failed to initialize system sid. Error = %d"), GetLastError()));
  4419. goto Exit;
  4420. }
  4421. psidUser = GetUserSid(hToken);
  4422. if (!psidUser) {
  4423. DebugMsg((DM_WARNING, TEXT("GetUserGuid: Couldn't get user sid, Error = %d"), GetLastError()));
  4424. goto Exit;
  4425. }
  4426. if (EqualSid(psidUser, psidSystem)) {
  4427. DebugMsg((DM_VERBOSE, TEXT("GetUserGuid: user sid matches local system, returning NULL"), GetLastError()));
  4428. goto Exit;
  4429. }
  4430. //
  4431. // impersonate the user and the get the user guid for this user.
  4432. //
  4433. if (!ImpersonateUser(hToken, &hOldToken)) {
  4434. DebugMsg((DM_WARNING, TEXT("GetUserGuid: Failed to impersonate user with %d."), GetLastError()));
  4435. goto Exit;
  4436. }
  4437. bImpersonated = TRUE;
  4438. szUserGuid = MyGetUserNameEx(NameUniqueId);
  4439. if (!szUserGuid) {
  4440. if ((GetLastError() != ERROR_CANT_ACCESS_DOMAIN_INFO) &&
  4441. (GetLastError() != ERROR_NONE_MAPPED)) {
  4442. DebugMsg((DM_WARNING, TEXT("GetUserGuid: Failed to get user guid with %d."), GetLastError()));
  4443. }
  4444. }
  4445. Exit:
  4446. if (bImpersonated)
  4447. RevertToUser(&hOldToken);
  4448. if (psidUser) {
  4449. DeleteUserSid (psidUser);
  4450. }
  4451. if (psidSystem)
  4452. FreeSid(psidSystem);
  4453. return szUserGuid;
  4454. }
  4455. //***************************************************************************
  4456. //
  4457. // GetOldSidString
  4458. //
  4459. // Purpose: Allocates and returns a string representing the old sid of
  4460. // the current user by looking at the profile guid in the registry.
  4461. //
  4462. // Parameters: hToken - user's token
  4463. // lpKeyName - key to read
  4464. //
  4465. // Return: SidString is successful
  4466. // NULL if an error occurs
  4467. //
  4468. // Comments:
  4469. //
  4470. // History: Date Author Comment
  4471. // 11/14/95 ushaji created
  4472. //***************************************************************************
  4473. LPTSTR GetOldSidString(HANDLE hToken, LPTSTR lpKeyName)
  4474. {
  4475. TCHAR szBuffer[MAX_PATH], *lpEnd;
  4476. LPTSTR szUserGuid;
  4477. DWORD dwSize=0, dwType;
  4478. TCHAR *lpSidString = NULL;
  4479. HKEY hKey = NULL;
  4480. LONG lResult;
  4481. DWORD dwErr;
  4482. HRESULT hr;
  4483. DWORD cchEnd;
  4484. //
  4485. // get the prev last error
  4486. //
  4487. dwErr = GetLastError();
  4488. szUserGuid = GetUserGuid(hToken);
  4489. if (!szUserGuid) {
  4490. dwErr = GetLastError();
  4491. goto Exit;
  4492. }
  4493. //
  4494. // Open the guid->sid mapping
  4495. //
  4496. hr = StringCchCopy(szBuffer, ARRAYSIZE(szBuffer), lpKeyName);
  4497. if (FAILED(hr))
  4498. {
  4499. dwErr = HRESULT_CODE(hr);
  4500. goto Exit;
  4501. }
  4502. lpEnd = CheckSlashEx (szBuffer, ARRAYSIZE(szBuffer), &cchEnd);
  4503. if (!lpEnd)
  4504. {
  4505. dwErr = ERROR_INSUFFICIENT_BUFFER;
  4506. goto Exit;
  4507. }
  4508. hr = StringCchCopy(lpEnd, cchEnd, szUserGuid);
  4509. if (FAILED(hr))
  4510. {
  4511. dwErr = HRESULT_CODE(hr);
  4512. goto Exit;
  4513. }
  4514. lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szBuffer, 0, KEY_READ, &hKey);
  4515. if (lResult != ERROR_SUCCESS) {
  4516. dwErr = lResult;
  4517. DebugMsg((DM_VERBOSE, TEXT("GetOldSidString: Failed to open profile profile guid key with error %d"), lResult));
  4518. goto Exit;
  4519. }
  4520. //
  4521. // Query for the Sid String, (size first)
  4522. //
  4523. lResult = RegQueryValueEx (hKey,
  4524. PROFILE_SID_STRING,
  4525. NULL,
  4526. &dwType,
  4527. NULL,
  4528. &dwSize);
  4529. if (lResult != ERROR_SUCCESS) {
  4530. dwErr = lResult;
  4531. DebugMsg((DM_WARNING, TEXT("GetOldSidString: Failed to query size of SidString with error %d"), lResult));
  4532. goto Exit;
  4533. }
  4534. lpSidString = LocalAlloc(LPTR, dwSize);
  4535. if (!lpSidString) {
  4536. dwErr = lResult;
  4537. DebugMsg((DM_WARNING, TEXT("GetOldSidString: Failed to allocate memory for SidString"), lResult));
  4538. goto Exit;
  4539. }
  4540. lResult = RegQueryValueEx (hKey,
  4541. PROFILE_SID_STRING,
  4542. NULL,
  4543. &dwType,
  4544. (LPBYTE)lpSidString,
  4545. &dwSize);
  4546. if (lResult != ERROR_SUCCESS) {
  4547. dwErr = lResult;
  4548. DebugMsg((DM_WARNING, TEXT("GetOldSidString: Failed to query SidString with error %d"), lResult));
  4549. LocalFree(lpSidString);
  4550. lpSidString = NULL;
  4551. goto Exit;
  4552. }
  4553. Exit:
  4554. if (szUserGuid)
  4555. LocalFree(szUserGuid);
  4556. if (hKey)
  4557. RegCloseKey(hKey);
  4558. SetLastError(dwErr);
  4559. return lpSidString;
  4560. }
  4561. //***************************************************************************
  4562. //
  4563. // SetOldSidString
  4564. //
  4565. // Purpose: Sets the old sid string corresp. to a user for the next domain
  4566. // migration
  4567. //
  4568. // Parameters: hToken - user's token
  4569. // lpSidString - user's sid (in a string form)
  4570. // lpKeyName - key to store
  4571. //
  4572. // Return: SidString is successful
  4573. // NULL if an error occurs
  4574. //
  4575. // Comments:
  4576. //
  4577. // History: Date Author Comment
  4578. // 11/14/95 ushaji created
  4579. //***************************************************************************
  4580. BOOL SetOldSidString(HANDLE hToken, LPTSTR lpSidString, LPTSTR lpKeyName)
  4581. {
  4582. TCHAR szBuffer[MAX_PATH+1], *lpEnd;
  4583. DWORD dwSize=0, dwDisp = 0;
  4584. HKEY hKey = NULL;
  4585. BOOL bRetVal = TRUE;
  4586. LONG lResult = 0;
  4587. LPTSTR szUserGuid;
  4588. DWORD dwErr;
  4589. HRESULT hr;
  4590. DWORD cchEnd;
  4591. //
  4592. // get the prev last error
  4593. //
  4594. dwErr = GetLastError();
  4595. szUserGuid = GetUserGuid(hToken);
  4596. if (!szUserGuid) {
  4597. dwErr = GetLastError();
  4598. goto Exit;
  4599. }
  4600. //
  4601. // Open the guid->sid mapping
  4602. //
  4603. hr = StringCchCopy(szBuffer, ARRAYSIZE(szBuffer), lpKeyName);
  4604. if (FAILED(hr))
  4605. {
  4606. dwErr = HRESULT_CODE(hr);
  4607. goto Exit;
  4608. }
  4609. lpEnd = CheckSlashEx (szBuffer, ARRAYSIZE(szBuffer), &cchEnd);
  4610. if (!lpEnd)
  4611. {
  4612. dwErr = ERROR_INSUFFICIENT_BUFFER;
  4613. goto Exit;
  4614. }
  4615. hr = StringCchCopy(lpEnd, cchEnd, szUserGuid);
  4616. if (FAILED(hr))
  4617. {
  4618. dwErr = HRESULT_CODE(hr);
  4619. goto Exit;
  4620. }
  4621. lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE, szBuffer, 0, 0, 0, KEY_READ | KEY_WRITE, NULL,
  4622. &hKey, &dwDisp);
  4623. if (lResult != ERROR_SUCCESS) {
  4624. dwErr = GetLastError();
  4625. DebugMsg((DM_VERBOSE, TEXT("GetOldSidString: Failed to open profile profile guid key with error %d"), lResult));
  4626. goto Exit;
  4627. }
  4628. //
  4629. // Set the Sid String
  4630. //
  4631. lResult = RegSetValueEx (hKey,
  4632. PROFILE_SID_STRING,
  4633. 0,
  4634. REG_SZ,
  4635. (LPBYTE) lpSidString,
  4636. (lstrlen(lpSidString) + 1) * sizeof(TCHAR));
  4637. if (lResult != ERROR_SUCCESS) {
  4638. dwErr = GetLastError();
  4639. DebugMsg((DM_WARNING, TEXT("SetOldSidString: Failed to set SidString with error %d"), lResult));
  4640. goto Exit;
  4641. }
  4642. bRetVal = TRUE;
  4643. Exit:
  4644. if (szUserGuid)
  4645. LocalFree(szUserGuid);
  4646. if (hKey)
  4647. RegCloseKey(hKey);
  4648. SetLastError(dwErr);
  4649. return bRetVal;
  4650. }
  4651. //***************************************************************************
  4652. //
  4653. // GetErrString
  4654. //
  4655. // Purpose: Calls FormatMessage to Get the error string corresp. to a error
  4656. // code
  4657. //
  4658. //
  4659. // Parameters: dwErr - Error Code
  4660. // szErr - Buffer to return the error string (MAX_PATH)
  4661. // is assumed.!!!
  4662. //
  4663. // Return: szErr
  4664. //
  4665. // History: Date Author Comment
  4666. // 4/28/99 ushaji created
  4667. //***************************************************************************
  4668. LPTSTR GetErrString(DWORD dwErr, LPTSTR szErr)
  4669. {
  4670. szErr[0] = TEXT('\0');
  4671. FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK,
  4672. NULL, dwErr,
  4673. MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
  4674. szErr, MAX_PATH, NULL);
  4675. return szErr;
  4676. }
  4677. //*************************************************************
  4678. //
  4679. // GetMachineToken()
  4680. //
  4681. // Purpose: Gets the machine token
  4682. //
  4683. // Parameters: none
  4684. //
  4685. // Note: This must be called from the LocalSystem context
  4686. //
  4687. // Return: TRUE if successful
  4688. // FALSE if an error occurs
  4689. //
  4690. //*************************************************************
  4691. HANDLE GetMachineToken (void)
  4692. {
  4693. SECURITY_STATUS SecStatus;
  4694. SECURITY_STATUS InitStatus;
  4695. SECURITY_STATUS AcceptStatus;
  4696. HANDLE hToken = NULL;
  4697. PSecPkgInfo PackageInfo = NULL;
  4698. BOOLEAN AcquiredServerCred = FALSE;
  4699. BOOLEAN AcquiredClientCred = FALSE;
  4700. BOOLEAN AcquiredClientContext = FALSE;
  4701. BOOLEAN AcquiredServerContext = FALSE;
  4702. CredHandle CredentialHandle2;
  4703. CredHandle ServerCredHandleStorage;
  4704. CtxtHandle ClientContextHandle;
  4705. CtxtHandle ServerContextHandle;
  4706. PCtxtHandle pServerContextHandle = NULL;
  4707. PCtxtHandle pClientContextHandle = NULL;
  4708. PCredHandle ServerCredHandle = NULL;
  4709. TimeStamp Lifetime;
  4710. DWORD dwSize;
  4711. TCHAR szComputerName[MAX_PATH];
  4712. SecBufferDesc NegotiateDesc;
  4713. SecBuffer NegotiateBuffer;
  4714. SecBufferDesc ChallengeDesc;
  4715. PSecBufferDesc pChallengeDesc = NULL;
  4716. SecBuffer ChallengeBuffer;
  4717. LPBYTE pvBuffer = NULL;
  4718. LPBYTE pvBuffer2 = NULL;
  4719. ULONG ContextAttributes;
  4720. PSECUR32_API pSecur32;
  4721. HRESULT hr;
  4722. //
  4723. // Load pSecur32->dll
  4724. //
  4725. if ( !( pSecur32 = LoadSecur32 () ) ) {
  4726. DebugMsg((DM_WARNING, TEXT("GetMachineToken: Failed to load Secur32.")));
  4727. SecStatus = GetLastError();
  4728. return NULL;
  4729. }
  4730. //
  4731. // Get the computer name
  4732. //
  4733. dwSize = ARRAYSIZE(szComputerName);
  4734. if (!GetComputerName (szComputerName, &dwSize)) {
  4735. DebugMsg((DM_WARNING, TEXT("GetMachineToken: Failed to get the computer name with %d"), GetLastError()));
  4736. SecStatus = GetLastError();
  4737. goto Exit;
  4738. }
  4739. hr = StringCchCat(szComputerName, ARRAYSIZE(szComputerName), TEXT("$"));
  4740. if (FAILED(hr))
  4741. {
  4742. DebugMsg((DM_WARNING, TEXT("GetMachineToken: Failed to append a '$'. ")));
  4743. SecStatus = ERROR_INSUFFICIENT_BUFFER;
  4744. goto Exit;
  4745. }
  4746. //
  4747. // Get the kerberos security package
  4748. //
  4749. SecStatus = pSecur32->pfnQuerySecurityPackageInfo( L"kerberos", &PackageInfo );
  4750. if (SecStatus != STATUS_SUCCESS) {
  4751. DebugMsg((DM_WARNING, TEXT("GetMachineToken: QuerySecurityPackageInfo failed with 0x%x"),
  4752. SecStatus));
  4753. goto Exit;
  4754. }
  4755. //
  4756. // Acquire a credential handle for the server side
  4757. //
  4758. ServerCredHandle = &ServerCredHandleStorage;
  4759. SecStatus = pSecur32->pfnAcquireCredentialsHandle(
  4760. NULL, // New principal
  4761. L"kerberos", // Package Name
  4762. SECPKG_CRED_INBOUND,
  4763. NULL,
  4764. NULL,
  4765. NULL,
  4766. NULL,
  4767. ServerCredHandle,
  4768. &Lifetime );
  4769. if (SecStatus != STATUS_SUCCESS) {
  4770. DebugMsg((DM_WARNING, TEXT("GetMachineToken: AcquireCredentialsHandle for server failed with 0x%x"),
  4771. SecStatus));
  4772. goto Exit;
  4773. }
  4774. AcquiredServerCred = TRUE;
  4775. //
  4776. // Acquire a credential handle for the client side
  4777. //
  4778. SecStatus = pSecur32->pfnAcquireCredentialsHandle(
  4779. NULL, // New principal
  4780. L"kerberos", // Package Name
  4781. SECPKG_CRED_OUTBOUND,
  4782. NULL,
  4783. NULL,
  4784. NULL,
  4785. NULL,
  4786. &CredentialHandle2,
  4787. &Lifetime );
  4788. if (SecStatus != STATUS_SUCCESS) {
  4789. DebugMsg((DM_WARNING, TEXT("GetMachineToken: AcquireCredentialsHandle for client failed with 0x%x"),
  4790. SecStatus));
  4791. goto Exit;
  4792. }
  4793. AcquiredClientCred = TRUE;
  4794. //
  4795. // Allocate buffers
  4796. //
  4797. pvBuffer = LocalAlloc( 0, PackageInfo->cbMaxToken);
  4798. if (!pvBuffer) {
  4799. DebugMsg((DM_WARNING, TEXT("GetMachineToken: LocalAlloc failed with %d"),
  4800. GetLastError()));
  4801. SecStatus = GetLastError();
  4802. goto Exit;
  4803. }
  4804. pvBuffer2 = LocalAlloc( 0, PackageInfo->cbMaxToken);
  4805. if (!pvBuffer2) {
  4806. DebugMsg((DM_WARNING, TEXT("GetMachineToken: LocalAlloc failed with %d"),
  4807. GetLastError()));
  4808. SecStatus = GetLastError();
  4809. goto Exit;
  4810. }
  4811. while (TRUE) {
  4812. //
  4813. // Initialize the security context (client side)
  4814. //
  4815. NegotiateDesc.ulVersion = 0;
  4816. NegotiateDesc.cBuffers = 1;
  4817. NegotiateDesc.pBuffers = &NegotiateBuffer;
  4818. NegotiateBuffer.cbBuffer = PackageInfo->cbMaxToken;
  4819. NegotiateBuffer.BufferType = SECBUFFER_TOKEN;
  4820. NegotiateBuffer.pvBuffer = pvBuffer;
  4821. InitStatus = pSecur32->pfnInitializeSecurityContext(
  4822. &CredentialHandle2,
  4823. pClientContextHandle,
  4824. szComputerName,
  4825. 0,
  4826. 0, // Reserved 1
  4827. SECURITY_NATIVE_DREP,
  4828. pChallengeDesc,
  4829. 0, // Reserved 2
  4830. &ClientContextHandle,
  4831. &NegotiateDesc,
  4832. &ContextAttributes,
  4833. &Lifetime );
  4834. if ((InitStatus != SEC_E_OK) && (InitStatus != SEC_I_CONTINUE_NEEDED)) {
  4835. DebugMsg((DM_WARNING, TEXT("GetMachineToken: InitializeSecurityContext failed with 0x%x"),
  4836. InitStatus));
  4837. SecStatus = InitStatus;
  4838. goto Exit;
  4839. }
  4840. pClientContextHandle = &ClientContextHandle;
  4841. AcquiredClientContext = TRUE;
  4842. //
  4843. // Accept the server side context
  4844. //
  4845. NegotiateBuffer.BufferType |= SECBUFFER_READONLY;
  4846. ChallengeDesc.ulVersion = 0;
  4847. ChallengeDesc.cBuffers = 1;
  4848. ChallengeDesc.pBuffers = &ChallengeBuffer;
  4849. ChallengeBuffer.cbBuffer = PackageInfo->cbMaxToken;
  4850. ChallengeBuffer.BufferType = SECBUFFER_TOKEN;
  4851. ChallengeBuffer.pvBuffer = pvBuffer2;
  4852. AcceptStatus = pSecur32->pfnAcceptSecurityContext(
  4853. ServerCredHandle,
  4854. pServerContextHandle,
  4855. &NegotiateDesc,
  4856. 0,
  4857. SECURITY_NATIVE_DREP,
  4858. &ServerContextHandle,
  4859. &ChallengeDesc,
  4860. &ContextAttributes,
  4861. &Lifetime );
  4862. if ((AcceptStatus != SEC_E_OK) && (AcceptStatus != SEC_I_CONTINUE_NEEDED)) {
  4863. DebugMsg((DM_WARNING, TEXT("GetMachineToken: AcceptSecurityContext failed with 0x%x"),
  4864. AcceptStatus));
  4865. SecStatus = AcceptStatus;
  4866. goto Exit;
  4867. }
  4868. AcquiredServerContext = TRUE;
  4869. if (AcceptStatus == SEC_E_OK) {
  4870. break;
  4871. }
  4872. pChallengeDesc = &ChallengeDesc;
  4873. pServerContextHandle = &ServerContextHandle;
  4874. DebugMsg((DM_VERBOSE, TEXT("GetMachineToken: Looping for authentication again.")));
  4875. }
  4876. //
  4877. // Get the server token
  4878. //
  4879. SecStatus = pSecur32->pfnQuerySecurityContextToken(&ServerContextHandle, &hToken);
  4880. if ( SecStatus != STATUS_SUCCESS ) {
  4881. DebugMsg((DM_WARNING, TEXT("GetMachineToken: QuerySecurityContextToken failed with 0x%x"),
  4882. SecStatus));
  4883. goto Exit;
  4884. }
  4885. Exit:
  4886. if (AcquiredClientContext) {
  4887. pSecur32->pfnDeleteSecurityContext( &ClientContextHandle );
  4888. }
  4889. if (AcquiredServerContext) {
  4890. pSecur32->pfnDeleteSecurityContext( &ServerContextHandle );
  4891. }
  4892. if (pvBuffer2) {
  4893. LocalFree (pvBuffer2);
  4894. }
  4895. if (pvBuffer) {
  4896. LocalFree (pvBuffer);
  4897. }
  4898. if (AcquiredClientCred) {
  4899. pSecur32->pfnFreeCredentialsHandle(&CredentialHandle2);
  4900. }
  4901. if (AcquiredServerCred)
  4902. {
  4903. pSecur32->pfnFreeCredentialsHandle(ServerCredHandle);
  4904. }
  4905. if (PackageInfo) {
  4906. pSecur32->pfnFreeContextBuffer(PackageInfo);
  4907. }
  4908. if (!hToken) {
  4909. SetLastError(SecStatus);
  4910. }
  4911. return hToken;
  4912. }
  4913. //*************************************************************
  4914. //
  4915. // IsNullGUID()
  4916. //
  4917. // Purpose: Determines if the passed in GUID is all zeros
  4918. //
  4919. // Parameters: pguid GUID to compare
  4920. //
  4921. // Return: TRUE if the GUID is all zeros
  4922. // FALSE if not
  4923. //
  4924. //*************************************************************
  4925. BOOL IsNullGUID (GUID *pguid)
  4926. {
  4927. return ( (pguid->Data1 == 0) &&
  4928. (pguid->Data2 == 0) &&
  4929. (pguid->Data3 == 0) &&
  4930. (pguid->Data4[0] == 0) &&
  4931. (pguid->Data4[1] == 0) &&
  4932. (pguid->Data4[2] == 0) &&
  4933. (pguid->Data4[3] == 0) &&
  4934. (pguid->Data4[4] == 0) &&
  4935. (pguid->Data4[5] == 0) &&
  4936. (pguid->Data4[6] == 0) &&
  4937. (pguid->Data4[7] == 0) );
  4938. }
  4939. //*************************************************************
  4940. //
  4941. // GetMachineRole()
  4942. //
  4943. // Purpose: Determines the role of the machine
  4944. // server vs workstation vs standalone
  4945. //
  4946. // Parameters: piRole - Receives the simple role number
  4947. //
  4948. // Return: TRUE if successful
  4949. // FALSE if an error occurs
  4950. //
  4951. //*************************************************************
  4952. BOOL GetMachineRole (LPINT piRole)
  4953. {
  4954. PDSROLE_PRIMARY_DOMAIN_INFO_BASIC pBasic;
  4955. DWORD dwResult;
  4956. PNETAPI32_API pNetAPI32;
  4957. //
  4958. // Check the cached value first
  4959. //
  4960. if (g_iMachineRole != -1) {
  4961. *piRole = g_iMachineRole;
  4962. return TRUE;
  4963. }
  4964. //
  4965. // Load netapi32
  4966. //
  4967. pNetAPI32 = LoadNetAPI32();
  4968. if (!pNetAPI32) {
  4969. DebugMsg((DM_WARNING, TEXT("GetMachineRole: Failed to load netapi32 with %d."),
  4970. GetLastError()));
  4971. return FALSE;
  4972. }
  4973. //
  4974. // Ask for the role of this machine
  4975. //
  4976. dwResult = pNetAPI32->pfnDsRoleGetPrimaryDomainInformation(NULL, DsRolePrimaryDomainInfoBasic,
  4977. (PBYTE *)&pBasic);
  4978. if (dwResult != ERROR_SUCCESS) {
  4979. DebugMsg((DM_WARNING, TEXT("GetMachineRole: DsRoleGetPrimaryDomainInformation failed with %d."),
  4980. dwResult));
  4981. return FALSE;
  4982. }
  4983. //
  4984. // Convert the role into a simple machine role
  4985. //
  4986. if ((pBasic->MachineRole == DsRole_RoleStandaloneWorkstation) ||
  4987. (pBasic->MachineRole == DsRole_RoleStandaloneServer)) {
  4988. *piRole = 0; // standalone machine not in a DS domain
  4989. } else {
  4990. if (pBasic->Flags & DSROLE_PRIMARY_DOMAIN_GUID_PRESENT) {
  4991. if (!IsNullGUID(&pBasic->DomainGuid)) {
  4992. *piRole = 2; // machine is a member of a domain with DS support
  4993. if ((pBasic->MachineRole == DsRole_RoleBackupDomainController) ||
  4994. (pBasic->MachineRole == DsRole_RolePrimaryDomainController)) {
  4995. *piRole = 3; // machine is a domain controller
  4996. }
  4997. } else {
  4998. *piRole = 1; // machine is a member of a NT4 domain
  4999. }
  5000. } else {
  5001. *piRole = 1; // machine is a member of a domain without DS support
  5002. }
  5003. }
  5004. pNetAPI32->pfnDsRoleFreeMemory (pBasic);
  5005. //
  5006. // Save this value in the cache for future use
  5007. //
  5008. g_iMachineRole = *piRole;
  5009. return TRUE;
  5010. }
  5011. //*************************************************************
  5012. //
  5013. // IsUNCPath()
  5014. //
  5015. // Purpose: Is the given path a UNC path
  5016. //
  5017. // Parameters: lpPath - Path to check
  5018. //
  5019. // Return: TRUE if the path is UNC
  5020. // FALSE if not
  5021. //
  5022. // Comments:
  5023. //
  5024. // History: Date Author Comment
  5025. // 6/21/96 ericflo Ported
  5026. //
  5027. //*************************************************************
  5028. BOOL IsUNCPath(LPCTSTR lpPath)
  5029. {
  5030. if ((!lpPath) || (!lpPath[0]) && (!lpPath[1]))
  5031. return FALSE;
  5032. if (lpPath[0] == TEXT('\\') && lpPath[1] == TEXT('\\')) {
  5033. return(TRUE);
  5034. }
  5035. return(FALSE);
  5036. }
  5037. //*************************************************************
  5038. //
  5039. // MakePathUNC()
  5040. //
  5041. // Purpose: Makes the given path UNC s.t. it can be accessed from a remote machine..
  5042. // if the path contains %systemroot% expanded then it substitutes
  5043. // \\machname\admin$ otherwise \\machname\<driveletter>$
  5044. //
  5045. // Parameters: lpPath - Input Path (needs to be absolute)
  5046. // szComputerName - Name of the computer on which this is the local path
  5047. //
  5048. // Return: Path if it was fone successfully
  5049. // NULL if not
  5050. //
  5051. // Comments:
  5052. //
  5053. //
  5054. //*************************************************************
  5055. LPTSTR MakePathUNC(LPTSTR pwszFile, LPTSTR szComputerName)
  5056. {
  5057. LPTSTR szUNCPath=NULL;
  5058. TCHAR szSysRoot[MAX_PATH];
  5059. DWORD dwSysLen;
  5060. LPTSTR lpEnd = NULL;
  5061. DWORD cchUNCPath;
  5062. DWORD cchEnd;
  5063. HRESULT hr;
  5064. DebugMsg((DM_VERBOSE, TEXT("MakePathUNC: Entering with <%s>"),
  5065. pwszFile ? pwszFile : TEXT("NULL")));
  5066. cchUNCPath = lstrlen(pwszFile)+lstrlen(szComputerName)+3+lstrlen(TEXT("admin$"))+1;
  5067. szUNCPath = LocalAlloc(LPTR, sizeof(TCHAR)*cchUNCPath);
  5068. if (!szUNCPath)
  5069. return NULL;
  5070. if (!pwszFile || !*pwszFile) {
  5071. DebugMsg((DM_VERBOSE, TEXT("MakePathUNC: lpFile is NULL, setting lpResult to a null string")));
  5072. *szUNCPath = TEXT('\0');
  5073. return szUNCPath;
  5074. }
  5075. if (IsUNCPath(pwszFile)) {
  5076. StringCchCopy(szUNCPath, cchUNCPath, pwszFile);
  5077. return szUNCPath;
  5078. }
  5079. StringCchCopy(szUNCPath, cchUNCPath, TEXT("\\\\"));
  5080. StringCchCat(szUNCPath, cchUNCPath, szComputerName);
  5081. //
  5082. // If the first part of lpFile is the expanded value of %SystemRoot%
  5083. //
  5084. if (FAILED(SafeExpandEnvironmentStrings (TEXT("%SystemRoot%"), szSysRoot, MAX_PATH))) {
  5085. DebugMsg((DM_WARNING, TEXT("MakePathUNC: ExpandEnvironmentString failed with error %d, setting szSysRoot to %systemroot% "), GetLastError()));
  5086. LocalFree(szUNCPath);
  5087. return NULL;
  5088. }
  5089. dwSysLen = lstrlen(szSysRoot);
  5090. lpEnd = CheckSlashEx(szUNCPath, cchUNCPath, &cchEnd);
  5091. //
  5092. // if the prefix is the same as expanded systemroot then..
  5093. //
  5094. if (((DWORD)lstrlen(pwszFile) > dwSysLen) &&
  5095. (CompareString (LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
  5096. szSysRoot, dwSysLen,
  5097. pwszFile, dwSysLen) == CSTR_EQUAL)) {
  5098. StringCchCat(szUNCPath, cchUNCPath, TEXT("admin$"));
  5099. StringCchCat(szUNCPath, cchUNCPath, pwszFile+dwSysLen);
  5100. }
  5101. else {
  5102. if (pwszFile[1] != TEXT(':')) {
  5103. DebugMsg((DM_WARNING, TEXT("MakePathUNC: Input path %s is not an absolute path"), pwszFile));
  5104. StringCchCat(szUNCPath, cchUNCPath, pwszFile);
  5105. return szUNCPath;
  5106. }
  5107. if (cchEnd > 2)
  5108. {
  5109. lpEnd[0] = pwszFile[0];
  5110. lpEnd[1] = TEXT('$');
  5111. lpEnd[2] = TEXT('\0');
  5112. StringCchCat(szUNCPath, cchUNCPath, pwszFile+2);
  5113. }
  5114. }
  5115. DebugMsg((DM_VERBOSE, TEXT("MakePathUNC: Returning a UNCPath of %s"), szUNCPath));
  5116. return szUNCPath;
  5117. }
  5118. //*************************************************************
  5119. //
  5120. // SupportLongFileName()
  5121. //
  5122. // Purpose: Prepends lpDir with \\?\UNC\ or \\?\ depending on
  5123. // whether lpDir is a UNC path or local path. Before
  5124. // prepending this function converts relative path or
  5125. // absolute path started with a slash to corresponding
  5126. // absolute path containing drive letter.
  5127. //
  5128. // Parameters: lpDir - Directory
  5129. // lpWrkDirSize - Size of the returned buffer in unit
  5130. // of TCHAR
  5131. //
  5132. // Return: LPTSTR pointing to prepended dir/file
  5133. // NULL if fail to allocate memory
  5134. //
  5135. // Comments: Prepending with \\?\UNC\ or \\?\ allows all file api's
  5136. // to handle file name > MAX_PATH.
  5137. //
  5138. // History: Date Author Comment
  5139. // 8/8/00 santanuc Created
  5140. //
  5141. //*************************************************************
  5142. LPTSTR SupportLongFileName (LPTSTR lpDir, LPDWORD lpWrkDirSize)
  5143. {
  5144. LPTSTR lpWrkDir = NULL;
  5145. *lpWrkDirSize = lstrlen(lpDir)+2*MAX_PATH;
  5146. lpWrkDir = (LPTSTR)LocalAlloc(LPTR, sizeof(TCHAR)**lpWrkDirSize);
  5147. if (!lpWrkDir) {
  5148. DebugMsg((DM_WARNING, TEXT("EnableLongFileNameDeletion: Failed to Allocate memory. Error = %d"),
  5149. GetLastError()));
  5150. return NULL;
  5151. }
  5152. if ( IsUNCPath(lpDir) ) {
  5153. // lpDir is of the form \\computername\...
  5154. StringCchCopy(lpWrkDir, *lpWrkDirSize, c_szUNCFilePrefix);
  5155. StringCchCat(lpWrkDir, *lpWrkDirSize, lpDir+2);
  5156. }
  5157. else if ( *CharNext(lpDir) == TEXT(':') ) {
  5158. // Local storage specified with drive name
  5159. StringCchCopy(lpWrkDir, *lpWrkDirSize, c_szLocalFilePrefix);
  5160. StringCchCat(lpWrkDir, *lpWrkDirSize, lpDir);
  5161. }
  5162. else if ( *lpDir == TEXT('\\') ) {
  5163. DWORD dwSize;
  5164. // Prepend lpDir with c_szLocalFilePrefix followed by current drive as DeleteFile function requires
  5165. // drive name to delete files from local storage with path name > MAX_PATH
  5166. StringCchCopy(lpWrkDir, *lpWrkDirSize, c_szLocalFilePrefix);
  5167. dwSize = GetCurrentDirectory(*lpWrkDirSize-c_dwLocalFilePrefixLen, lpWrkDir+c_dwLocalFilePrefixLen);
  5168. if (dwSize == 0) {
  5169. DebugMsg((DM_VERBOSE, TEXT("DelNode: GetCurrentDirectory failed with error %d"), GetLastError()));
  5170. // proceed to delete lpDir without long file name deletion feature
  5171. StringCchCopy(lpWrkDir, *lpWrkDirSize, lpDir);
  5172. }
  5173. else {
  5174. if (dwSize > *lpWrkDirSize-c_dwLocalFilePrefixLen) {
  5175. // Extend lpWrkDir to accomodate current directory name with drive
  5176. LocalFree(lpWrkDir);
  5177. *lpWrkDirSize = dwSize+c_dwLocalFilePrefixLen;
  5178. lpWrkDir = (LPTSTR)LocalAlloc(LPTR, sizeof(TCHAR)**lpWrkDirSize);
  5179. if (!lpWrkDir) {
  5180. DebugMsg((DM_WARNING, TEXT("Delnode: Failed to Allocate memory. Error = %d"), GetLastError()));
  5181. return NULL;
  5182. }
  5183. StringCchCopy(lpWrkDir, *lpWrkDirSize, c_szLocalFilePrefix);
  5184. dwSize = GetCurrentDirectory(*lpWrkDirSize-c_dwLocalFilePrefixLen, lpWrkDir+c_dwLocalFilePrefixLen);
  5185. if (dwSize == 0 || dwSize > *lpWrkDirSize-c_dwLocalFilePrefixLen) {
  5186. DebugMsg((DM_VERBOSE, TEXT("DelNode: GetCurrentDirectory 2nd call failed with error %d"), GetLastError()));
  5187. // proceed to delete lpDir without long file name deletion feature
  5188. StringCchCopy(lpWrkDir, *lpWrkDirSize, lpDir);
  5189. }
  5190. else {
  5191. // Copy lpDir after c_szLocalFilePrefix and drive name
  5192. StringCchCopy(lpWrkDir+c_dwLocalFilePrefixLen+2, *lpWrkDirSize-c_dwLocalFilePrefixLen-2, lpDir);
  5193. }
  5194. }
  5195. else {
  5196. // Copy lpDir after c_szLocalFilePrefix and drive name
  5197. StringCchCopy(lpWrkDir+c_dwLocalFilePrefixLen+2, *lpWrkDirSize-c_dwLocalFilePrefixLen-2, lpDir);
  5198. }
  5199. }
  5200. }
  5201. else {
  5202. LPTSTR szFileName;
  5203. DWORD dwSize;
  5204. // Relative path name specified. So Prepend lpDir with c_szLocalFilePrefix followed by the current directory
  5205. StringCchCopy(lpWrkDir, *lpWrkDirSize, c_szLocalFilePrefix);
  5206. dwSize = GetFullPathName(lpDir, *lpWrkDirSize-c_dwLocalFilePrefixLen, lpWrkDir+c_dwLocalFilePrefixLen, &szFileName);
  5207. if ( dwSize == 0 ) {
  5208. DebugMsg((DM_VERBOSE, TEXT("DelNode: GetFullPathName failed with error %d"), GetLastError()));
  5209. // proceed to delete lpDir without long file name deletion feature
  5210. StringCchCopy(lpWrkDir, *lpWrkDirSize, lpDir);
  5211. }
  5212. else {
  5213. if ( dwSize > *lpWrkDirSize-c_dwLocalFilePrefixLen ) {
  5214. // Extend lpWrkDir to accomodate absolute path name
  5215. LocalFree(lpWrkDir);
  5216. *lpWrkDirSize = dwSize+2*MAX_PATH;
  5217. lpWrkDir = (LPTSTR)LocalAlloc(LPTR, sizeof(TCHAR)**lpWrkDirSize);
  5218. if (!lpWrkDir) {
  5219. DebugMsg((DM_WARNING, TEXT("Delnode: Failed to Allocate memory. Error = %d"), GetLastError()));
  5220. return NULL;
  5221. }
  5222. StringCchCopy(lpWrkDir, *lpWrkDirSize, c_szLocalFilePrefix);
  5223. dwSize = GetFullPathName(lpDir, *lpWrkDirSize-c_dwLocalFilePrefixLen, lpWrkDir+c_dwLocalFilePrefixLen, &szFileName);
  5224. if (dwSize == 0 || dwSize > *lpWrkDirSize-c_dwLocalFilePrefixLen) {
  5225. DebugMsg((DM_VERBOSE, TEXT("DelNode: GetFullPathName 2nd call failed with error %d"), GetLastError()));
  5226. // proceed to delete lpDir without long file name deletion feature
  5227. StringCchCopy(lpWrkDir, *lpWrkDirSize, lpDir);
  5228. }
  5229. }
  5230. }
  5231. }
  5232. return lpWrkDir;
  5233. }
  5234. //*************************************************************
  5235. //
  5236. // SecureNestedDir_Recurse()
  5237. //
  5238. // Purpose: Recursive function for securing nested dirs/files
  5239. //
  5240. // Parameters: lpDir - Full Directory Path.
  5241. // dwSize - Allocated size of the working buffer
  5242. // pDirSd - Security descriptor to be applied with dirs
  5243. // pFileSd - Security descriptor to be applied with files
  5244. //
  5245. // Return: TRUE if successful
  5246. // FALSE if an error occurs
  5247. //
  5248. // Comments:
  5249. //
  5250. // History: Date Author Comment
  5251. //
  5252. //
  5253. //*************************************************************
  5254. BOOL SecureNestedDir_Recurse (LPTSTR lpDir, DWORD dwSize, PSECURITY_DESCRIPTOR pDirSd, PSECURITY_DESCRIPTOR pFileSd)
  5255. {
  5256. BOOL bOwn = FALSE, bRetVal = FALSE;
  5257. LPTSTR lpEnd = NULL, lpWrkDir = NULL;
  5258. WIN32_FIND_DATA *pfd = NULL;
  5259. HANDLE hFile;
  5260. DWORD dwWrkDirSize;
  5261. DWORD cchEnd;
  5262. //
  5263. // Verbose output
  5264. //
  5265. DebugMsg((DM_VERBOSE, TEXT("SecureNestedDir_Recurse: Entering, lpDir = <%s>"), lpDir));
  5266. //
  5267. // Each filename or a directory has to be less than MAX_PATH in the worst case.
  5268. // So make sure that we have at least MAX_PATH + 2 (for a slash and '\0'
  5269. // space left in the working buffer case.
  5270. //
  5271. // In the normal case, when we have a path of length ~MAX_PATH it will do only
  5272. // 1 allocation
  5273. //
  5274. if ((DWORD)(lstrlen(lpDir) + MAX_PATH+2) > (dwSize)) {
  5275. dwWrkDirSize = dwSize+2*MAX_PATH;
  5276. lpWrkDir = (LPWSTR)LocalAlloc(LPTR, dwWrkDirSize*sizeof(TCHAR));
  5277. if (!lpWrkDir) {
  5278. DebugMsg((DM_WARNING, TEXT("SecureNestedDir_Recurse: Couldn't allocate memory for working buffer. Error - %d"), GetLastError()));
  5279. goto Exit;
  5280. }
  5281. StringCchCopy(lpWrkDir, dwWrkDirSize, lpDir);
  5282. bOwn = TRUE;
  5283. }
  5284. else {
  5285. lpWrkDir = lpDir;
  5286. dwWrkDirSize = dwSize;
  5287. }
  5288. //
  5289. // Allocate WIN32_FIND_DATA in the heap to save stack space
  5290. //
  5291. pfd = (WIN32_FIND_DATA*) LocalAlloc (LPTR, sizeof(WIN32_FIND_DATA));
  5292. if (!pfd)
  5293. {
  5294. DebugMsg((DM_WARNING, TEXT("SecureNestedDir_Recurse: Couldn't allocate memory for WIN32_FIND_DATA. Error - %d"), GetLastError()));
  5295. goto Exit;
  5296. }
  5297. //
  5298. // Attach a Slash the end if required
  5299. //
  5300. lpEnd = CheckSlashEx(lpWrkDir, dwWrkDirSize, &cchEnd);
  5301. StringCchCopy(lpEnd, cchEnd, c_szStarDotStar);
  5302. //
  5303. // Find the first file
  5304. //
  5305. hFile = FindFirstFile(lpWrkDir, pfd);
  5306. if (hFile == INVALID_HANDLE_VALUE) {
  5307. if ((GetLastError() == ERROR_FILE_NOT_FOUND) || (GetLastError() == ERROR_PATH_NOT_FOUND)) {
  5308. bRetVal = TRUE;
  5309. goto Exit;
  5310. } else {
  5311. DebugMsg((DM_WARNING, TEXT("SecureNestedDir_Recurse: FindFirstFile failed. Error = %d"),
  5312. GetLastError()));
  5313. goto Exit;
  5314. }
  5315. }
  5316. do {
  5317. //
  5318. // Verbose output
  5319. //
  5320. DebugMsg((DM_VERBOSE, TEXT("SecureNestedDir_Recurse: FindFile found: <%s>"), pfd->cFileName));
  5321. //
  5322. // Check for "." and ".."
  5323. //
  5324. if (!lstrcmpi(pfd->cFileName, c_szDot)) {
  5325. continue;
  5326. }
  5327. if (!lstrcmpi(pfd->cFileName, c_szDotDot)) {
  5328. continue;
  5329. }
  5330. StringCchCopy(lpEnd, cchEnd, pfd->cFileName);
  5331. if (pfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  5332. //
  5333. // Check for reparse point, don't recurse into it.
  5334. //
  5335. if (pfd->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  5336. {
  5337. DebugMsg((DM_WARNING, TEXT("SecureNestedDir_Recurse: a reparse point was found: <%s>, will not recurse into it."), lpWrkDir));
  5338. }
  5339. else
  5340. {
  5341. SecureNestedDir_Recurse(lpWrkDir, dwWrkDirSize, pDirSd, pFileSd);
  5342. //
  5343. // ignore errors and go ahead..
  5344. //
  5345. StringCchCopy(lpEnd, cchEnd, pfd->cFileName);
  5346. }
  5347. if (!SetFileSecurity (lpWrkDir, DACL_SECURITY_INFORMATION, pDirSd)) {
  5348. DebugMsg((DM_WARNING, TEXT("SecureNestedDir_Recurse: Failed to secure directory <%s>. Error = %d"),
  5349. lpWrkDir, GetLastError()));
  5350. }
  5351. } else {
  5352. //
  5353. // We found a file. Try to secure it
  5354. //
  5355. if (!SetFileSecurity (lpWrkDir, DACL_SECURITY_INFORMATION, pFileSd)) {
  5356. DebugMsg((DM_WARNING, TEXT("SecureNestedDir_Recurse: Failed to secure file <%s>. Error = %d"),
  5357. pfd->cFileName, GetLastError()));
  5358. }
  5359. }
  5360. //
  5361. // Find the next entry
  5362. //
  5363. } while (FindNextFile(hFile, pfd));
  5364. //
  5365. // Close the search handle
  5366. //
  5367. FindClose(hFile);
  5368. //
  5369. // Success.
  5370. //
  5371. DebugMsg((DM_VERBOSE, TEXT("SecureNestedDir_Recurse: Leaving <%s>"), lpDir));
  5372. bRetVal = TRUE;
  5373. Exit:
  5374. if (pfd)
  5375. LocalFree(pfd);
  5376. if (bOwn)
  5377. LocalFree(lpWrkDir);
  5378. return bRetVal;
  5379. }
  5380. //*************************************************************
  5381. //
  5382. // SecureNestedDir()
  5383. //
  5384. // Purpose: Secure the dir and nested dirs(files) with input
  5385. // SECURITY_DESCRIPTOR.
  5386. //
  5387. // Parameters: lpDir - Directory
  5388. // pDirSd - Security descriptor to be applied with dirs.
  5389. // pFileSd - Security descriptor to be applied with files.
  5390. //
  5391. // Return: TRUE if successful
  5392. // FALSE if an error occurs
  5393. //
  5394. // History: Date Author Comment
  5395. // 8/8/00 santanuc Created
  5396. //
  5397. //*************************************************************
  5398. BOOL SecureNestedDir (LPTSTR lpDir, PSECURITY_DESCRIPTOR pDirSd, PSECURITY_DESCRIPTOR pFileSd)
  5399. {
  5400. LPTSTR lpWrkDir = NULL;
  5401. DWORD dwWrkDirSize;
  5402. BOOL bRetVal = FALSE;
  5403. lpWrkDir = SupportLongFileName(lpDir, &dwWrkDirSize);
  5404. if (!lpWrkDir) {
  5405. DebugMsg((DM_WARNING, TEXT("SecureNestedDir: Failed to Allocate memory. Error = %d"),
  5406. GetLastError()));
  5407. goto Exit;
  5408. }
  5409. if (!SecureNestedDir_Recurse (lpWrkDir, dwWrkDirSize, pDirSd, pFileSd)) {
  5410. DebugMsg((DM_WARNING, TEXT("SecureNestedDir: SecureNestedDir recurse failed with error %d"),
  5411. GetLastError()));
  5412. }
  5413. if (!SetFileSecurity (lpDir, DACL_SECURITY_INFORMATION, pDirSd)) {
  5414. DebugMsg((DM_WARNING, TEXT("SecureNestedDir: SetFileSecurity failed. Error = %d"), GetLastError()));
  5415. goto Exit;
  5416. }
  5417. bRetVal = TRUE;
  5418. DebugMsg((DM_VERBOSE, TEXT("SecureNestedDir: Secure directory <%s> successfully."), lpDir));
  5419. Exit:
  5420. if (lpWrkDir) {
  5421. LocalFree(lpWrkDir);
  5422. }
  5423. return bRetVal;
  5424. }
  5425. //*************************************************************
  5426. //
  5427. // SetEnvironmentVariableInBlock()
  5428. //
  5429. // Purpose: Sets the environment variable in the given block
  5430. //
  5431. // Parameters: pEnv - Environment block
  5432. // lpVariable - Variables
  5433. // lpValue - Value
  5434. // bOverwrite - Overwrite
  5435. //
  5436. //
  5437. // Return: TRUE if successful
  5438. // FALSE if an error occurs
  5439. //
  5440. // Comments:
  5441. //
  5442. // History: Date Author Comment
  5443. // 6/21/96 ericflo Ported
  5444. //
  5445. //*************************************************************
  5446. BOOL SetEnvironmentVariableInBlock(PVOID *pEnv, LPTSTR lpVariable,
  5447. LPTSTR lpValue, BOOL bOverwrite)
  5448. {
  5449. NTSTATUS Status;
  5450. UNICODE_STRING Name, Value;
  5451. DWORD cb;
  5452. LPTSTR szValue = NULL;
  5453. if (!*pEnv || !lpVariable || !*lpVariable) {
  5454. return(FALSE);
  5455. }
  5456. RtlInitUnicodeString(&Name, lpVariable);
  5457. cb = 1025 * sizeof(WCHAR);
  5458. Value.Buffer = LocalAlloc(LPTR, cb);
  5459. if (Value.Buffer) {
  5460. Value.Length = 0;
  5461. Value.MaximumLength = (USHORT)cb;
  5462. Status = RtlQueryEnvironmentVariable_U(*pEnv, &Name, &Value);
  5463. LocalFree(Value.Buffer);
  5464. if ( NT_SUCCESS(Status) && !bOverwrite) {
  5465. return(TRUE);
  5466. }
  5467. }
  5468. szValue = (LPTSTR)LocalAlloc(LPTR, 1024*sizeof(TCHAR));
  5469. if (!szValue) {
  5470. DebugMsg((DM_WARNING, TEXT("SetEnvironmentVariableInBlock: Out of memory")));
  5471. return FALSE;
  5472. }
  5473. if (lpValue && *lpValue) {
  5474. //
  5475. // Special case TEMP and TMP and shorten the path names
  5476. //
  5477. if ( CompareString(LOCALE_INVARIANT, NORM_IGNORECASE, lpVariable, -1, TEXT("TEMP"), -1) == CSTR_EQUAL ||
  5478. CompareString(LOCALE_INVARIANT, NORM_IGNORECASE, lpVariable, -1, TEXT("TMP") , -1) == CSTR_EQUAL ) {
  5479. DWORD dwLength = GetShortPathName (lpValue, szValue, 1024);
  5480. if (!dwLength || dwLength > 1024) {
  5481. StringCchCopy (szValue, 1024, lpValue);
  5482. }
  5483. } else {
  5484. StringCchCopy (szValue, 1024, lpValue);
  5485. }
  5486. RtlInitUnicodeString(&Value, szValue);
  5487. Status = RtlSetEnvironmentVariable(pEnv, &Name, &Value);
  5488. }
  5489. else {
  5490. Status = RtlSetEnvironmentVariable(pEnv, &Name, NULL);
  5491. }
  5492. LocalFree(szValue);
  5493. if (NT_SUCCESS(Status)) {
  5494. return(TRUE);
  5495. }
  5496. return(FALSE);
  5497. }
  5498. /***************************************************************************\
  5499. * ExpandUserEvironmentVariable
  5500. *
  5501. *
  5502. * History:
  5503. * 2-28-92 Johannec Created
  5504. *
  5505. \***************************************************************************/
  5506. DWORD
  5507. ExpandUserEnvironmentStrings(
  5508. PVOID pEnv,
  5509. LPCTSTR lpSrc,
  5510. LPTSTR lpDst,
  5511. DWORD nSize
  5512. )
  5513. {
  5514. NTSTATUS Status;
  5515. UNICODE_STRING Source, Destination;
  5516. ULONG Length;
  5517. RtlInitUnicodeString( &Source, lpSrc );
  5518. Destination.Buffer = lpDst;
  5519. Destination.Length = 0;
  5520. Destination.MaximumLength = (USHORT)(nSize*sizeof(WCHAR));
  5521. Length = 0;
  5522. Status = RtlExpandEnvironmentStrings_U( pEnv,
  5523. (PUNICODE_STRING)&Source,
  5524. (PUNICODE_STRING)&Destination,
  5525. &Length
  5526. );
  5527. if (NT_SUCCESS( Status ) || Status == STATUS_BUFFER_TOO_SMALL) {
  5528. return( Length / sizeof(WCHAR) );
  5529. }
  5530. else {
  5531. return( 0 );
  5532. }
  5533. }
  5534. //*************************************************************
  5535. //
  5536. // ConvertToShareName()
  5537. //
  5538. // Purpose: Convert the UNC path of a file\dir to a share
  5539. //
  5540. // Parameters: lpShare : Full UNC path of file\dir
  5541. //
  5542. // Return: None.
  5543. //
  5544. // Comments:
  5545. //
  5546. // History: Date Author Comment
  5547. // 8/21/00 santanuc Created
  5548. //
  5549. //*************************************************************
  5550. LPTSTR ConvertToShareName(LPTSTR lpShare)
  5551. {
  5552. BOOL bShareName = FALSE;
  5553. lpShare += 2; // Skip initial two slashes
  5554. while ((!bShareName || *lpShare != TEXT('\\')) && *lpShare != TEXT('\0')) {
  5555. if (*lpShare == TEXT('\\'))
  5556. bShareName = TRUE;
  5557. lpShare++;
  5558. }
  5559. if (*lpShare == TEXT('\\')) {
  5560. *lpShare = TEXT('\0');
  5561. return lpShare+1;
  5562. }
  5563. return NULL;
  5564. }
  5565. //*************************************************************
  5566. //
  5567. // AbleToBypassCSC()
  5568. //
  5569. // Purpose: Try to bypass CSC using a secret api.
  5570. //
  5571. // Parameters: hTokenUser - User's token
  5572. // lpDir - Roaming profile dir
  5573. // lppCscBypassedPath - Path name with mapped drive (OUT)
  5574. // cpDrive - Mapped drive (OUT)
  5575. //
  5576. // Return: ERROR_SUCCESS if successful
  5577. // Error code if an error occurs
  5578. //
  5579. // Comments: We will always bypass csc for roaming share.
  5580. // There are two reason behind this :
  5581. // o csc mark entire server offline even if only
  5582. // one share goes offline. This is a bad design
  5583. // from csc perspective and they need to fix it
  5584. // o If csc is turned on in the roaming share server
  5585. // then both csc and profile will try to sync files
  5586. // on top of one another and we will be in a inconsistent
  5587. // state
  5588. //
  5589. // History: Date Author Comment
  5590. // 10/29/00 santanuc Created
  5591. //
  5592. //*************************************************************
  5593. DWORD AbleToBypassCSC(HANDLE hTokenUser, LPCTSTR lpDir, LPTSTR *lppCscBypassedPath, TCHAR *cpDrive)
  5594. {
  5595. NETRESOURCE sNR;
  5596. LPTSTR lpShare = NULL;
  5597. BOOL bIsDfsConnect = FALSE, bRetValue = FALSE;
  5598. DWORD dwFlags = 0, dwError;
  5599. HANDLE hOldToken;
  5600. WIN32_FIND_DATA fd;
  5601. HANDLE hResult;
  5602. LPTSTR lpFileName;
  5603. BOOL bImpersonated = FALSE;
  5604. DWORD cchShare;
  5605. DWORD cchCscBypassedPath;
  5606. DebugMsg((DM_VERBOSE, TEXT("AbleToBypassCSC: Try to bypass CSC")));
  5607. if (!lpDir || !IsUNCPath(lpDir) || !lppCscBypassedPath || !cpDrive) {
  5608. return ERROR_INVALID_PARAMETER; // Invalid argument
  5609. }
  5610. // Initialize
  5611. *lppCscBypassedPath = NULL;
  5612. memset(&sNR, 0, sizeof(NETRESOURCE));
  5613. if (!ImpersonateUser(hTokenUser, &hOldToken)) {
  5614. dwError = GetLastError();
  5615. DebugMsg((DM_WARNING, TEXT("AbleToBypassCSC: Failed to impersonate user with %d."), dwError));
  5616. goto Exit;
  5617. }
  5618. bImpersonated = TRUE;
  5619. //
  5620. // Construct the roaming share name
  5621. //
  5622. cchShare = lstrlen(lpDir) + 1;
  5623. lpShare = (LPTSTR)LocalAlloc(LPTR, cchShare * sizeof(TCHAR));
  5624. if (!lpShare) {
  5625. dwError = GetLastError();
  5626. DebugMsg((DM_WARNING, TEXT("AbleToBypassCSC: Failed to allocate memory")));
  5627. goto Exit;
  5628. }
  5629. StringCchCopy(lpShare, cchShare, lpDir);
  5630. lpFileName = ConvertToShareName(lpShare);
  5631. cchCscBypassedPath = lstrlen(lpDir)+1;
  5632. *lppCscBypassedPath = (LPTSTR)LocalAlloc(LPTR, cchCscBypassedPath * sizeof(TCHAR));
  5633. if (!*lppCscBypassedPath) {
  5634. dwError = GetLastError();
  5635. DebugMsg((DM_WARNING, TEXT("AbleToBypassCSC: Failed to allocate memory")));
  5636. goto Exit;
  5637. }
  5638. //
  5639. // Initialize NETRESOURCE structure
  5640. //
  5641. sNR.dwType = RESOURCETYPE_DISK;
  5642. sNR.lpRemoteName = lpShare;
  5643. sNR.lpLocalName = (LPTSTR)LocalAlloc(LPTR, 3 * sizeof(TCHAR));
  5644. if (!sNR.lpLocalName) {
  5645. dwError = GetLastError();
  5646. DebugMsg((DM_WARNING, TEXT("AbleToBypassCSC: Failed to allocate memory")));
  5647. goto Exit;
  5648. }
  5649. sNR.lpLocalName[0] = TEXT('E');
  5650. sNR.lpLocalName[1] = TEXT(':');
  5651. sNR.lpLocalName[2] = TEXT('\0');
  5652. do{
  5653. __try {
  5654. dwError = NPAddConnection3ForCSCAgent(NULL, &sNR, NULL, NULL, dwFlags, &bIsDfsConnect);
  5655. DebugMsg((DM_VERBOSE, TEXT("AbleToBypassCSC: tried NPAddConnection3ForCSCAgent. Error %d"), dwError));
  5656. }
  5657. __except(EXCEPTION_EXECUTE_HANDLER) {
  5658. dwError = GetLastError();
  5659. DebugMsg((DM_WARNING, TEXT("AbleToBypassCSC: Took exception in NPAddConnection3ForCSCAgent. Error %d"), dwError));
  5660. }
  5661. if (dwError == WN_SUCCESS || dwError == WN_CONNECTED_OTHER_PASSWORD ||
  5662. dwError == WN_CONNECTED_OTHER_PASSWORD_DEFAULT){
  5663. dwError = ERROR_SUCCESS;
  5664. break;
  5665. }
  5666. if (sNR.lpLocalName[0]==TEXT('Z')) {
  5667. goto Exit;
  5668. }
  5669. else if ((dwError == WN_BAD_LOCALNAME) || (dwError == WN_ALREADY_CONNECTED)){
  5670. ++sNR.lpLocalName[0];
  5671. continue;
  5672. }
  5673. else{
  5674. if (GetNetworkProvider(&sNR) == ERROR_BAD_PROVIDER) {
  5675. dwError = ERROR_BAD_PROVIDER;
  5676. }
  5677. goto Exit;
  5678. }
  5679. }while (TRUE);
  5680. // Succesfully bypassed CSC. Do not modify dwError in this part.
  5681. bRetValue = TRUE;
  5682. *cpDrive = sNR.lpLocalName[0];
  5683. StringCchCopy(*lppCscBypassedPath, cchCscBypassedPath, sNR.lpLocalName);
  5684. StringCchCat(*lppCscBypassedPath, cchCscBypassedPath, TEXT("\\"));
  5685. if (lpFileName)
  5686. {
  5687. StringCchCat(*lppCscBypassedPath, cchCscBypassedPath, lpFileName);
  5688. }
  5689. DebugMsg((DM_VERBOSE, TEXT("AbleToBypassCSC: Share %s mapped to drive %c. Returned Path %s"), lpShare, sNR.lpLocalName[0], *lppCscBypassedPath));
  5690. Exit:
  5691. if (lpShare) {
  5692. LocalFree(lpShare);
  5693. }
  5694. if (!bRetValue && *lppCscBypassedPath) {
  5695. LocalFree(*lppCscBypassedPath);
  5696. *lppCscBypassedPath = NULL;
  5697. }
  5698. if (sNR.lpLocalName) {
  5699. LocalFree(sNR.lpLocalName);
  5700. }
  5701. if (bImpersonated) {
  5702. RevertToUser(&hOldToken);
  5703. }
  5704. return dwError;
  5705. }
  5706. //*************************************************************
  5707. //
  5708. // CancelCSCBypassedConnection()
  5709. //
  5710. // Purpose: Release the mapped drive.
  5711. //
  5712. // Parameters: hTokenUser - User's token
  5713. // cDrive - Drive letter to unmap
  5714. //
  5715. // Return: None
  5716. //
  5717. // Comments: We will always bypass csc for roaming share.
  5718. // There are two reason behind this :
  5719. // o csc mark entire server offline even if only
  5720. // one share goes offline. This is a bad design
  5721. // from csc perspective and they need to fix it
  5722. // o If csc is turned on in the roaming share server
  5723. // then both csc and profile will try to sync files
  5724. // on top of one another and we will be in a inconsistent
  5725. // state
  5726. //
  5727. // History: Date Author Comment
  5728. // 10/29/00 santanuc Created
  5729. //
  5730. //*************************************************************
  5731. void CancelCSCBypassedConnection(HANDLE hTokenUser, TCHAR cDrive)
  5732. {
  5733. DWORD dwError;
  5734. TCHAR szDrive[3];
  5735. HANDLE hOldToken;
  5736. if (!ImpersonateUser(hTokenUser, &hOldToken)) {
  5737. dwError = GetLastError();
  5738. DebugMsg((DM_WARNING, TEXT("CancelCSCBypassedConnection: Failed to impersonate user with %d."), dwError));
  5739. return ;
  5740. }
  5741. szDrive[0] = cDrive;
  5742. szDrive[1] = TEXT(':');
  5743. szDrive[2] = TEXT('\0');
  5744. DebugMsg((DM_VERBOSE, TEXT("CancelCSCBypassedConnection: Cancelling connection of %s"), szDrive));
  5745. __try {
  5746. dwError = NPCancelConnectionForCSCAgent(szDrive, TRUE);
  5747. }
  5748. __except(EXCEPTION_EXECUTE_HANDLER) {
  5749. dwError = GetLastError();
  5750. DebugMsg((DM_WARNING, TEXT("CancelCSCBypassedConnection: Took exception in NPCancelConnectionForCSCAgent. Error %d"), dwError));
  5751. }
  5752. if (dwError != WN_SUCCESS) {
  5753. DebugMsg((DM_WARNING, TEXT("CancelCSCBypassedConnection: Fail to delete connection. Error returned %d"), dwError));
  5754. }
  5755. else {
  5756. DebugMsg((DM_VERBOSE, TEXT("CancelCSCBypassedConnection: Connection deleted.")));
  5757. }
  5758. RevertToUser(&hOldToken);
  5759. }
  5760. //*************************************************************
  5761. //
  5762. // GetNetworkProvider()
  5763. //
  5764. // Purpose: Determine network provider for a share
  5765. //
  5766. // Parameters:
  5767. //
  5768. // Return: DWORD
  5769. //
  5770. // Comments: Returns ERROR_BAD_PROVIDER if provider is other
  5771. // than microsoft SMB provider otherwise return
  5772. // NO_ERROR.
  5773. //
  5774. // History: Date Author Comment
  5775. // 03/08/01 santanuc Created
  5776. //
  5777. //*************************************************************
  5778. DWORD GetNetworkProvider(NETRESOURCE *psNR)
  5779. {
  5780. PFNWNETGETRESOURCEINFORMATION pfnWNetGetResourceInformation;
  5781. HMODULE hWNetLib = NULL;
  5782. NETRESOURCE dNR;
  5783. LPBYTE pbBuffer = (LPBYTE)&dNR;
  5784. DWORD cbBuffer = sizeof(dNR);
  5785. DWORD dwError = NO_ERROR;
  5786. LPTSTR lpSystem = NULL;
  5787. TCHAR szSMBProvider[100];
  5788. HKEY hKeyProvider = NULL;
  5789. DWORD dwSize, dwType;
  5790. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, NETWORK_PROVIDER,
  5791. 0, KEY_READ, &hKeyProvider) != ERROR_SUCCESS) {
  5792. DebugMsg((DM_WARNING, TEXT("GetNetworkProvider: Failed to open network provider key. Error %d"), GetLastError()));
  5793. goto Exit;
  5794. }
  5795. dwSize = ARRAYSIZE(szSMBProvider);
  5796. if (RegQueryValueEx(hKeyProvider,
  5797. PROVIDER_NAME,
  5798. NULL,
  5799. &dwType,
  5800. (LPBYTE) szSMBProvider,
  5801. &dwSize) != ERROR_SUCCESS) {
  5802. DebugMsg((DM_WARNING, TEXT("GetNetworkProvider: Failed to get network provider name. Error %d"), GetLastError()));
  5803. goto Exit;
  5804. }
  5805. if (!(hWNetLib = LoadLibrary(TEXT("mpr.dll")))) {
  5806. DebugMsg((DM_WARNING, TEXT("GetNetworkProvider: LoadLibrary failed with %d"), GetLastError()));
  5807. goto Exit;
  5808. }
  5809. pfnWNetGetResourceInformation = (PFNWNETGETRESOURCEINFORMATION)GetProcAddress(hWNetLib, "WNetGetResourceInformationW");
  5810. if (!pfnWNetGetResourceInformation) {
  5811. DebugMsg((DM_WARNING, TEXT("GetNetworkProvider: GetProcAddress failed with %d"), GetLastError()));
  5812. goto Exit;
  5813. }
  5814. dwError = (*pfnWNetGetResourceInformation)(psNR, pbBuffer, &cbBuffer, &lpSystem);
  5815. if (ERROR_MORE_DATA == dwError) {
  5816. pbBuffer = LocalAlloc(LPTR, cbBuffer);
  5817. if (!pbBuffer) {
  5818. DebugMsg((DM_WARNING, TEXT("AbleToBypassCSC: Failed to impersonate user with %d."), GetLastError()));
  5819. goto Exit;
  5820. }
  5821. dwError = (*pfnWNetGetResourceInformation)(psNR, pbBuffer, &cbBuffer, &lpSystem);
  5822. }
  5823. if (NO_ERROR == dwError) {
  5824. if (lstrcmpi(((NETRESOURCE *)pbBuffer)->lpProvider, szSMBProvider) != 0) {
  5825. dwError = ERROR_BAD_PROVIDER;
  5826. goto Exit;
  5827. }
  5828. }
  5829. dwError = NO_ERROR;
  5830. Exit:
  5831. if (hKeyProvider) {
  5832. RegCloseKey(hKeyProvider);
  5833. }
  5834. if (pbBuffer && (pbBuffer != (LPBYTE)&dNR)) {
  5835. LocalFree(pbBuffer);
  5836. }
  5837. if (hWNetLib) {
  5838. FreeLibrary(hWNetLib);
  5839. }
  5840. return dwError;
  5841. }
  5842. //*************************************************************
  5843. //
  5844. // GetUserNameFromSid()
  5845. //
  5846. // Purpose: Returns the user name in domain\user format
  5847. //
  5848. // Parameters: lpSidString - User's sid string
  5849. //
  5850. // Return: LPTSTR : domain\user name if succeeds
  5851. // lpSidString if fails
  5852. //
  5853. // Comments:
  5854. //
  5855. // History: Date Author Comment
  5856. // 10/31/00 santanuc Created
  5857. //
  5858. //*************************************************************
  5859. LPTSTR GetUserNameFromSid(LPTSTR lpSidString)
  5860. {
  5861. PSID pSidUser = NULL;
  5862. LPTSTR lpRetVal = lpSidString;
  5863. TCHAR szUserName[MAX_PATH], szDomainName[MAX_PATH];
  5864. DWORD dwUserSize = MAX_PATH, dwDomainSize = MAX_PATH;
  5865. SID_NAME_USE TypeOfAccount;
  5866. DWORD cchRetVal;
  5867. //
  5868. // Get the user sid
  5869. //
  5870. if (AllocateAndInitSidFromString(lpSidString, &pSidUser) != STATUS_SUCCESS) {
  5871. DebugMsg((DM_WARNING, TEXT("GetUserNameFromSid: Failed to create user sid.")));
  5872. goto Exit;
  5873. }
  5874. //
  5875. // Get the user and domain name
  5876. //
  5877. if (!LookupAccountSid(NULL, pSidUser, szUserName, &dwUserSize, szDomainName, &dwDomainSize, &TypeOfAccount)) {
  5878. DebugMsg((DM_WARNING, TEXT("GetUserNameFromSid: LookupAccountSid failed with error %d."), GetLastError()));
  5879. goto Exit;
  5880. }
  5881. cchRetVal = lstrlen(szUserName) + lstrlen(szDomainName) + 2;
  5882. lpRetVal = (LPTSTR)LocalAlloc(LPTR, cchRetVal * sizeof(TCHAR));
  5883. if (!lpRetVal) {
  5884. DebugMsg((DM_WARNING, TEXT("GetUserNameFromSid: Memory alloaction failure. error %d"), GetLastError()));
  5885. lpRetVal = lpSidString;
  5886. goto Exit;
  5887. }
  5888. // Construct the return string
  5889. StringCchCopy(lpRetVal, cchRetVal, szDomainName);
  5890. StringCchCat(lpRetVal, cchRetVal, TEXT("\\"));
  5891. StringCchCat(lpRetVal, cchRetVal, szUserName);
  5892. Exit:
  5893. if (pSidUser) {
  5894. LocalFree(pSidUser);
  5895. }
  5896. return lpRetVal;
  5897. }
  5898. //*************************************************************
  5899. //
  5900. // TakeOwnership()
  5901. //
  5902. // Purpose: Take ownership of a file or directory
  5903. //
  5904. // Parameters: lpFileName - file or directory name to work on
  5905. //
  5906. // Return: S_OK for success, else for error
  5907. //
  5908. // Comments:
  5909. //
  5910. // History: Date Author Comment
  5911. // 04/08/2002 mingzhu Created
  5912. //
  5913. //*************************************************************
  5914. HRESULT TakeOwnership(LPTSTR lpFileName)
  5915. {
  5916. HRESULT hr = E_FAIL;
  5917. DWORD dwErr;
  5918. PSID pSID = NULL;
  5919. NTSTATUS status;
  5920. BOOLEAN bTakeOwnerWasEnabled;
  5921. BOOL bTakeOwnerEnabled = FALSE;
  5922. SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_NT_AUTHORITY;
  5923. //
  5924. // Output a debug message
  5925. //
  5926. DebugMsg((DM_VERBOSE, TEXT("TakeOwnership : Taking ownership of %s ..."), lpFileName));
  5927. //
  5928. // Enable SE_TAKE_OWNERSHIP_NAME priviledge
  5929. //
  5930. status = RtlAdjustPrivilege(SE_TAKE_OWNERSHIP_PRIVILEGE, TRUE, FALSE, &bTakeOwnerWasEnabled);
  5931. if(!NT_SUCCESS(status))
  5932. {
  5933. hr = HRESULT_FROM_WIN32(RtlNtStatusToDosError(status));
  5934. DebugMsg((DM_WARNING, TEXT("TakeOwnership: RtlAdjustPrivilege failed, error = %08x"), hr));
  5935. goto Exit;
  5936. }
  5937. //
  5938. // Create a SID for the BUILTIN\Administrators group.
  5939. //
  5940. if (!AllocateAndInitializeSid(&SIDAuth, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
  5941. 0, 0, 0, 0, 0, 0, &pSID))
  5942. {
  5943. hr = HRESULT_FROM_WIN32(GetLastError());
  5944. DebugMsg((DM_WARNING, TEXT("TakeOwnership: AllocateAndInitializeSid failed, error = %08x"), hr));
  5945. goto Exit;
  5946. }
  5947. //
  5948. // Set the owner in the object's security descriptor.
  5949. //
  5950. dwErr = SetNamedSecurityInfo(lpFileName, // name of the object
  5951. SE_FILE_OBJECT, // type of object
  5952. OWNER_SECURITY_INFORMATION, // change only the object's owner
  5953. pSID, // SID of Administrator group
  5954. NULL, NULL, NULL);
  5955. if (dwErr != ERROR_SUCCESS)
  5956. {
  5957. hr = HRESULT_FROM_WIN32(dwErr);
  5958. DebugMsg((DM_WARNING, TEXT("TakeOwnership: SetNamedSecurityInfo failed, error = %08x"), hr));
  5959. goto Exit;
  5960. }
  5961. //
  5962. // We're done!
  5963. //
  5964. DebugMsg((DM_VERBOSE, TEXT("TakeOwnership : Success!")));
  5965. hr = S_OK;
  5966. Exit:
  5967. if (bTakeOwnerEnabled && !bTakeOwnerWasEnabled)
  5968. {
  5969. status = RtlAdjustPrivilege(SE_TAKE_OWNERSHIP_PRIVILEGE, FALSE, FALSE, &bTakeOwnerWasEnabled);
  5970. if(!NT_SUCCESS(status))
  5971. {
  5972. DebugMsg((DM_WARNING, TEXT("TakeOwnership: RtlAdjustPrivilege failed, error = %08x"), status));
  5973. }
  5974. }
  5975. if (pSID)
  5976. {
  5977. FreeSid(pSID);
  5978. }
  5979. return hr;
  5980. }
  5981. //*************************************************************
  5982. //
  5983. // AddAdminAccess()
  5984. //
  5985. // Purpose: Add administrators full access to a file or directory
  5986. //
  5987. // Parameters: lpFileName - file or directory name to work on
  5988. //
  5989. // Return: S_OK for success, else for error
  5990. //
  5991. // Comments:
  5992. //
  5993. // History: Date Author Comment
  5994. // 04/08/2002 mingzhu Created
  5995. //
  5996. //*************************************************************
  5997. HRESULT AddAdminAccess(LPTSTR lpFileName)
  5998. {
  5999. HRESULT hr = E_FAIL;
  6000. DWORD dwErr;
  6001. PSECURITY_DESCRIPTOR pSD = NULL;
  6002. PACL pOldDACL = NULL;
  6003. PACL pNewDACL = NULL;
  6004. EXPLICIT_ACCESS ea;
  6005. //
  6006. // Output a debug message
  6007. //
  6008. DebugMsg((DM_VERBOSE, TEXT("AddAdminAccess : Adding administrators access to %s."), lpFileName));
  6009. //
  6010. // Get the old DACL in the file.
  6011. //
  6012. dwErr = GetNamedSecurityInfo(lpFileName, // name of the object
  6013. SE_FILE_OBJECT, // type of object
  6014. DACL_SECURITY_INFORMATION, // change only the object's owner
  6015. NULL, NULL, &pOldDACL, NULL, // DACL to get
  6016. &pSD); // Security Descriptor of the file
  6017. if (dwErr != ERROR_SUCCESS)
  6018. {
  6019. DebugMsg((DM_WARNING, TEXT("AddAdminAccess : GetNamedSecurityInfo failed with %d"), dwErr));
  6020. hr = HRESULT_FROM_WIN32(dwErr);
  6021. goto Exit;
  6022. }
  6023. //
  6024. // Initialize an EXPLICIT_ACCESS structure for the new ACE (admin full access).
  6025. //
  6026. ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
  6027. ea.grfAccessPermissions = FILE_ALL_ACCESS;
  6028. ea.grfAccessMode = GRANT_ACCESS;
  6029. ea.grfInheritance= SUB_CONTAINERS_AND_OBJECTS_INHERIT;
  6030. ea.Trustee.pMultipleTrustee = NULL;
  6031. ea.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
  6032. ea.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
  6033. ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
  6034. ea.Trustee.ptstrName = TEXT("Administrators");
  6035. //
  6036. // Create a new ACL that merges the new ACE into the existing DACL.
  6037. //
  6038. dwErr = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
  6039. if (ERROR_SUCCESS != dwErr)
  6040. {
  6041. DebugMsg((DM_WARNING, TEXT("AddAdminAccess : SetEntriesInAcl failed. Error = %d"), dwErr));
  6042. hr = HRESULT_FROM_WIN32(dwErr);
  6043. goto Exit;
  6044. }
  6045. //
  6046. // Set the owner in the object's security descriptor.
  6047. //
  6048. dwErr = SetNamedSecurityInfo(lpFileName, // name of the object
  6049. SE_FILE_OBJECT, // type of object
  6050. DACL_SECURITY_INFORMATION, // change only the object's owner
  6051. NULL, NULL, pNewDACL, NULL); // DACL to be set
  6052. if (dwErr != ERROR_SUCCESS)
  6053. {
  6054. DebugMsg((DM_WARNING, TEXT("AddAdminAccess : SetNamedSecurityInfo failed with %d"), dwErr));
  6055. hr = HRESULT_FROM_WIN32(dwErr);
  6056. goto Exit;
  6057. }
  6058. //
  6059. // We're done!
  6060. //
  6061. DebugMsg((DM_VERBOSE, TEXT("AddAdminAccess : Success!")));
  6062. hr = S_OK;
  6063. Exit:
  6064. if(pNewDACL != NULL)
  6065. LocalFree(pNewDACL);
  6066. if(pSD != NULL)
  6067. LocalFree(pSD);
  6068. return hr;
  6069. }
  6070. //*************************************************************
  6071. //
  6072. // Routine Description:
  6073. //
  6074. // This routine determines if we're doing a gui-mode setup.
  6075. //
  6076. // This value is retrieved from the following registry location:
  6077. //
  6078. // \HKLM\System\Setup\
  6079. //
  6080. // SystemSetupInProgress : REG_DWORD : 0x00 (where nonzero
  6081. // means we're doing a gui-setup)
  6082. //
  6083. // Arguments:
  6084. //
  6085. // None.
  6086. //
  6087. // Return Value:
  6088. //
  6089. // TRUE/FALSE
  6090. //
  6091. // Note:
  6092. //
  6093. // This function is courtesy of Andrew Ritz and the Setup API.
  6094. // It's copied over from base\pnp\setupapi\dll.c.
  6095. //
  6096. //***************************************************************
  6097. BOOL IsGuiSetupInProgress()
  6098. {
  6099. HKEY hKey;
  6100. DWORD Err, DataType, DataSize = sizeof(DWORD);
  6101. DWORD Value;
  6102. if((Err = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  6103. TEXT("System\\Setup"),
  6104. 0,
  6105. KEY_READ,
  6106. &hKey)) == ERROR_SUCCESS) {
  6107. //
  6108. // Attempt to read the the "DriverCachePath" value.
  6109. //
  6110. Err = RegQueryValueEx(
  6111. hKey,
  6112. TEXT("SystemSetupInProgress"),
  6113. NULL,
  6114. &DataType,
  6115. (LPBYTE)&Value,
  6116. &DataSize);
  6117. RegCloseKey(hKey);
  6118. }
  6119. if(Err == NO_ERROR) {
  6120. if(Value) {
  6121. return(TRUE);
  6122. }
  6123. }
  6124. return(FALSE);
  6125. }
  6126. //*************************************************************
  6127. //
  6128. // Description:
  6129. //
  6130. // This function will setup a new key under the ProfileList\{sid}
  6131. // entry and give the specified user write permittion to it in order
  6132. // to change his/her preference.
  6133. //
  6134. // Arguments:
  6135. //
  6136. // lpSidString - String format of the sid indicate which entry we will work on.
  6137. //
  6138. // Return Value:
  6139. //
  6140. // S_OK for success, else for failure
  6141. //
  6142. // Note:
  6143. //
  6144. // History: Date Author Comment
  6145. // 04/19/2002 mingzhu Created
  6146. //
  6147. //***************************************************************
  6148. HRESULT SetupPreferenceKey(LPCTSTR lpSidString)
  6149. {
  6150. HRESULT hr = E_FAIL;
  6151. LONG lResult;
  6152. DWORD dwResult;
  6153. TCHAR szKeyName[MAX_PATH];
  6154. HKEY hKey = NULL;
  6155. PSID psidUser = NULL;
  6156. PACL pOldDACL = NULL;
  6157. PACL pNewDACL = NULL;
  6158. PSECURITY_DESCRIPTOR pSD = NULL;
  6159. EXPLICIT_ACCESS ea;
  6160. DebugMsg((DM_VERBOSE, TEXT("SetupPreferenceKey: Setting up the preference key for <%s>"), lpSidString));
  6161. //
  6162. // Construct the key name
  6163. //
  6164. hr = StringCchPrintf(szKeyName,
  6165. ARRAYSIZE(szKeyName),
  6166. TEXT("%s\\%s\\%s"),
  6167. PROFILE_LIST_PATH,
  6168. lpSidString,
  6169. PREFERENCE_KEYNAME);
  6170. if (FAILED(hr))
  6171. {
  6172. DebugMsg((DM_WARNING, TEXT("SetupPreferenceKey: Failed to make key name, hr = %08X"), hr));
  6173. goto Exit;
  6174. }
  6175. //
  6176. // Create the "Preference" key, using default security (inherited)
  6177. //
  6178. lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
  6179. szKeyName,
  6180. 0,
  6181. NULL,
  6182. REG_OPTION_NON_VOLATILE,
  6183. KEY_ALL_ACCESS,
  6184. NULL,
  6185. &hKey,
  6186. NULL);
  6187. if (lResult != ERROR_SUCCESS)
  6188. {
  6189. DebugMsg((DM_WARNING, TEXT("SetupPreferenceKey: RegCreateKeyEx failed. Error = %d"), lResult));
  6190. hr = HRESULT_FROM_WIN32(lResult);
  6191. goto Exit;
  6192. }
  6193. //
  6194. // Get the user's sid from its string form
  6195. //
  6196. if (!ConvertStringSidToSid(lpSidString, &psidUser))
  6197. {
  6198. dwResult = GetLastError();
  6199. DebugMsg((DM_WARNING, TEXT("SetupPreferenceKey: ConvertStringSidToSid failed. Error = %d"), dwResult));
  6200. hr = HRESULT_FROM_WIN32(dwResult);
  6201. goto Exit;
  6202. }
  6203. //
  6204. // Get a pointer to the existing DACL and its SD
  6205. //
  6206. dwResult = GetSecurityInfo(hKey,
  6207. SE_REGISTRY_KEY,
  6208. DACL_SECURITY_INFORMATION,
  6209. NULL,
  6210. NULL,
  6211. &pOldDACL,
  6212. NULL,
  6213. &pSD);
  6214. if (dwResult != ERROR_SUCCESS)
  6215. {
  6216. DebugMsg((DM_WARNING, TEXT("SetupPreferenceKey: GetSecurityInfo failed. Error = %d"), dwResult));
  6217. hr = HRESULT_FROM_WIN32(dwResult);
  6218. goto Exit;
  6219. }
  6220. //
  6221. // Initialize an EXPLICIT_ACCESS structure for the new ACE.
  6222. //
  6223. ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
  6224. ea.grfAccessPermissions = KEY_READ | KEY_SET_VALUE;
  6225. ea.grfAccessMode = GRANT_ACCESS;
  6226. ea.grfInheritance= SUB_CONTAINERS_AND_OBJECTS_INHERIT;
  6227. ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
  6228. ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
  6229. ea.Trustee.ptstrName = psidUser;
  6230. //
  6231. // Create a new ACL that merges the new ACE into the existing DACL.
  6232. //
  6233. dwResult = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
  6234. if (dwResult != ERROR_SUCCESS)
  6235. {
  6236. DebugMsg((DM_WARNING, TEXT("SetupPreferenceKey: SetEntriesInAcl failed. Error = %d"), dwResult));
  6237. hr = HRESULT_FROM_WIN32(dwResult);
  6238. goto Exit;
  6239. }
  6240. //
  6241. // Attach the new ACL to the key
  6242. //
  6243. dwResult = SetSecurityInfo(hKey,
  6244. SE_REGISTRY_KEY,
  6245. DACL_SECURITY_INFORMATION,
  6246. NULL,
  6247. NULL,
  6248. pNewDACL,
  6249. NULL);
  6250. if (dwResult != ERROR_SUCCESS)
  6251. {
  6252. DebugMsg((DM_WARNING, TEXT("SetupPreferenceKey: SetSecurityInfo failed. Error = %d"), dwResult));
  6253. hr = HRESULT_FROM_WIN32(dwResult);
  6254. goto Exit;
  6255. }
  6256. DebugMsg((DM_VERBOSE, TEXT("SetupPreferenceKey: Successfully setup the preference key for <%s>"), lpSidString));
  6257. hr = S_OK;
  6258. Exit:
  6259. if(pSD)
  6260. LocalFree(pSD);
  6261. if(pNewDACL)
  6262. LocalFree(pNewDACL);
  6263. if (psidUser)
  6264. LocalFree(psidUser);
  6265. if (hKey)
  6266. RegCloseKey(hKey);
  6267. return hr;
  6268. }