Source code of Windows XP (NT5)
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.

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