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.

3763 lines
120 KiB

  1. //*************************************************************
  2. //
  3. // Copyright (c) Microsoft Corporation 1998
  4. // All rights reserved
  5. //
  6. // util.cxx
  7. //
  8. //*************************************************************
  9. #include "fdeploy.hxx"
  10. WCHAR* NTPrivs[] = {
  11. /*SE_CREATE_TOKEN_NAME,
  12. SE_ASSIGNPRIMARYTOKEN_NAME,
  13. SE_LOCK_MEMORY_NAME,
  14. SE_INCREASE_QUOTA_NAME,
  15. SE_UNSOLICITED_INPUT_NAME,
  16. SE_MACHINE_ACCOUNT_NAME,
  17. SE_TCB_NAME,
  18. SE_SECURITY_NAME,*/
  19. SE_TAKE_OWNERSHIP_NAME, //we only need take ownership privileges
  20. /*SE_LOAD_DRIVER_NAME,
  21. SE_SYSTEM_PROFILE_NAME,
  22. SE_SYSTEMTIME_NAME,
  23. SE_PROF_SINGLE_PROCESS_NAME,
  24. SE_INC_BASE_PRIORITY_NAME,
  25. SE_CREATE_PAGEFILE_NAME,
  26. SE_CREATE_PERMANENT_NAME,
  27. SE_BACKUP_NAME,*/
  28. SE_RESTORE_NAME, //we only need to be able to assign owners
  29. /*SE_SHUTDOWN_NAME,
  30. SE_DEBUG_NAME,
  31. SE_AUDIT_NAME,
  32. SE_SYSTEM_ENVIRONMENT_NAME,
  33. SE_CHANGE_NOTIFY_NAME,
  34. SE_REMOTE_SHUTDOWN_NAME,*/
  35. L"\0"
  36. };
  37. //+--------------------------------------------------------------------------
  38. //
  39. // Member: CCopyFailData::CCopyFailData
  40. //
  41. // Synopsis: constructor for the object that contains data about
  42. // copy failures.
  43. //
  44. // Arguments: none.
  45. //
  46. // Returns: nothing.
  47. //
  48. // History: 1/25/2000 RahulTh created
  49. //
  50. // Notes:
  51. //
  52. //---------------------------------------------------------------------------
  53. CCopyFailData::CCopyFailData () : m_bCopyFailed (FALSE), m_dwSourceBufLen (0),
  54. m_pwszSourceName (NULL), m_dwDestBufLen (0),
  55. m_pwszDestName (NULL)
  56. {
  57. }
  58. //+--------------------------------------------------------------------------
  59. //
  60. // Member: CCopyFailData::~CCopyFailData
  61. //
  62. // Synopsis: destructor for the object that contains data about the last
  63. // copy failure
  64. //
  65. // Arguments: none.
  66. //
  67. // Returns: nothing.
  68. //
  69. // History: 1/25/2000 RahulTh created
  70. //
  71. // Notes:
  72. //
  73. //---------------------------------------------------------------------------
  74. CCopyFailData::~CCopyFailData ()
  75. {
  76. if (m_dwSourceBufLen)
  77. delete [] m_pwszSourceName;
  78. if (m_dwDestBufLen)
  79. delete [] m_pwszDestName;
  80. }
  81. //+--------------------------------------------------------------------------
  82. //
  83. // Member: CCopyFailData::RegisterFailure
  84. //
  85. // Synopsis: registers information about a failed copy.
  86. //
  87. // Arguments: [in] pwszSource : the source file for the copy.
  88. // [in] pwszDest : the destination file for the copy.
  89. //
  90. // Returns: ERROR_SUCCESS : on succesful registration.
  91. // an error code otherwise.
  92. //
  93. // History: 1/25/2000 RahulTh created
  94. //
  95. // Notes: if another failure has already been registered in this
  96. // object, it is not overwritten with the new info. We only
  97. // keep track of the first failure. Since folder redirection
  98. // anyway bails out on the first copy failure, we don't really
  99. // expect this function to be called more than once.
  100. //
  101. //---------------------------------------------------------------------------
  102. DWORD CCopyFailData::RegisterFailure (LPCTSTR pwszSource, LPCTSTR pwszDest)
  103. {
  104. DWORD dwStatus = ERROR_SUCCESS;
  105. DWORD dwFromLen = 0;
  106. DWORD dwToLen = 0;
  107. //bail out if another copy failure has already been registered.
  108. if (m_bCopyFailed)
  109. return dwStatus;
  110. //first copy the source info.
  111. dwFromLen = wcslen (pwszSource);
  112. if (dwFromLen >= m_dwSourceBufLen)
  113. {
  114. //we need a bigger buffer.
  115. delete [] m_pwszSourceName;
  116. m_dwSourceBufLen = 0;
  117. m_pwszSourceName = new WCHAR [dwFromLen + 1];
  118. if (m_pwszSourceName)
  119. m_dwSourceBufLen = dwFromLen + 1;
  120. else
  121. dwStatus = ERROR_OUTOFMEMORY;
  122. }
  123. if (ERROR_SUCCESS == dwStatus)
  124. wcscpy (m_pwszSourceName, pwszSource);
  125. //now copy the destination info.
  126. if (ERROR_SUCCESS == dwStatus)
  127. {
  128. dwToLen = wcslen (pwszDest);
  129. if (dwToLen >= m_dwDestBufLen)
  130. {
  131. //we need a bigger buffer
  132. delete [] m_pwszDestName;
  133. m_dwDestBufLen = 0;
  134. m_pwszDestName = new WCHAR [dwToLen + 1];
  135. if (m_pwszDestName)
  136. m_dwDestBufLen = dwToLen + 1;
  137. else
  138. dwStatus = ERROR_OUTOFMEMORY;
  139. }
  140. }
  141. if (ERROR_SUCCESS == dwStatus)
  142. wcscpy (m_pwszDestName, pwszDest);
  143. //register the fact that the copy fail data has been
  144. //successfully incorporated into the object
  145. if (ERROR_SUCCESS == dwStatus)
  146. m_bCopyFailed = TRUE;
  147. return dwStatus;
  148. }
  149. //+--------------------------------------------------------------------------
  150. //
  151. // Member: CCopyFailData::IsCopyFailure
  152. //
  153. // Synopsis: indicates if copy failure data exists within the object.
  154. //
  155. // Arguments: none.
  156. //
  157. // Returns: TRUE / FALSE : self-explanatory
  158. //
  159. // History: 1/25/2000 RahulTh created
  160. //
  161. // Notes:
  162. //
  163. //---------------------------------------------------------------------------
  164. BOOL CCopyFailData::IsCopyFailure (void)
  165. {
  166. return m_bCopyFailed;
  167. }
  168. //+--------------------------------------------------------------------------
  169. //
  170. // Member: CCopyFailData::GetSourceName
  171. //
  172. // Synopsis: gets the name of the source file of the failed copy.
  173. //
  174. // Arguments: none.
  175. //
  176. // Returns: name of the source file of the failed copy.
  177. //
  178. // History: 1/25/2000 RahulTh created
  179. //
  180. // Notes: returns NULL if the data does not exist or if a
  181. // copy failure has not been incorporated into the object
  182. //
  183. //---------------------------------------------------------------------------
  184. LPCTSTR CCopyFailData::GetSourceName (void)
  185. {
  186. if (! m_bCopyFailed)
  187. return NULL;
  188. if (! m_dwSourceBufLen)
  189. return NULL;
  190. return m_pwszSourceName;
  191. }
  192. //+--------------------------------------------------------------------------
  193. //
  194. // Member: CCopyFailData::GetDestName
  195. //
  196. // Synopsis: gets the name of the destination file of the failed copy.
  197. //
  198. // Arguments: none.
  199. //
  200. // Returns: name of the destination file of the failed copy.
  201. //
  202. // History: 1/25/2000 RahulTh created
  203. //
  204. // Notes: returns NULL if the data does not exist or if a copy failure
  205. // has not been incorporated into the object.
  206. //
  207. //---------------------------------------------------------------------------
  208. LPCTSTR CCopyFailData::GetDestName (void)
  209. {
  210. if (! m_bCopyFailed)
  211. return NULL;
  212. if (! m_dwDestBufLen)
  213. return NULL;
  214. return m_pwszDestName;
  215. }
  216. //+--------------------------------------------------------------------------
  217. //
  218. // Function: IsOnNTFS
  219. //
  220. // Synopsis: this function determines whether a given file/folder lies
  221. // on an NTFS volume or not.
  222. //
  223. // Arguments: [in] pwszPath : the full pathname of the file.
  224. //
  225. // Returns: ERROR_SUCCESS : if it is on NTFS
  226. // ERROR_NO_SECURITY_ON_OBJECT : if it is on FAT
  227. // other error codes if something goes wrong
  228. //
  229. // History: 9/4/1998 RahulTh created
  230. //
  231. // Notes:
  232. // 1. the full pathname is required in order to determine
  233. // if the file/folder is on an NTFS volume
  234. // 2. If the file/folder lies on a network share, then the
  235. // share must be online when this function is executed.
  236. // if it is offline and CSC is turned on, then even NTFS
  237. // volumes will show up as FAT volumes.
  238. //
  239. //---------------------------------------------------------------------------
  240. DWORD IsOnNTFS (const WCHAR* pwszPath)
  241. {
  242. WCHAR* szName = 0;
  243. DWORD Status;
  244. size_t len;
  245. BOOL bAddSlash = FALSE;
  246. BOOL bStatus;
  247. DWORD dwFlags;
  248. WCHAR* szLastSlash;
  249. WCHAR* pwszSuccess = NULL;
  250. // Basic sanity checks
  251. if (NULL == pwszPath || L'\0' == *pwszPath)
  252. {
  253. return ERROR_BAD_PATHNAME;
  254. }
  255. //GetVolumeInformation requires its 1st argument to be terminated by a slash
  256. //so we first make sure that this is the case.
  257. len = wcslen (pwszPath);
  258. if ('\\' != pwszPath[len-1])
  259. {
  260. len++;
  261. bAddSlash = TRUE;
  262. }
  263. szName = (WCHAR*) alloca ((len + 1)*sizeof(WCHAR));
  264. if (0 == szName)
  265. return ERROR_OUTOFMEMORY;
  266. //obtain the absolute path
  267. pwszSuccess = _wfullpath (szName, pwszPath, len + 1);
  268. if (!pwszSuccess)
  269. {
  270. return ERROR_BAD_PATHNAME; //_wfullpath will very rarely fail, but
  271. //never hurts to take precautions
  272. }
  273. if (bAddSlash)
  274. {
  275. szName[len] = '\0';
  276. szName[len-1] = '\\';
  277. }
  278. //now our path name is terminated by a slash, and we have the absolute path
  279. //too, so we don't have to worry about errors generating from weird paths
  280. //like \\server\share\hello\..\.\ etc...
  281. for (szLastSlash = szName + len - 1;;)
  282. {
  283. bStatus = GetVolumeInformation (szName, 0, 0, 0, 0, &dwFlags, 0, 0);
  284. if (!bStatus)
  285. {
  286. Status = GetLastError();
  287. if (ERROR_DIR_NOT_ROOT != Status)
  288. {
  289. return Status;
  290. }
  291. //GetVolumeInformation requires that the path provided to it be
  292. //the root of the volume. So if we are here, it means that the
  293. //function returned ERROR_DIR_NOT_ROOT. So we remove the last
  294. //component from the path and try with the smaller path. We repeat
  295. //this until we either succeed or end up with no path in which
  296. //case we return ERROR_INVALID_NAME
  297. *szLastSlash = '\0';
  298. szLastSlash = wcsrchr (szName, '\\');
  299. if (NULL == szLastSlash)
  300. return ERROR_INVALID_NAME; //we have run out of components
  301. else
  302. szLastSlash[1] = '\0'; //get rid of the last component.
  303. }
  304. else
  305. break;
  306. }
  307. if (dwFlags & FS_PERSISTENT_ACLS)
  308. return ERROR_SUCCESS; //NTFS supports persistent ACLs
  309. //if we are here, then GetVolumeInformation succeeded, but the volume
  310. //does not support persistent ACLs. So it must be a FAT volume.
  311. return ERROR_NO_SECURITY_ON_OBJECT;
  312. }
  313. //+--------------------------------------------------------------------------
  314. //
  315. // Function: ModifyAccessAllowedAceCounts
  316. //
  317. // Synopsis: given an ace, this function determines if the rights of this
  318. // ace apply to the object itself, propogates to its container
  319. // descendants and propogates to its non-container (or object)
  320. // descendants. It increments one or more of the provided counts
  321. // based on this.
  322. //
  323. // Arguments: [in] pAceHeader : pointer to the ACE header structure
  324. // [in,out] pCount : pointer to count which is incremented if the
  325. // ACE applies to the object on whose ACL it is
  326. // found
  327. // [in,out] pContainerCount : pointer to count which is incremented
  328. // if the ACE propagates to all
  329. // container descendants
  330. // [in,out] pObjectCount : pointer to count which is incremented if
  331. // the ACE propagates to all non-container
  332. // descendants
  333. //
  334. // Returns: nothing
  335. //
  336. // History: 9/4/1998 RahulTh created
  337. //
  338. // Notes: inheritance of the ace is not counted if the
  339. // NO_PROPAGATE_INHERIT_ACE flag is present.
  340. //
  341. //---------------------------------------------------------------------------
  342. void
  343. ModifyAccessAllowedAceCounts (
  344. PACE_HEADER pAceHeader, LONG* pCount,
  345. LONG* pContainerCount, LONG* pObjectCount
  346. )
  347. {
  348. if (! (INHERIT_ONLY_ACE & pAceHeader->AceFlags))
  349. (*pCount)++;
  350. if (NO_PROPAGATE_INHERIT_ACE & pAceHeader->AceFlags)
  351. return; //the rights of this Ace will not be propagated all the way
  352. if (CONTAINER_INHERIT_ACE & pAceHeader->AceFlags)
  353. (*pContainerCount)++;
  354. if (OBJECT_INHERIT_ACE & pAceHeader->AceFlags)
  355. (*pObjectCount)++;
  356. return;
  357. }
  358. //+--------------------------------------------------------------------------
  359. //
  360. // Function: RestrictMyDocsRedirection
  361. //
  362. // Synopsis: Disables/Enables the ability of users to redirect the
  363. // "My Documents" folder
  364. //
  365. // Arguments: [in] fRestrict : Disable if TRUE, Enable if FALSE
  366. //
  367. // Returns: ERROR_SUCCESS : on success
  368. // *OR* other Win32 error codes based on the error that occurred
  369. //
  370. // History: 8/25/1998 RahulTh created
  371. //
  372. // Notes:
  373. //
  374. //---------------------------------------------------------------------------
  375. DWORD RestrictMyDocsRedirection (
  376. HANDLE hToken,
  377. HKEY hKeyRoot,
  378. BOOL fRestrict
  379. )
  380. {
  381. HKEY hkRoot;
  382. HANDLE hUserToken;
  383. HKEY hkPolicies;
  384. HKEY hkExplorer;
  385. DWORD Status;
  386. hkRoot = hKeyRoot;
  387. hUserToken = hToken;
  388. //
  389. // This policies key is secured, so we must do this as LocalSystem.
  390. //
  391. RevertToSelf();
  392. Status = RegCreateKeyEx(
  393. hkRoot,
  394. L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies",
  395. 0,
  396. NULL,
  397. REG_OPTION_NON_VOLATILE,
  398. KEY_READ | KEY_WRITE,
  399. NULL,
  400. &hkPolicies,
  401. NULL );
  402. if ( ERROR_SUCCESS == Status )
  403. {
  404. Status = RegCreateKeyEx(
  405. hkPolicies,
  406. L"Explorer",
  407. 0,
  408. NULL,
  409. REG_OPTION_NON_VOLATILE,
  410. KEY_READ | KEY_WRITE,
  411. NULL,
  412. &hkExplorer,
  413. NULL );
  414. RegCloseKey( hkPolicies );
  415. }
  416. if ( ERROR_SUCCESS == Status )
  417. {
  418. if ( fRestrict )
  419. {
  420. Status = RegSetValueEx(
  421. hkExplorer,
  422. L"DisablePersonalDirChange",
  423. 0,
  424. REG_DWORD,
  425. (PBYTE) &fRestrict,
  426. sizeof(fRestrict) );
  427. }
  428. else
  429. {
  430. RegDeleteValue( hkExplorer, L"DisablePersonalDirChange" );
  431. }
  432. RegCloseKey( hkExplorer );
  433. }
  434. //now that the keys have been modified, return to impersonation.
  435. if (!ImpersonateLoggedOnUser( hUserToken ))
  436. Status = GetLastError();
  437. if ( ERROR_SUCCESS == Status )
  438. {
  439. if ( fRestrict )
  440. {
  441. DebugMsg((DM_VERBOSE, IDS_MYDOCSRESTRICT_ON));
  442. }
  443. else
  444. {
  445. DebugMsg((DM_VERBOSE, IDS_MYDOCSRESTRICT_OFF));
  446. }
  447. }
  448. return Status;
  449. }
  450. //+--------------------------------------------------------------------------
  451. //
  452. // Function: GroupInList
  453. //
  454. // Synopsis: given a group sid in string format, and a list of group sids
  455. // in PTOKEN_GROUPS format, this function figures out if the
  456. // give sid belongs to that list
  457. //
  458. // Arguments: [in] pwszSid : the given sid in string format
  459. // [in] PTOKEN_GROUPS : a list of group sids
  460. //
  461. // Returns: TRUE : if the group is found in the list
  462. // FALSE : otherwise. FALSE is also returned if an error occurs
  463. //
  464. // History: 10/6/1998 RahulTh created
  465. //
  466. // Notes:
  467. //
  468. //---------------------------------------------------------------------------
  469. BOOL GroupInList (WCHAR * pwszSid, PTOKEN_GROUPS pGroups)
  470. {
  471. ASSERT (pwszSid);
  472. PSID pSid = 0;
  473. DWORD Status;
  474. BOOL bStatus = FALSE;
  475. DWORD i;
  476. //optimization for the basic case
  477. if (0 == lstrcmpi (pwszSid, L"s-1-1-0")) //if the user is an earthling
  478. {
  479. bStatus = TRUE;
  480. goto GroupInListEnd;
  481. }
  482. Status = AllocateAndInitSidFromString (pwszSid, &pSid);
  483. if (ERROR_SUCCESS != Status)
  484. goto GroupInListEnd;
  485. for (i = 0, bStatus = FALSE;
  486. i < pGroups->GroupCount && !bStatus;
  487. i++
  488. )
  489. {
  490. bStatus = RtlEqualSid (pSid, pGroups->Groups[i].Sid);
  491. }
  492. GroupInListEnd:
  493. if (pSid)
  494. RtlFreeSid (pSid);
  495. return bStatus;
  496. }
  497. //+--------------------------------------------------------------------------
  498. //
  499. // Function: AllocateAndInitSidFromString
  500. //
  501. // Synopsis: given the string representation of a SID, this function
  502. // allocate and initializes a SID which the string represents
  503. // For more information on the string representation of SIDs
  504. // refer to ntseapi.h & ntrtl.h
  505. //
  506. // Arguments: [in] lpszSidStr : the string representation of the SID
  507. // [out] pSID : the actual SID structure created from the string
  508. //
  509. // Returns: STATUS_SUCCESS : if the sid structure was successfully created
  510. // or an error code based on errors that might occur
  511. //
  512. // History: 10/6/1998 RahulTh created
  513. //
  514. // Notes:
  515. //
  516. //---------------------------------------------------------------------------
  517. NTSTATUS AllocateAndInitSidFromString (const WCHAR* lpszSidStr, PSID* ppSid)
  518. {
  519. WCHAR * pSidStr = 0;
  520. WCHAR* pString = 0;
  521. NTSTATUS Status;
  522. WCHAR* pEnd = 0;
  523. int count;
  524. BYTE SubAuthCount;
  525. DWORD SubAuths[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  526. ULONG n;
  527. SID_IDENTIFIER_AUTHORITY Auth;
  528. pSidStr = new WCHAR [lstrlen (lpszSidStr) + 1];
  529. if (!pSidStr)
  530. {
  531. Status = STATUS_NO_MEMORY;
  532. goto AllocAndInitSidFromStr_End;
  533. }
  534. lstrcpy (pSidStr, lpszSidStr);
  535. pString = pSidStr;
  536. *ppSid = NULL;
  537. count = 0;
  538. do
  539. {
  540. pString = wcschr (pString, '-');
  541. if (NULL == pString)
  542. break;
  543. count++;
  544. pString++;
  545. } while (1);
  546. SubAuthCount = (BYTE)(count - 2);
  547. if (0 > SubAuthCount || 8 < SubAuthCount)
  548. {
  549. Status = ERROR_INVALID_SID;
  550. goto AllocAndInitSidFromStr_End;
  551. }
  552. pString = wcschr (pSidStr, L'-');
  553. pString++;
  554. pString = wcschr (pString, L'-'); //ignore the revision #
  555. pString++;
  556. pEnd = wcschr (pString, L'-'); //go to the beginning of subauths.
  557. if (NULL != pEnd) *pEnd = L'\0';
  558. Status = LoadSidAuthFromString (pString, &Auth);
  559. if (STATUS_SUCCESS != Status)
  560. goto AllocAndInitSidFromStr_End;
  561. for (count = 0; count < SubAuthCount; count++)
  562. {
  563. pString = pEnd + 1;
  564. pEnd = wcschr (pString, L'-');
  565. if (pEnd)
  566. *pEnd = L'\0';
  567. Status = GetIntFromUnicodeString (pString, 10, &n);
  568. if (STATUS_SUCCESS != Status)
  569. goto AllocAndInitSidFromStr_End;
  570. SubAuths[count] = n;
  571. }
  572. Status = RtlAllocateAndInitializeSid (&Auth, SubAuthCount,
  573. SubAuths[0], SubAuths[1], SubAuths[2],
  574. SubAuths[3], SubAuths[4], SubAuths[5],
  575. SubAuths[6], SubAuths[7], ppSid);
  576. AllocAndInitSidFromStr_End:
  577. if (pSidStr)
  578. delete [] pSidStr;
  579. return Status;
  580. }
  581. //+--------------------------------------------------------------------------
  582. //
  583. // Function: LoadSidAuthFromString
  584. //
  585. // Synopsis: given a string representing the SID authority (as it is
  586. // normally represented in string format, fill the SID_AUTH..
  587. // structure. For more details on the format of the string
  588. // representation of the sid authority, refer to ntseapi.h and
  589. // ntrtl.h
  590. //
  591. // Arguments: [in] pString : pointer to the unicode string
  592. // [out] pSidAuth : pointer to the SID_IDENTIFIER_AUTH.. that is
  593. // desired
  594. //
  595. // Returns: STATUS_SUCCESS if it succeeds
  596. // or an error code
  597. //
  598. // History: 9/29/1998 RahulTh created
  599. //
  600. // Notes:
  601. //
  602. //---------------------------------------------------------------------------
  603. NTSTATUS LoadSidAuthFromString (const WCHAR* pString,
  604. PSID_IDENTIFIER_AUTHORITY pSidAuth)
  605. {
  606. size_t len;
  607. int i;
  608. NTSTATUS Status;
  609. const ULONG LowByteMask = 0xFF;
  610. ULONG n;
  611. len = wcslen (pString);
  612. if (len > 2 && 'x' == pString[1])
  613. {
  614. //this is in hex.
  615. //so we must have exactly 14 characters
  616. //(2 each for each of the 6 bytes) + 2 for the leading 0x
  617. if (14 != len)
  618. {
  619. Status = ERROR_INVALID_SID;
  620. goto LoadAuthEnd;
  621. }
  622. for (i=0; i < 6; i++)
  623. {
  624. pString += 2; //we need to skip the leading 0x
  625. pSidAuth->Value[i] = (UCHAR)(((pString[0] - L'0') << 4) +
  626. (pString[1] - L'0'));
  627. }
  628. }
  629. else
  630. {
  631. //this is in decimal
  632. Status = GetIntFromUnicodeString (pString, 10, &n);
  633. if (Status != STATUS_SUCCESS)
  634. goto LoadAuthEnd;
  635. pSidAuth->Value[0] = pSidAuth->Value[1] = 0;
  636. for (i = 5; i >=2; i--, n>>=8)
  637. pSidAuth->Value[i] = (UCHAR)(n & LowByteMask);
  638. }
  639. Status = STATUS_SUCCESS;
  640. LoadAuthEnd:
  641. return Status;
  642. }
  643. //+--------------------------------------------------------------------------
  644. //
  645. // Function: GetIntfromUnicodeString
  646. //
  647. // Synopsis: converts a unicode string into an integer
  648. //
  649. // Arguments: [in] szNum : the number represented as a unicode string
  650. // [in] Base : the base in which the resultant int is desired
  651. // [out] pValue : pointer to the integer representation of the
  652. // number
  653. //
  654. // Returns: STATUS_SUCCESS if successful.
  655. // or some other error code
  656. //
  657. // History: 9/29/1998 RahulTh created
  658. //
  659. // Notes:
  660. //
  661. //---------------------------------------------------------------------------
  662. NTSTATUS GetIntFromUnicodeString (const WCHAR* szNum, ULONG Base, PULONG pValue)
  663. {
  664. WCHAR * pwszNumStr = 0;
  665. UNICODE_STRING StringW;
  666. size_t len;
  667. NTSTATUS Status;
  668. len = lstrlen (szNum);
  669. pwszNumStr = new WCHAR [len + 1];
  670. if (!pwszNumStr)
  671. {
  672. Status = STATUS_NO_MEMORY;
  673. goto GetNumEnd;
  674. }
  675. lstrcpy (pwszNumStr, szNum);
  676. StringW.Length = len * sizeof(WCHAR);
  677. StringW.MaximumLength = StringW.Length + sizeof (WCHAR);
  678. StringW.Buffer = pwszNumStr;
  679. Status = RtlUnicodeStringToInteger (&StringW, Base, pValue);
  680. GetNumEnd:
  681. if (pwszNumStr)
  682. delete [] pwszNumStr;
  683. return Status;
  684. }
  685. //+--------------------------------------------------------------------------
  686. //
  687. // Function: CopyProgressRoutine
  688. //
  689. // Synopsis: this is a callback function for PrivCopyFileExW. It is used
  690. // to track errors that are considered fatal by the folder
  691. // redirection client. In many cases, PrivCopyFileExW will succeed
  692. // even if a certain operation like encryption fails. The only
  693. // way a calling prgram can find out about this is through this
  694. // callback function by looking at the reason for the callback.
  695. // currently, the only 3 reasons that are considered fatal for
  696. // redirection are PRIVCALLBACK_ENCRYPTION_FAILED and
  697. // PRIVCALLBACK_DACL_ACCESS_DENIED and
  698. // PRIVCALLBACK_OWNER_GROUP_ACCESS_DENIED. All other reasons will
  699. // either not occur, or can be safely ignored.
  700. //
  701. // The data passed via lpData is actually a pointer to a DWORD
  702. // that this callback function uses to store an error code if one
  703. // occurs.
  704. //
  705. // Arguments: see sdk help on CopyProgressRoutine
  706. //
  707. // Returns: see sdk help on CopyProgressRoutine
  708. //
  709. // History: 10/21/1998 RahulTh created
  710. //
  711. // Notes:
  712. //
  713. //---------------------------------------------------------------------------
  714. DWORD CALLBACK CopyProgressRoutine (
  715. LARGE_INTEGER TotalFileSize,
  716. LARGE_INTEGER TotalBytesTransferred,
  717. LARGE_INTEGER StreamSize,
  718. LARGE_INTEGER StreamBytesTransferred,
  719. DWORD dwStreamNumber,
  720. DWORD dwCallbackReason,
  721. HANDLE hSourceFile,
  722. HANDLE hDestinationFile,
  723. LPVOID lpData
  724. )
  725. {
  726. LPDWORD lpStatus = (LPDWORD) lpData;
  727. //an error condition has already been registered. No need to invoke
  728. //this callback again
  729. if (ERROR_SUCCESS != *lpStatus)
  730. return PROGRESS_QUIET;
  731. switch (dwCallbackReason)
  732. {
  733. case PRIVCALLBACK_ENCRYPTION_FAILED:
  734. *lpStatus = ERROR_ENCRYPTION_FAILED;
  735. return PROGRESS_CANCEL; //no point continuing. we have already failed
  736. case PRIVCALLBACK_DACL_ACCESS_DENIED:
  737. *lpStatus = ERROR_INVALID_SECURITY_DESCR;
  738. return PROGRESS_CANCEL; //same as above
  739. case PRIVCALLBACK_OWNER_GROUP_ACCESS_DENIED:
  740. *lpStatus = ERROR_INVALID_OWNER;
  741. return PROGRESS_CANCEL;
  742. default:
  743. return PROGRESS_CONTINUE; //all other conditions can be safely ignored
  744. }
  745. }
  746. //+--------------------------------------------------------------------------
  747. //
  748. // Function: FullFileCopyW
  749. //
  750. // Synopsis: this function makes use of the internal API PrivCopyFileExW
  751. // to copy not only the contents of a file but also metadata
  752. // like encryption, compression and DACL
  753. //
  754. // This function also imposes limits on the lengths of the files
  755. // that can be copied. Anything longer than MAX_PATH is disallowed
  756. // because the shell cannot gracefully handle such paths and we
  757. // don't want to create problems for the user by redirecting their
  758. // files to paths that explorer cannot get to.
  759. //
  760. // Arguments: [in] wszSource : the path of the source file.
  761. // [in] wszDest : the path of the destination file.
  762. // [in] bFailIfExists : whether the function should fail if
  763. // the destination exists
  764. //
  765. // Returns: ERROR_SUCCESS : if successful
  766. // ERROR_ENCRYPTION_FAILED : if the source is encrypted and
  767. // the destination cannot be encrypted
  768. // ERROR_INVALID_SECURITY_DESCR: if the DACL of the source cannot
  769. // be copied over to the destination
  770. // ERROR_FILE_EXISTS / ERROR_ALREADY_EXISTS : if the destination
  771. // exists and bFailIfExists is TRUE
  772. // ERROR_INVALID_OWNER : if the owner info. cannot be copied
  773. // or other error codes.
  774. //
  775. // ERROR_FILENAME_EXCED_RANGE : if the filename is longer than MAX_PATH.
  776. //
  777. // History: 10/22/1998 RahulTh created
  778. // 12/13/2000 RahulTh added length limitations
  779. //
  780. // Notes:
  781. //
  782. //---------------------------------------------------------------------------
  783. DWORD FullFileCopyW (
  784. const WCHAR* wszSource,
  785. const WCHAR* wszDest,
  786. BOOL bFailIfExists
  787. )
  788. {
  789. DWORD Status = ERROR_SUCCESS;
  790. DWORD dwFlags = PRIVCOPY_FILE_METADATA | PRIVCOPY_FILE_OWNER_GROUP;
  791. BOOL bCancel = FALSE;
  792. BOOL bStatus;
  793. int lenSource = 0;
  794. int lenDest = 0;
  795. if (bFailIfExists)
  796. dwFlags |= COPY_FILE_FAIL_IF_EXISTS;
  797. if (! wszSource)
  798. lenSource = wcslen (wszSource);
  799. if (! wszDest)
  800. lenDest = wcslen (wszDest);
  801. //
  802. // Prevent copying of files longer than MAX_PATH characters. This limitation
  803. // needs to be added because the shell cannot handle paths longer than
  804. // MAX_PATH gracefully and we don't want to land the users into trouble by
  805. // creating files / folder that they cannot get to via explorer.
  806. //
  807. if (lenDest >= MAX_PATH || lenSource >= MAX_PATH)
  808. return ERROR_FILENAME_EXCED_RANGE;
  809. bStatus = PrivCopyFileExW (wszSource, wszDest,
  810. (LPPROGRESS_ROUTINE) CopyProgressRoutine,
  811. (LPVOID) &Status,
  812. &bCancel,
  813. dwFlags
  814. );
  815. //get the last error if PrivCopyFileExW failed
  816. //and the callback function has not already registered a fatal error
  817. if ((ERROR_SUCCESS == Status) && (!bStatus))
  818. Status = GetLastError();
  819. return Status;
  820. }
  821. //+--------------------------------------------------------------------------
  822. //
  823. // Function: FullDirCopyW
  824. //
  825. // Synopsis: creates a directory using the new PrivCopyFileExW so that
  826. // all the file metadata and ownership information is retained
  827. //
  828. // This function also imposes limits on the lengths of the folders
  829. // that can be copied. Anything longer than MAX_PATH is disallowed
  830. // because the shell cannot gracefully handle such paths and we
  831. // don't want to create problems for the user by redirecting their
  832. // files to paths that explorer cannot get to.
  833. //
  834. // Arguments: [in] pwszSource : the full path of the source directory
  835. // [in] pwszDest : the full path of the destination directory
  836. // [in] bSkipDacl : Skip DACL copying.
  837. //
  838. // Returns: ERROR_SUCCESS : if the copy was successful
  839. // ERROR_INVALID_SECURITY_DESCR : if the DACL could not be applied
  840. // ERROR_INVALID_OWNER : if the owner information could not be copied
  841. // ERROR_ENCRYPTION_FAILED : if the encryption info. could not be copied
  842. // or other error codes if some other error occurs
  843. // ERROR_FILENAME_EXCED_RANGE : if the filename is longer than MAX_PATH.
  844. //
  845. // History: 11/5/1998 RahulTh created
  846. // 12/13/2000 RahulTh added length limitations
  847. // 5/2/2002 RahulTh added the skip DACL flag
  848. //
  849. // Notes: Essentially the same as FullFileCopyW, but we have an extra
  850. // attribute to indicate that we are trying to copy a directory
  851. // Also, the FAIL_IF_EXSTS flag doesn't have any significance
  852. // when we are trying to copy directories, so that is something
  853. // we do not need here.
  854. //
  855. //---------------------------------------------------------------------------
  856. DWORD FullDirCopyW (const WCHAR* pwszSource, const WCHAR* pwszDest, BOOL bSkipDacl)
  857. {
  858. DWORD Status = ERROR_SUCCESS;
  859. DWORD dwFlags = PRIVCOPY_FILE_METADATA |
  860. PRIVCOPY_FILE_OWNER_GROUP | PRIVCOPY_FILE_DIRECTORY;
  861. BOOL bCancel = FALSE;
  862. BOOL bStatus = TRUE;
  863. int lenSource = 0;
  864. int lenDest = 0;
  865. if (! pwszSource)
  866. lenSource = wcslen (pwszSource);
  867. if (! pwszDest)
  868. lenDest = wcslen (pwszDest);
  869. //
  870. // Prevent copying of files longer than MAX_PATH characters. This limitation
  871. // needs to be added because the shell cannot handle paths longer than
  872. // MAX_PATH gracefully and we don't want to land the users into trouble by
  873. // creating files / folder that they cannot get to via explorer.
  874. //
  875. if (lenDest >= MAX_PATH || lenSource >= MAX_PATH)
  876. return ERROR_FILENAME_EXCED_RANGE;
  877. if (bSkipDacl)
  878. dwFlags |= PRIVCOPY_FILE_SKIP_DACL;
  879. bStatus = PrivCopyFileExW (pwszSource, pwszDest,
  880. (LPPROGRESS_ROUTINE) CopyProgressRoutine,
  881. (LPVOID) &Status,
  882. &bCancel,
  883. dwFlags
  884. );
  885. //get the last error if PrivCopyFileExW failed
  886. //and the callback function has not already registered a fatal error
  887. if ((ERROR_SUCCESS == Status) && (!bStatus))
  888. Status = GetLastError();
  889. return Status;
  890. }
  891. //+--------------------------------------------------------------------------
  892. //
  893. // Function: FileInDir
  894. //
  895. // Synopsis: given a file and a directory, this function determines if
  896. // a file with the same name exists in the given directory.
  897. //
  898. // Arguments: [in] pwszFile : the name of the file : it can be the full path
  899. // [in] pwszDir : the directory for which the check needs to be
  900. // performed
  901. // [out] pExists : if the function succeeds, this will contain
  902. // the result. TRUE if the file is present in the
  903. // directory. FALSE otherwise.
  904. //
  905. // Returns: ERROR_SUCCESS : if it is successful
  906. // ERROR_OUTOFMEMORY : if it runs out of memory
  907. // ERROR_BAD_NETPATH : if the network path for the given directory
  908. // cannot be found
  909. //
  910. // History: 10/28/1998 RahulTh created
  911. //
  912. // Notes: pwszDir MUST BE \ terminated
  913. //
  914. //---------------------------------------------------------------------------
  915. DWORD FileInDir (LPCWSTR pwszFile, LPCWSTR pwszDir, BOOL* pExists)
  916. {
  917. const WCHAR* pwszFileName = NULL;
  918. WCHAR* pwszDestName = NULL;
  919. int len;
  920. //first get the display name of the source file
  921. pwszFileName = wcsrchr (pwszFile, L'\\');
  922. if (!pwszFileName)
  923. pwszFileName = pwszFile;
  924. else
  925. pwszFileName++; //go past the slash
  926. //the dir should be \ terminated
  927. len = wcslen (pwszFile) + wcslen (pwszDir) + 1;
  928. pwszDestName = (WCHAR*) alloca (sizeof (WCHAR) * len);
  929. if (!pwszDestName)
  930. return ERROR_OUTOFMEMORY;
  931. wcscpy (pwszDestName, pwszDir);
  932. wcscat (pwszDestName, pwszFileName);
  933. if (0xFFFFFFFF == GetFileAttributes(pwszDestName))
  934. {
  935. //return an error if it is a bad network name. Saves us the trouble
  936. //of trying to redirect to a non-existent location later
  937. if (ERROR_BAD_NETPATH == GetLastError())
  938. return ERROR_BAD_NETPATH;
  939. else
  940. *pExists = FALSE;
  941. }
  942. else
  943. *pExists = TRUE;
  944. return ERROR_SUCCESS;
  945. }
  946. //+--------------------------------------------------------------------------
  947. //
  948. // Function: ComparePaths
  949. //
  950. // Synopsis: given 2 paths, this function compares them to check if
  951. // they are identical or if one is a descendant of the other
  952. // or if no such relationship can be deduced
  953. //
  954. // Arguments: [in] pwszSource : the first path
  955. // [in] pwszDest : the second path
  956. // [out] pResult : the result of the comparison if the function
  957. // succeeds in comparing the paths.
  958. // value of pResult may contain the following values upon
  959. // successful completion.
  960. // 0 : if the 2 paths are identical
  961. // -1 : if the second path is a descendant of the first
  962. // 1 : if no such relationship can be deduced
  963. //
  964. // Returns: ERROR_SUCCESS : if the function succeeds in comparing the paths
  965. // other error codes depending on the failure
  966. //
  967. // History: 10/28/1998 RahulTh created
  968. //
  969. // Notes: the result of the comparison is unreliable if the paths are
  970. // expressed in different formats, e.g. TCP/IP, UNC, NetBios etc.
  971. //
  972. //---------------------------------------------------------------------------
  973. DWORD ComparePaths (LPCWSTR pwszSource, LPCWSTR pwszDest, int* pResult)
  974. {
  975. DWORD Status = ERROR_SUCCESS;
  976. BOOL bStatus;
  977. WCHAR* pwszAbsSource = NULL;
  978. WCHAR* pwszAbsDest = NULL;
  979. int lSource, lDest;
  980. WCHAR* pwszSuccess = NULL;
  981. ASSERT (pResult);
  982. //first allocate memory for the absolute paths.
  983. //since the arguments to this function are full pathnames
  984. //the lengths of the absolute paths cannot exceed the length of
  985. //the parameters
  986. //add an extra character because we will add a \ to the end of the abs. path
  987. lSource = wcslen (pwszSource) + 2;
  988. pwszAbsSource = (WCHAR*) alloca (sizeof(WCHAR) * lSource);
  989. if (!pwszAbsSource)
  990. {
  991. Status = ERROR_OUTOFMEMORY;
  992. goto ComparePathsEnd;
  993. }
  994. //add an extra character because we will add a \ to the end of the abs. path
  995. lDest = wcslen (pwszDest) + 2;
  996. pwszAbsDest = (WCHAR*) alloca (sizeof(WCHAR) * lDest);
  997. if (!pwszAbsDest)
  998. {
  999. Status = ERROR_OUTOFMEMORY;
  1000. goto ComparePathsEnd;
  1001. }
  1002. //first get the absolute paths. after that we will just work with the
  1003. //absolute paths.
  1004. //note: we need the absolute paths so that we can can check if one path
  1005. //is a descendant of the other path by just using wcsncmp. without absolute
  1006. //paths, wcsncmp cannot be used because we can have 2 paths like
  1007. //\\server\share\hello\there and \\server\share\hello\..\hello\there\hi
  1008. //in this case the second path is actually a descendant of the first, but
  1009. //wcsncmp cannot detect that. getting the absolute paths will eliminate
  1010. //the .., . etc.
  1011. //also we must terminate the absolute paths with \, so that wcsncmp does
  1012. //not mistakenly think that \\server\share\hellofubar is a descendant
  1013. //of \\server\share\hello
  1014. pwszSuccess = _wfullpath (pwszAbsSource, pwszSource, lSource);
  1015. if (!pwszSuccess)
  1016. {
  1017. Status = ERROR_BAD_PATHNAME;
  1018. goto ComparePathsEnd;
  1019. }
  1020. pwszSuccess = _wfullpath (pwszAbsDest, pwszDest, lDest);
  1021. if (!pwszSuccess)
  1022. {
  1023. Status = ERROR_BAD_PATHNAME;
  1024. goto ComparePathsEnd;
  1025. }
  1026. //update the lengths with the actual lengths of the absolute paths
  1027. //not including the terminating null character
  1028. lSource = wcslen (pwszAbsSource);
  1029. lDest = wcslen (pwszAbsDest);
  1030. //terminate the absolute paths with '\' if necessary. also make
  1031. //the appropriate changes to the lengths
  1032. if (L'\\' != pwszAbsSource[lSource - 1])
  1033. {
  1034. wcscat (pwszAbsSource, L"\\"); //we won't run out of space here
  1035. //because of the extra character allocation
  1036. lSource++;
  1037. }
  1038. if (L'\\' != pwszAbsDest[lDest - 1])
  1039. {
  1040. wcscat (pwszAbsDest, L"\\"); //won't run out of space here because
  1041. //of the extra allocation above
  1042. lDest++;
  1043. }
  1044. //now we are all set (finally!) to perform the comparisons
  1045. //first do a simple check of whether the paths are identical
  1046. if ((lSource == lDest) && (0 == _wcsicmp (pwszAbsSource, pwszAbsDest)))
  1047. {
  1048. *pResult = 0;
  1049. goto ComparePathsSuccess;
  1050. }
  1051. //check for recursion
  1052. if ((lDest > lSource) && (0 == _wcsnicmp (pwszAbsSource, pwszAbsDest, lSource)))
  1053. {
  1054. *pResult = -1;
  1055. goto ComparePathsSuccess;
  1056. }
  1057. //if we are here, these paths are not identical...
  1058. *pResult = 1;
  1059. ComparePathsSuccess:
  1060. Status = ERROR_SUCCESS;
  1061. goto ComparePathsEnd;
  1062. ComparePathsEnd:
  1063. return Status;
  1064. }
  1065. //+--------------------------------------------------------------------------
  1066. //
  1067. // Function: CheckIdenticalSpecial
  1068. //
  1069. // Synopsis: given 2 paths, this function determines if they are actually
  1070. // the same path expressed in 2 different formats
  1071. //
  1072. // Arguments: [in] pwszSource : path #1
  1073. // [in] pwszDest : path #2
  1074. // [out] pResult : result of the comparison
  1075. //
  1076. // Returns: ERROR_SUCCESS if the function could perform the comparison
  1077. // in this case *pResult will contain the result of comparison
  1078. // Other win32 errors, in which case *pResult should not be used
  1079. // by the calling function
  1080. //
  1081. // History: 12/1/1998 RahulTh created
  1082. //
  1083. // Notes: this function expects both pwszSource and pwszDest to exist and
  1084. // be online when it is called.
  1085. //
  1086. //---------------------------------------------------------------------------
  1087. DWORD CheckIdenticalSpecial (LPCWSTR pwszSource, LPCWSTR pwszDest, int* pResult)
  1088. {
  1089. ASSERT (pResult);
  1090. BOOL bStatus;
  1091. DWORD Status;
  1092. BOOL bTempFileCreated = FALSE;
  1093. WCHAR * pwszTempPath;
  1094. UINT lUnique = 0;
  1095. BOOL bFileExists;
  1096. WCHAR * pwszSlashTerminatedDest;
  1097. int lDest;
  1098. //first append a \ to pwszDest if it is not already \ terminated
  1099. //allocate an extra characted just in case we need it
  1100. pwszSlashTerminatedDest = (WCHAR *) alloca (sizeof (WCHAR) * ((lDest = wcslen(pwszDest)) + 2));
  1101. if (!pwszSlashTerminatedDest)
  1102. {
  1103. Status = ERROR_OUTOFMEMORY;
  1104. goto CheckIdenticalEnd;
  1105. }
  1106. wcscpy (pwszSlashTerminatedDest, pwszDest);
  1107. if (L'\\' != pwszSlashTerminatedDest[lDest - 1])
  1108. {
  1109. wcscat (pwszSlashTerminatedDest, L"\\");
  1110. lDest++;
  1111. }
  1112. pwszTempPath = (WCHAR*) alloca (sizeof (WCHAR) * (MAX_PATH + wcslen(pwszSource) + 2));
  1113. if (!pwszTempPath)
  1114. {
  1115. Status = ERROR_OUTOFMEMORY;
  1116. goto CheckIdenticalEnd;
  1117. }
  1118. if (0 == (lUnique = GetTempFileName(pwszSource, L"fde", 0, pwszTempPath)))
  1119. {
  1120. //a failure to create the temporary file would mean that the source
  1121. //and destination paths are different...
  1122. *pResult = 1;
  1123. goto CheckIdenticalSuccess;
  1124. }
  1125. //now we have created a temporary file,
  1126. bTempFileCreated = TRUE;
  1127. //check if it exists on the destination
  1128. //note: FileInDir requires that the path in the second parameter is
  1129. // slash terminated.
  1130. Status = FileInDir (pwszTempPath, pwszSlashTerminatedDest, &bFileExists);
  1131. if (Status != ERROR_SUCCESS)
  1132. goto CheckIdenticalEnd;
  1133. //if the file does not exist at the destination, we know that these 2 paths
  1134. //are different. However, if the file does exist at the destination, we
  1135. //need to watch out for the rare case that the file existed even before we
  1136. //we created the temp file at the source. To do this, we must delete the
  1137. //temp file from the source and make sure that it has indeed disappeared
  1138. //from the destination
  1139. if (!bFileExists)
  1140. {
  1141. *pResult = 1;
  1142. }
  1143. else
  1144. {
  1145. if (!DeleteFile(pwszTempPath))
  1146. goto CheckIdenticalErr;
  1147. //the file has been deleted
  1148. bTempFileCreated = FALSE;
  1149. //make sure that it has disappeared from the destination
  1150. Status = FileInDir (pwszTempPath, pwszSlashTerminatedDest, &bFileExists);
  1151. if (Status != ERROR_SUCCESS)
  1152. goto CheckIdenticalEnd;
  1153. if (bFileExists)
  1154. {
  1155. *pResult = 1; //by some quirk of fate, a file by the same name as
  1156. //the tempfile preexisted on the destination, so
  1157. //in reality they are not the same share.
  1158. }
  1159. else
  1160. {
  1161. //the file has disappeared from the dest. this means that it was
  1162. //indeed the same share
  1163. *pResult = 0;
  1164. }
  1165. }
  1166. CheckIdenticalSuccess:
  1167. Status = ERROR_SUCCESS;
  1168. goto CheckIdenticalEnd;
  1169. CheckIdenticalErr:
  1170. Status = GetLastError();
  1171. CheckIdenticalEnd:
  1172. if (bTempFileCreated)
  1173. DeleteFile (pwszTempPath); //ignore any errors here.
  1174. return Status;
  1175. }
  1176. //*************************************************************
  1177. //
  1178. // CheckSlash()
  1179. //
  1180. // Purpose: Checks for an ending slash and adds one if
  1181. // it is missing.
  1182. //
  1183. // Parameters: lpDir - directory
  1184. //
  1185. // Return: Pointer to the end of the string
  1186. //
  1187. // Comments:
  1188. //
  1189. // History: Date Author Comment
  1190. // 6/19/95 ericflo Created
  1191. //
  1192. //*************************************************************
  1193. LPTSTR CheckSlash (LPTSTR lpDir)
  1194. {
  1195. LPTSTR lpEnd;
  1196. lpEnd = lpDir + lstrlen(lpDir);
  1197. if (*(lpEnd - 1) != TEXT('\\')) {
  1198. *lpEnd = TEXT('\\');
  1199. lpEnd++;
  1200. *lpEnd = TEXT('\0');
  1201. }
  1202. return lpEnd;
  1203. }
  1204. //*************************************************************
  1205. //
  1206. // RegDelnodeRecurse()
  1207. //
  1208. // Purpose: Deletes a registry key and all it's subkeys / values.
  1209. // Called by RegDelnode
  1210. //
  1211. // Parameters: hKeyRoot - Root key
  1212. // lpSubKey - SubKey to delete
  1213. //
  1214. // Return: TRUE if successful
  1215. // FALSE if an error occurs
  1216. //
  1217. // Comments:
  1218. //
  1219. // History: Date Author Comment
  1220. // 10/3/95 EricFlo Created
  1221. // 11/5/98 RahulTh Copied from EricFlo's code
  1222. //
  1223. //*************************************************************
  1224. BOOL RegDelnodeRecurse (HKEY hKeyRoot, LPTSTR lpSubKey)
  1225. {
  1226. LPTSTR lpEnd;
  1227. LONG lResult;
  1228. DWORD dwSize;
  1229. TCHAR szName[MAX_PATH];
  1230. HKEY hKey;
  1231. FILETIME ftWrite;
  1232. //
  1233. // First, see if we can delete the key without having
  1234. // to recurse.
  1235. //
  1236. lResult = RegDeleteKey(hKeyRoot, lpSubKey);
  1237. if (lResult == ERROR_SUCCESS) {
  1238. return TRUE;
  1239. }
  1240. lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);
  1241. if (lResult != ERROR_SUCCESS) {
  1242. return FALSE;
  1243. }
  1244. lpEnd = CheckSlash(lpSubKey);
  1245. //
  1246. // Enumerate the keys
  1247. //
  1248. dwSize = MAX_PATH;
  1249. lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
  1250. NULL, NULL, &ftWrite);
  1251. if (lResult == ERROR_SUCCESS) {
  1252. do {
  1253. lstrcpy (lpEnd, szName);
  1254. if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) {
  1255. break;
  1256. }
  1257. //
  1258. // Enumerate again
  1259. //
  1260. dwSize = MAX_PATH;
  1261. lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
  1262. NULL, NULL, &ftWrite);
  1263. } while (lResult == ERROR_SUCCESS);
  1264. }
  1265. lpEnd--;
  1266. *lpEnd = TEXT('\0');
  1267. RegCloseKey (hKey);
  1268. //
  1269. // Try again to delete the key
  1270. //
  1271. lResult = RegDeleteKey(hKeyRoot, lpSubKey);
  1272. if (lResult == ERROR_SUCCESS) {
  1273. return TRUE;
  1274. }
  1275. return FALSE;
  1276. }
  1277. //*************************************************************
  1278. //
  1279. // RegDelnode()
  1280. //
  1281. // Purpose: Deletes a registry key and all it's subkeys / values
  1282. //
  1283. // Parameters: hKeyRoot - Root key
  1284. // lpSubKey - SubKey to delete
  1285. //
  1286. // Return: TRUE if successful
  1287. // FALSE if an error occurs
  1288. //
  1289. // Comments:
  1290. //
  1291. // History: Date Author Comment
  1292. // 10/3/95 ericflo Created
  1293. // 11/8/98 RahulTh Copied from EricFlo's code
  1294. //
  1295. //*************************************************************
  1296. BOOL RegDelnode (HKEY hKeyRoot, LPTSTR lpSubKey)
  1297. {
  1298. TCHAR szDelKey[2 * MAX_PATH];
  1299. lstrcpy (szDelKey, lpSubKey);
  1300. return RegDelnodeRecurse(hKeyRoot, szDelKey);
  1301. }
  1302. //+--------------------------------------------------------------------------
  1303. //
  1304. // Function: GetSetOwnerPrivileges
  1305. //
  1306. // Synopsis: tries to get privileges to set ownership
  1307. //
  1308. // Arguments: [in] hToken : handle to the token for which we are trying to
  1309. // obtain the privileges
  1310. //
  1311. // Returns: nothing
  1312. //
  1313. // History: 11/6/1998 RahulTh created
  1314. //
  1315. // Notes: this function never fails. It just tries its best to get all
  1316. // NT privileges. It is not guaranteed that it will get all of
  1317. // them, as it depends on the user's rights
  1318. //
  1319. //---------------------------------------------------------------------------
  1320. void GetSetOwnerPrivileges (HANDLE hToken)
  1321. {
  1322. BOOL bStatus;
  1323. DWORD Status;
  1324. DWORD Size = 0;
  1325. DWORD i;
  1326. DWORD privCount;
  1327. PTOKEN_PRIVILEGES pPrivs = NULL;
  1328. //try to get all the windows NT privileges.
  1329. for (i=0, privCount=0; *NTPrivs[i]; i++)
  1330. privCount++;
  1331. Size = sizeof (LUID_AND_ATTRIBUTES) * (privCount - 1) +
  1332. sizeof (TOKEN_PRIVILEGES);
  1333. pPrivs = (PTOKEN_PRIVILEGES) alloca (Size);
  1334. if (NULL == pPrivs)
  1335. goto GetAllPrivsEnd;
  1336. for (i=0, privCount = 0; *NTPrivs[i]; i++)
  1337. {
  1338. bStatus = LookupPrivilegeValue (NULL, NTPrivs[i],
  1339. &(pPrivs->Privileges[privCount].Luid));
  1340. if (!bStatus)
  1341. continue;
  1342. pPrivs->Privileges[privCount++].Attributes = SE_PRIVILEGE_ENABLED;
  1343. }
  1344. pPrivs->PrivilegeCount = privCount;
  1345. AdjustTokenPrivileges (hToken,
  1346. FALSE,
  1347. pPrivs,
  1348. NULL, NULL, NULL
  1349. );
  1350. GetAllPrivsEnd:
  1351. return;
  1352. }
  1353. //+--------------------------------------------------------------------------
  1354. //
  1355. // Function: SafeGetPrivateProfileStringW
  1356. //
  1357. // Synopsis: a wrapper for GetPrivateProfileString which takes care of
  1358. // all the error checks etc. so that functions that call
  1359. // this routine won't have to do it.
  1360. //
  1361. // Arguments: very similar to GetPrivateProfileStringW
  1362. //
  1363. // Returns: ERROR_SUCCESS if successful. An error code otherwise
  1364. // Also, upon successful return *pSize contains the size of
  1365. // the data copied -- not including the terminating NULL
  1366. // probably the only Error code this will ever return is
  1367. // ERROR_OUTOFMEMORY
  1368. //
  1369. // History: 11/19/1998 RahulTh created
  1370. // 12/13/2000 RahulTh made prefix happy by initializing vars.
  1371. // which anyway get set by GetPrivateProfileString
  1372. //
  1373. // Notes: if *ppwszReturnedString has been allocated memory, it might
  1374. // get freed by this function
  1375. // this function also allocates memory for the data
  1376. //
  1377. //---------------------------------------------------------------------------
  1378. DWORD SafeGetPrivateProfileStringW (
  1379. const WCHAR * pwszSection,
  1380. const WCHAR * pwszKey,
  1381. const WCHAR * pwszDefault,
  1382. WCHAR ** ppwszReturnedString,
  1383. DWORD * pSize,
  1384. const WCHAR * pwszIniFile
  1385. )
  1386. {
  1387. DWORD Status = ERROR_SUCCESS;
  1388. DWORD retVal;
  1389. *pSize = MAX_PATH;
  1390. do
  1391. {
  1392. if (*ppwszReturnedString)
  1393. delete [] *ppwszReturnedString;
  1394. *ppwszReturnedString = new WCHAR [*pSize];
  1395. if (!(*ppwszReturnedString))
  1396. {
  1397. Status = ERROR_OUTOFMEMORY;
  1398. *pSize = 0;
  1399. goto SafeGetEnd;
  1400. }
  1401. (*ppwszReturnedString)[0] = L'*';
  1402. (*ppwszReturnedString)[1] = L'\0';
  1403. retVal = GetPrivateProfileString (
  1404. pwszSection,
  1405. pwszKey,
  1406. pwszDefault,
  1407. *ppwszReturnedString,
  1408. *pSize,
  1409. pwszIniFile
  1410. );
  1411. if (*pSize - 1 != retVal)
  1412. {
  1413. *pSize = retVal;
  1414. break;
  1415. }
  1416. //if we are here, we need more memory
  1417. //try with twice of what we had
  1418. *pSize = (*pSize) * 2;
  1419. } while ( TRUE );
  1420. SafeGetEnd:
  1421. return Status;
  1422. }
  1423. //+--------------------------------------------------------------------------
  1424. //
  1425. // Function: MySidCopy
  1426. //
  1427. // Synopsis: copies sids and also allocates memory for the destination Sid
  1428. //
  1429. // Arguments: [out] ppDestSid : pointer the destination Sid;
  1430. // [in] pSourceSid : the source Sid
  1431. //
  1432. // Returns: ERROR_SUCCESS if successful. an error code otherwise
  1433. //
  1434. // History: 11/20/1998 RahulTh created
  1435. //
  1436. // Notes:
  1437. //
  1438. //---------------------------------------------------------------------------
  1439. DWORD MySidCopy (PSID * ppDestSid, PSID pSourceSid)
  1440. {
  1441. DWORD Status;
  1442. ULONG Size = 0;
  1443. *ppDestSid = 0;
  1444. if (!pSourceSid)
  1445. return ERROR_SUCCESS;
  1446. Size = RtlLengthSid (pSourceSid);
  1447. if (!Size)
  1448. return ERROR_SUCCESS;
  1449. *ppDestSid = (PSID) new BYTE [Size];
  1450. if (! (*ppDestSid))
  1451. return ERROR_OUTOFMEMORY;
  1452. return RtlCopySid (Size, *ppDestSid, pSourceSid);
  1453. }
  1454. //+--------------------------------------------------------------------------
  1455. //
  1456. // Function: GetShareStatus
  1457. //
  1458. // Synopsis: this function is a wrapper for CSCQueryFileStatus.
  1459. // basically CSCQueryFileStatus can fail if there was never a net
  1460. // use to a share. So this function tries to create a net use to
  1461. // the share if CSCQueryFileStatus fails and then re-queries the
  1462. // file status
  1463. //
  1464. // Arguments: [in] pwszShare : the share name
  1465. // [out] pdwStatus : the share Status
  1466. // [out] pdwPinCount : the pin count
  1467. // [out] pdwHints : the hints
  1468. //
  1469. // Returns: TRUE : if everything was successful.
  1470. // FALSE : if there was an error. In this case, it GetLastError()
  1471. // will contain the specific error code.
  1472. //
  1473. // History: 5/11/1999 RahulTh created
  1474. //
  1475. // Notes: it is very important that this function be passed a share name
  1476. // it does not do any parameter validation. So under no
  1477. // circumstance should this function be passed a filename.
  1478. //
  1479. //---------------------------------------------------------------------------
  1480. BOOL GetShareStatus (const WCHAR * pwszShare, DWORD * pdwStatus,
  1481. DWORD * pdwPinCount, DWORD * pdwHints)
  1482. {
  1483. NETRESOURCE nr;
  1484. DWORD dwResult;
  1485. DWORD dwErr = NO_ERROR;
  1486. BOOL bStatus;
  1487. bStatus = CSCQueryFileStatus(pwszShare, pdwStatus, pdwPinCount, pdwHints);
  1488. if (!bStatus)
  1489. {
  1490. //try to connect to the share
  1491. ZeroMemory ((PVOID) (&nr), sizeof (NETRESOURCE));
  1492. nr.dwType = RESOURCETYPE_DISK;
  1493. nr.lpLocalName = NULL;
  1494. nr.lpRemoteName = (LPTSTR) pwszShare;
  1495. nr.lpProvider = NULL;
  1496. dwErr = WNetUseConnection(NULL, &nr, NULL, NULL, 0,
  1497. NULL, NULL, &dwResult);
  1498. if (NO_ERROR == dwErr)
  1499. {
  1500. bStatus = CSCQueryFileStatus (pwszShare, pdwStatus, pdwPinCount, pdwHints);
  1501. if (!bStatus)
  1502. dwErr = GetLastError();
  1503. else
  1504. dwErr = NO_ERROR;
  1505. WNetCancelConnection2 (pwszShare, 0, FALSE);
  1506. }
  1507. else
  1508. {
  1509. bStatus = FALSE;
  1510. }
  1511. }
  1512. SetLastError(dwErr);
  1513. return bStatus;
  1514. }
  1515. //+--------------------------------------------------------------------------
  1516. //
  1517. // Function: GetCSCStatus
  1518. //
  1519. // Synopsis: given a path, finds out if it is local and if it is not
  1520. // whether it is online or offline.
  1521. //
  1522. // Arguments: [in] pwszPath : the path to the file
  1523. //
  1524. // Returns: Local/Online/Offline
  1525. //
  1526. // History: 11/20/1998 RahulTh created
  1527. //
  1528. // Notes: it is important that the path passed to this function is a
  1529. // a full path and not a relative path
  1530. //
  1531. // this function will return offline if the share is not live or
  1532. // if the share is live but CSC thinks that it is offline
  1533. //
  1534. // it will return PathLocal if the path is local or if the path
  1535. // is a network path that cannot be handled by CSC e.g. a network
  1536. // share with a pathname longer than what csc can handle or if it
  1537. // is a netware share. in this case it makes sense to return
  1538. // PathLocal because CSC won't maintain a database for these shares
  1539. // -- same as for a local path. so as far as CSC is concerned, this
  1540. // is as good as a local path.
  1541. //
  1542. //---------------------------------------------------------------------------
  1543. SHARESTATUS GetCSCStatus (const WCHAR * pwszPath)
  1544. {
  1545. WCHAR * pwszAbsPath = NULL;
  1546. WCHAR * pwszCurr = NULL;
  1547. int len;
  1548. BOOL bRetVal;
  1549. DWORD Status;
  1550. DWORD dwPinCount;
  1551. DWORD dwHints;
  1552. if (!pwszPath)
  1553. return ShareOffline; //a path must be provided
  1554. len = wcslen (pwszPath);
  1555. pwszAbsPath = (WCHAR *) alloca (sizeof (WCHAR) * (len + 1));
  1556. if (!pwszAbsPath)
  1557. {
  1558. //we are out of memory, so it is safest to return ShareOffline
  1559. //so that we can bail out of redirection.
  1560. return ShareOffline;
  1561. }
  1562. //get the absolute path
  1563. pwszCurr = _wfullpath (pwszAbsPath, pwszPath, len + 1);
  1564. if (!pwszCurr)
  1565. {
  1566. //in order for _wfullpath to fail, something really bad has to happen
  1567. //so it is best to return ShareOffline so that we can bail out of
  1568. //redirection
  1569. return ShareOffline;
  1570. }
  1571. len = wcslen (pwszAbsPath);
  1572. if (! (
  1573. (2 <= len) &&
  1574. (L'\\' == pwszAbsPath[0]) &&
  1575. (L'\\' == pwszAbsPath[1])
  1576. )
  1577. )
  1578. {
  1579. //it is a local path if it does not begin with 2 backslashes
  1580. return PathLocal;
  1581. }
  1582. //this is a UNC path; so extract the \\server\share part
  1583. pwszCurr = wcschr ( & (pwszAbsPath[2]), L'\\');
  1584. //first make sure that it is at least of the form \\server\share
  1585. //watch out for the \\server\ case
  1586. if (!pwszCurr || !pwszCurr[1])
  1587. return ShareOffline; //it is an invalid path (no share name)
  1588. //the path is of the form \\server\share
  1589. //note: the use _wfullpath automatically protects us against the \\server\\ case
  1590. pwszCurr = wcschr (&(pwszCurr[1]), L'\\');
  1591. if (pwszCurr) //if it is of the form \\server\share\...
  1592. *pwszCurr = L'\0';
  1593. //now pwszAbsPath is a share name
  1594. bRetVal = CSCCheckShareOnline (pwszAbsPath);
  1595. if (!bRetVal)
  1596. {
  1597. if (!g_bCSCEnabled)
  1598. {
  1599. //CSC has not been enabled on this machine, so the fact that
  1600. //CSC check share online failed means that the share is indeed
  1601. //offline.
  1602. return ShareOffline;
  1603. }
  1604. if (ERROR_SUCCESS != GetLastError())
  1605. {
  1606. //either there is really a problem (e.g. invalid share name) or
  1607. //it is just a share that is not handled by CSC e.g. a netware share
  1608. //or a share with a name that is longer than can be handled by CSC
  1609. //so check if the share actually exists
  1610. if (0xFFFFFFFF != GetFileAttributes(pwszAbsPath))
  1611. {
  1612. //this can still be a share that is offline since GetFileAttributes
  1613. //will return the attributes stored in the cache
  1614. Status = 0;
  1615. bRetVal = GetShareStatus (pwszAbsPath, &Status, &dwPinCount,
  1616. &dwHints);
  1617. if (! bRetVal || (! (FLAG_CSC_SHARE_STATUS_DISCONNECTED_OP & Status)))
  1618. return PathLocal; //this is simply a valid path that CSC cannot handle
  1619. else if (bRetVal &&
  1620. (FLAG_CSC_SHARE_STATUS_NO_CACHING ==
  1621. (FLAG_CSC_SHARE_STATUS_CACHING_MASK & Status)))
  1622. return PathLocal; //CSC caching is not turned on for the share.
  1623. }
  1624. }
  1625. //it is indeed an inaccessble share
  1626. return ShareOffline; //for all other cases, treat this as offline
  1627. }
  1628. else
  1629. {
  1630. if (!g_bCSCEnabled)
  1631. {
  1632. //CSC has not been enabled on this machine, so the fact that
  1633. //CSCCheckShareOnline succeed means that the share is indeed
  1634. //accessible. Since nothing can be cached, we must return
  1635. //PathLocal here.
  1636. return PathLocal;
  1637. }
  1638. //if we are here, it means that the share is live, but CSC might still
  1639. //think that it is offline.
  1640. Status = 0;
  1641. bRetVal = GetShareStatus (pwszAbsPath, &Status, &dwPinCount,
  1642. &dwHints);
  1643. if (bRetVal && (FLAG_CSC_SHARE_STATUS_DISCONNECTED_OP & Status))
  1644. return ShareOffline; //CSC thinks that the share is offline
  1645. else if (bRetVal &&
  1646. (FLAG_CSC_SHARE_STATUS_NO_CACHING ==
  1647. (FLAG_CSC_SHARE_STATUS_CACHING_MASK & Status)))
  1648. return PathLocal; //CSC caching is not turned on for the share
  1649. else if (!bRetVal)
  1650. return ShareOffline;
  1651. //in all other cases, consider the share as online since
  1652. //CSCCheckShareOnline has already returned TRUE
  1653. return ShareOnline;
  1654. }
  1655. }
  1656. //+--------------------------------------------------------------------------
  1657. //
  1658. // Function: MoveDirInCSC
  1659. //
  1660. // Synopsis: this function moves a directory within the CSC cache without
  1661. // prejudice. If the destination is a local path, it just deletes
  1662. // the source tree from the cache
  1663. //
  1664. // Arguments: [in] pwszSource : the source path
  1665. // [in] pwszDest : the dest path
  1666. // [in] pwszSkipSubdir : the directory to skip while moving
  1667. // [in] StatusFrom : the CSC status of the source path
  1668. // [in] StatusTo : the CSC status of the dest. path
  1669. // [in] bAllowRdrTimeout : if stuff needs to be deleted from the
  1670. // cache, we may not succeed immediately since
  1671. // the rdr keeps the handles to recently opened
  1672. // files open. This paramaters tells the function
  1673. // whether it needs to wait and retry
  1674. //
  1675. // Returns: nothing. it just tries its best.
  1676. //
  1677. // History: 11/21/1998 RahulTh created
  1678. //
  1679. // Notes: the value of bAllowRdrTimeout is always ignored for the
  1680. // in-cache rename operation. we always want to wait for
  1681. // the timeout.
  1682. //
  1683. //---------------------------------------------------------------------------
  1684. void MoveDirInCSC (const WCHAR * pwszSource, const WCHAR * pwszDest,
  1685. const WCHAR * pwszSkipSubdir,
  1686. SHARESTATUS StatusFrom, SHARESTATUS StatusTo,
  1687. BOOL bAllowRdrTimeoutForDel,
  1688. BOOL bAllowRdrTimeoutForRen)
  1689. {
  1690. WIN32_FIND_DATA findData;
  1691. DWORD dwFileStatus;
  1692. DWORD dwPinCount;
  1693. HANDLE hCSCFind;
  1694. DWORD dwHintFlags;
  1695. FILETIME origTime;
  1696. WCHAR * pwszPath;
  1697. WCHAR * pwszEnd;
  1698. int len;
  1699. DWORD StatusCSCRen = ERROR_SUCCESS;
  1700. if (!g_bCSCEnabled || PathLocal == StatusFrom)
  1701. return; //there is nothing to do. nothing was cached.
  1702. if (PathLocal == StatusTo)
  1703. {
  1704. //the destination is a local path, so we should just delete the
  1705. //files from the source
  1706. DeleteCSCFileTree (pwszSource, pwszSkipSubdir, bAllowRdrTimeoutForDel);
  1707. }
  1708. else
  1709. {
  1710. pwszPath = (WCHAR *) alloca (sizeof (WCHAR) * ((len = wcslen (pwszSource)) + MAX_PATH + 2));
  1711. if (!pwszPath || len <= 0)
  1712. return;
  1713. wcscpy (pwszPath, pwszSource);
  1714. pwszEnd = pwszPath + len;
  1715. if (L'\\' != pwszEnd[-1])
  1716. {
  1717. *pwszEnd++ = L'\\';
  1718. }
  1719. hCSCFind = CSCFindFirstFile (pwszSource, &findData, &dwFileStatus,
  1720. &dwPinCount, &dwHintFlags, &origTime);
  1721. if (INVALID_HANDLE_VALUE != hCSCFind)
  1722. {
  1723. do
  1724. {
  1725. if (0 != _wcsicmp (L".", findData.cFileName) &&
  1726. 0 != _wcsicmp (L"..", findData.cFileName) &&
  1727. (!pwszSkipSubdir || (0 != _wcsicmp (findData.cFileName, pwszSkipSubdir))))
  1728. {
  1729. wcscpy (pwszEnd, findData.cFileName);
  1730. if (ERROR_SUCCESS == StatusCSCRen)
  1731. {
  1732. StatusCSCRen = DoCSCRename (pwszPath, pwszDest, TRUE, bAllowRdrTimeoutForRen);
  1733. }
  1734. else
  1735. {
  1736. //here we ignore the return value since an error has already occurred.
  1737. //and we do not wish to spend any more time in timeouts in any subsequent
  1738. //rename operation.
  1739. DoCSCRename (pwszPath, pwszDest, TRUE, FALSE);
  1740. }
  1741. }
  1742. } while ( CSCFindNextFile (hCSCFind, &findData, &dwFileStatus,
  1743. &dwPinCount, &dwHintFlags, &origTime)
  1744. );
  1745. CSCFindClose (hCSCFind);
  1746. }
  1747. //merge the pin info. at the top level folder
  1748. MergePinInfo (pwszSource, pwszDest, StatusFrom, StatusTo);
  1749. }
  1750. return;
  1751. }
  1752. //+--------------------------------------------------------------------------
  1753. //
  1754. // Function: DoCSCRename
  1755. //
  1756. // Synopsis: does a file rename within the CSC cache.
  1757. //
  1758. // Arguments: [in] pwszSource : full source path
  1759. // [in] pwszDest : full path to destination directory
  1760. // [in] bOverwrite : overwrite if the file/folder exists at
  1761. // the destination
  1762. // [in] bAllowRdrTimeout : if TRUE, retry for 10 seconds on failure
  1763. // so that rdr and mem. mgr. get enough time to
  1764. // release the handles.
  1765. //
  1766. // Returns: ERROR_SUCCESS if the rename was successful.
  1767. // an error code otherwise.
  1768. //
  1769. // History: 5/26/1999 RahulTh created
  1770. //
  1771. // Notes: no validation of parameters is done. The caller is responsible
  1772. // for that
  1773. //
  1774. //---------------------------------------------------------------------------
  1775. DWORD DoCSCRename (const WCHAR * pwszSource, const WCHAR * pwszDest,
  1776. BOOL bOverwrite, BOOL bAllowRdrTimeout)
  1777. {
  1778. DWORD Status = ERROR_SUCCESS;
  1779. BOOL bStatus;
  1780. int i;
  1781. bStatus = CSCDoLocalRename (pwszSource, pwszDest, bOverwrite);
  1782. if (!bStatus)
  1783. {
  1784. Status = GetLastError();
  1785. if (ERROR_SUCCESS != Status &&
  1786. ERROR_FILE_NOT_FOUND != Status &&
  1787. ERROR_PATH_NOT_FOUND != Status &&
  1788. ERROR_INVALID_PARAMETER != Status &&
  1789. ERROR_BAD_NETPATH != Status)
  1790. {
  1791. if (bAllowRdrTimeout)
  1792. {
  1793. if (!bOverwrite && ERROR_FILE_EXISTS == Status)
  1794. {
  1795. Status = ERROR_SUCCESS;
  1796. }
  1797. else
  1798. {
  1799. for (i = 0; i < 11; i++)
  1800. {
  1801. Sleep (1000); //wait for the handle to be released
  1802. bStatus = CSCDoLocalRename (pwszSource, pwszDest, bOverwrite);
  1803. if (bStatus)
  1804. {
  1805. Status = ERROR_SUCCESS;
  1806. break;
  1807. }
  1808. }
  1809. }
  1810. }
  1811. }
  1812. else
  1813. {
  1814. Status = ERROR_SUCCESS;
  1815. }
  1816. }
  1817. if (ERROR_SUCCESS != Status)
  1818. {
  1819. DebugMsg ((DM_VERBOSE, IDS_CSCRENAME_FAIL, pwszSource, pwszDest, Status));
  1820. }
  1821. return Status;
  1822. }
  1823. //+--------------------------------------------------------------------------
  1824. //
  1825. // Function: DeleteCSCFileTree
  1826. //
  1827. // Synopsis: deletes a file tree from the CSC
  1828. //
  1829. // Arguments: [in] pwszSource : the path to the folder whose contents should
  1830. // be deleted
  1831. // [in] pwszSkipSubdir : name of the subdirectory to be skipped.
  1832. // [in] bAllowRdrTimeout : if true, makes multiple attempts to
  1833. // delete the file since the rdr may have left
  1834. // the handle open for sometime which can result
  1835. // in an ACCESS_DENIED message.
  1836. //
  1837. // Returns: ERROR_SUCCESS if the deletion was successful. An error code
  1838. // otherwise.
  1839. //
  1840. // History: 11/21/1998 RahulTh created
  1841. //
  1842. // Notes:
  1843. //
  1844. //---------------------------------------------------------------------------
  1845. DWORD DeleteCSCFileTree (const WCHAR * pwszSource, const WCHAR * pwszSkipSubdir,
  1846. BOOL bAllowRdrTimeout)
  1847. {
  1848. WIN32_FIND_DATA findData;
  1849. DWORD dwFileStatus;
  1850. DWORD dwPinCount;
  1851. HANDLE hCSCFind;
  1852. DWORD dwHintFlags;
  1853. FILETIME origTime;
  1854. WCHAR * pwszPath;
  1855. WCHAR * pwszEnd;
  1856. int len;
  1857. DWORD Status = ERROR_SUCCESS;
  1858. if (! g_bCSCEnabled)
  1859. return ERROR_SUCCESS;
  1860. pwszPath = (WCHAR *) alloca (sizeof(WCHAR) * ((len = wcslen(pwszSource)) + MAX_PATH + 2));
  1861. if (!pwszPath)
  1862. return ERROR_OUTOFMEMORY; //nothing much we can do if we run out of memory
  1863. if (len <= 0)
  1864. return ERROR_BAD_PATHNAME;
  1865. wcscpy (pwszPath, pwszSource);
  1866. pwszEnd = pwszPath + len;
  1867. if (L'\\' != pwszEnd[-1])
  1868. {
  1869. *pwszEnd++ = L'\\';
  1870. }
  1871. hCSCFind = CSCFindFirstFile (pwszSource, &findData, &dwFileStatus,
  1872. &dwPinCount, &dwHintFlags, &origTime);
  1873. if (INVALID_HANDLE_VALUE != hCSCFind)
  1874. {
  1875. do
  1876. {
  1877. if (0 != _wcsicmp (L".", findData.cFileName) &&
  1878. 0 != _wcsicmp (L"..", findData.cFileName) &&
  1879. (!pwszSkipSubdir || (0 != _wcsicmp (pwszSkipSubdir, findData.cFileName))))
  1880. {
  1881. wcscpy (pwszEnd, findData.cFileName);
  1882. if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  1883. {
  1884. if (ERROR_SUCCESS != Status)
  1885. {
  1886. //no point delaying the deletes since a delete has already
  1887. //failed.
  1888. DeleteCSCFileTree (pwszPath, NULL, FALSE);
  1889. }
  1890. else
  1891. {
  1892. Status = DeleteCSCFileTree (pwszPath, NULL, bAllowRdrTimeout);
  1893. }
  1894. }
  1895. else
  1896. {
  1897. if (ERROR_SUCCESS != Status)
  1898. {
  1899. //no point delaying the delete if we have already failed.
  1900. DeleteCSCFile (pwszPath, FALSE);
  1901. }
  1902. else
  1903. {
  1904. Status = DeleteCSCFile (pwszPath, bAllowRdrTimeout);
  1905. }
  1906. }
  1907. }
  1908. } while ( CSCFindNextFile (hCSCFind, &findData, &dwFileStatus,
  1909. &dwPinCount, &dwHintFlags, &origTime)
  1910. );
  1911. CSCFindClose (hCSCFind);
  1912. }
  1913. if (ERROR_SUCCESS != Status)
  1914. {
  1915. //no point in delaying the delete if we have already failed.
  1916. DeleteCSCFile (pwszSource, FALSE);
  1917. }
  1918. else
  1919. {
  1920. Status = DeleteCSCFile (pwszSource, bAllowRdrTimeout);
  1921. }
  1922. return Status;
  1923. }
  1924. //+--------------------------------------------------------------------------
  1925. //
  1926. // Function: DeleteCSCFile
  1927. //
  1928. // Synopsis: deletes the given path. but might make repeated attempts to
  1929. // make sure that the rdr has enough time to release any handles
  1930. // that it holds.
  1931. //
  1932. // Arguments: [in] pwszPath : the path to delete.
  1933. // [in] bAllowRdrTimeout : make multiple attempts to delete the
  1934. // file with waits in between so that the rdr has
  1935. // enough time to release any held handles.
  1936. //
  1937. // Returns: ERROR_SUCCES if the delete was successful. An error code
  1938. // otherwise.
  1939. //
  1940. // History: 5/26/1999 RahulTh created
  1941. //
  1942. // Notes:
  1943. //
  1944. //---------------------------------------------------------------------------
  1945. DWORD DeleteCSCFile (const WCHAR * pwszPath, BOOL bAllowRdrTimeout)
  1946. {
  1947. BOOL bStatus;
  1948. DWORD Status = ERROR_SUCCESS;
  1949. int i;
  1950. bStatus = CSCDelete (pwszPath);
  1951. if (!bStatus)
  1952. {
  1953. Status = GetLastError();
  1954. if (ERROR_SUCCESS != Status &&
  1955. ERROR_FILE_NOT_FOUND != Status &&
  1956. ERROR_PATH_NOT_FOUND != Status &&
  1957. ERROR_INVALID_PARAMETER != Status)
  1958. {
  1959. //this is a valid error.
  1960. //so based on the value of bAllowRdrTimeout and based
  1961. //on whether we have already failed in deleting something
  1962. //we will try repeatedly to delete the file for 10 seconds
  1963. //note: there is no point in repeatedly trying if the deletion
  1964. //failed because this was a directory which was not empty
  1965. if (bAllowRdrTimeout && ERROR_DIR_NOT_EMPTY != Status)
  1966. {
  1967. for (i = 0; i < 11; i++)
  1968. {
  1969. Sleep (1000); //wait for 1 second and try again
  1970. bStatus = CSCDelete (pwszPath);
  1971. if (bStatus)
  1972. {
  1973. Status = ERROR_SUCCESS;
  1974. break;
  1975. }
  1976. }
  1977. }
  1978. }
  1979. else
  1980. {
  1981. Status = ERROR_SUCCESS;
  1982. }
  1983. }
  1984. if (ERROR_SUCCESS != Status)
  1985. {
  1986. DebugMsg ((DM_VERBOSE, IDS_CSCDELETE_FAIL, pwszPath, Status));
  1987. }
  1988. return Status;
  1989. }
  1990. //+--------------------------------------------------------------------------
  1991. //
  1992. // Function: DisplayStatusMessage
  1993. //
  1994. // Synopsis: displays the status message in the UI when the verbose status
  1995. // is on.
  1996. //
  1997. // Arguments: resource id of the message to be displayed.
  1998. //
  1999. // Returns: nothing
  2000. //
  2001. // History: 2/25/1999 RahulTh created
  2002. //
  2003. // Notes: failures are ignored.
  2004. //
  2005. //---------------------------------------------------------------------------
  2006. void DisplayStatusMessage (UINT rid)
  2007. {
  2008. WCHAR pwszMessage [MAX_PATH];
  2009. if (!gpStatusCallback)
  2010. return;
  2011. if (!LoadString (ghDllInstance, rid, pwszMessage, MAX_PATH))
  2012. return;
  2013. gpStatusCallback (TRUE, pwszMessage);
  2014. }
  2015. //+--------------------------------------------------------------------------
  2016. //
  2017. // Function: DeleteCSCShareIfEmpty
  2018. //
  2019. // Synopsis: given a file name, this function deletes from the local cache
  2020. // the share to which the file belongs if the local cache for that
  2021. // share is empty
  2022. //
  2023. // Arguments: [in] pwszFileName : the full file name -- must be UNC
  2024. // [in] shStatus : the share status - online, offline, local etc.
  2025. //
  2026. // Returns: ERROR_SUCCESS : if successful
  2027. // a win32 error code if something goes wrong
  2028. //
  2029. // History: 4/22/1999 RahulTh created
  2030. //
  2031. // Notes: we do not have to explicitly check if the share is empty
  2032. // because if it is not, then the delete will fail anyway
  2033. //
  2034. //---------------------------------------------------------------------------
  2035. DWORD DeleteCSCShareIfEmpty (LPCTSTR pwszFileName, SHARESTATUS shStatus)
  2036. {
  2037. DWORD Status;
  2038. WCHAR * pwszFullPath = NULL;
  2039. WCHAR * pwszCurr = NULL;
  2040. int len;
  2041. WCHAR * pwszShrEnd;
  2042. if (PathLocal == shStatus || NoCSC == shStatus)
  2043. return ERROR_SUCCESS;
  2044. if (ShareOffline == shStatus)
  2045. return ERROR_CSCSHARE_OFFLINE;
  2046. len = wcslen (pwszFileName);
  2047. if (len <= 2)
  2048. return ERROR_BAD_PATHNAME;
  2049. if (pwszFileName[0] != L'\\' || pwszFileName[1] != L'\\')
  2050. return ERROR_BAD_PATHNAME;
  2051. pwszFullPath = (WCHAR *) alloca (sizeof (WCHAR) * (len + 1));
  2052. if (NULL == pwszFullPath)
  2053. return ERROR_OUTOFMEMORY;
  2054. if (NULL == _wfullpath(pwszFullPath, pwszFileName, len + 1))
  2055. return ERROR_BAD_PATHNAME; //canonicalization was unsuccessful.
  2056. // -- rarely happens
  2057. pwszShrEnd = wcschr (pwszFullPath + 2, L'\\');
  2058. if (NULL == pwszShrEnd)
  2059. return ERROR_BAD_PATHNAME; //the path does not have the share component
  2060. pwszShrEnd++;
  2061. pwszShrEnd = wcschr (pwszShrEnd, L'\\');
  2062. if (NULL == pwszShrEnd)
  2063. {
  2064. //we already have the path in \\server\share form, so just try to
  2065. //delete the share.
  2066. return DeleteCSCFile (pwszFullPath, TRUE);
  2067. }
  2068. //if we are here, then we have a path longer than just \\server\share.
  2069. //so try to delete all the way up to the share name. This is necessary
  2070. //because a user might be redirected to something like
  2071. // \\server\share\folder\%username% and we wouldn't want only \\server\share
  2072. // and \\server\share\folder to be cached.
  2073. Status = ERROR_SUCCESS;
  2074. do
  2075. {
  2076. pwszCurr = wcsrchr (pwszFullPath, L'\\');
  2077. if (NULL == pwszCurr)
  2078. break;
  2079. *pwszCurr = L'\0';
  2080. Status = DeleteCSCFile (pwszFullPath, TRUE);
  2081. //no point trying to delete the parent if deletion of this directory
  2082. //failed.
  2083. if (ERROR_SUCCESS != Status)
  2084. break;
  2085. } while ( pwszCurr > pwszShrEnd );
  2086. return Status;
  2087. }
  2088. //+--------------------------------------------------------------------------
  2089. //
  2090. // Function: MergePinInfo
  2091. //
  2092. // Synopsis: merges the pin info. from the source to destination
  2093. //
  2094. // Arguments: [in] pwszSource : the full path to the source
  2095. // [in] pwszDest : the full path to the destination
  2096. // [in] StatusFrom : CSC status of the source share
  2097. // [in] StatusTo : CSC status of the destination share
  2098. //
  2099. // Returns: ERROR_SUCCESS : if it was successful
  2100. // a Win32 error code otherwise
  2101. //
  2102. // History: 4/23/1999 RahulTh created
  2103. //
  2104. // Notes: the hint flags are a union of the source hint flags and
  2105. // destination hint flags. The pin count is the greater of the
  2106. // source and destination pin count
  2107. //
  2108. // Usually this function should only be called for folders. The
  2109. // CSC rename API handles files well. But this function will work
  2110. // for files as well.
  2111. //
  2112. //---------------------------------------------------------------------------
  2113. DWORD MergePinInfo (LPCTSTR pwszSource, LPCTSTR pwszDest,
  2114. SHARESTATUS StatusFrom, SHARESTATUS StatusTo)
  2115. {
  2116. BOOL bStatus;
  2117. DWORD dwSourceStat, dwDestStat;
  2118. DWORD dwSourcePinCount, dwDestPinCount;
  2119. DWORD dwSourceHints, dwDestHints;
  2120. DWORD Status = ERROR_SUCCESS;
  2121. DWORD i;
  2122. if (ShareOffline == StatusFrom || ShareOffline == StatusTo)
  2123. return ERROR_CSCSHARE_OFFLINE;
  2124. if (ShareOnline != StatusFrom || ShareOnline != StatusTo)
  2125. return ERROR_SUCCESS; //there is nothing to do if one of the shares
  2126. //is local.
  2127. if (!pwszSource || !pwszDest ||
  2128. 0 == wcslen(pwszSource) || 0 == wcslen(pwszDest))
  2129. return ERROR_BAD_PATHNAME;
  2130. bStatus = CSCQueryFileStatus (pwszSource, &dwSourceStat, &dwSourcePinCount,
  2131. &dwSourceHints);
  2132. if (!bStatus)
  2133. return GetLastError();
  2134. bStatus = CSCQueryFileStatus (pwszDest, &dwDestStat, &dwDestPinCount,
  2135. &dwDestHints);
  2136. if (!bStatus)
  2137. return GetLastError();
  2138. //first set the hint flags on the destination
  2139. if (dwDestHints != dwSourceHints)
  2140. {
  2141. bStatus = CSCPinFile (pwszDest, dwSourceHints, &dwDestStat,
  2142. &dwDestPinCount, &dwDestHints);
  2143. if (!bStatus)
  2144. Status = GetLastError(); //note: we do not bail out here. we try
  2145. //to at least merge the pin count before
  2146. //leaving
  2147. }
  2148. //now merge the pin count : there is nothing to be done if the destination
  2149. //pin count is greater than or equal to the source pin count
  2150. if (dwDestPinCount < dwSourcePinCount)
  2151. {
  2152. for (i = 0, bStatus = TRUE; i < (dwSourcePinCount - dwDestPinCount) &&
  2153. bStatus;
  2154. i++)
  2155. {
  2156. bStatus = CSCPinFile( pwszDest,
  2157. FLAG_CSC_HINT_COMMAND_ALTER_PIN_COUNT,
  2158. NULL, NULL, NULL );
  2159. }
  2160. if (!bStatus && ERROR_SUCCESS == Status)
  2161. Status = GetLastError();
  2162. }
  2163. return Status;
  2164. }
  2165. //+--------------------------------------------------------------------------
  2166. //
  2167. // Function: PinIfNecessary
  2168. //
  2169. // Synopsis: this function pins a file if necessary.
  2170. //
  2171. // Arguments: [in] pwszPath : full path of the file/folder to be pinned
  2172. // [in] shStatus : CSC status of the share.
  2173. //
  2174. // Returns: ERROR_SUCCESS if it was successful. An error code otherwise.
  2175. //
  2176. // History: 5/27/1999 RahulTh created
  2177. //
  2178. // Notes:
  2179. //
  2180. //---------------------------------------------------------------------------
  2181. DWORD PinIfNecessary (const WCHAR * pwszPath, SHARESTATUS shStatus)
  2182. {
  2183. DWORD Status = ERROR_SUCCESS;
  2184. BOOL bStatus;
  2185. DWORD dwStatus;
  2186. DWORD dwPinCount;
  2187. DWORD dwHints;
  2188. if (!pwszPath || !pwszPath[0])
  2189. return ERROR_BAD_NETPATH;
  2190. if (! g_bCSCEnabled)
  2191. return ERROR_SUCCESS;
  2192. if (ShareOffline == shStatus)
  2193. return ERROR_CSCSHARE_OFFLINE;
  2194. else if (PathLocal == shStatus || NoCSC == shStatus)
  2195. return ERROR_SUCCESS;
  2196. bStatus = CSCQueryFileStatus (pwszPath, &dwStatus, &dwPinCount, &dwHints);
  2197. if (!bStatus || dwPinCount <= 0)
  2198. {
  2199. bStatus = CSCPinFile (pwszPath,
  2200. FLAG_CSC_HINT_COMMAND_ALTER_PIN_COUNT,
  2201. NULL, NULL, NULL);
  2202. if (!bStatus)
  2203. Status = GetLastError();
  2204. }
  2205. return Status;
  2206. }
  2207. //+--------------------------------------------------------------------------
  2208. //
  2209. // Function: CacheDesktopIni
  2210. //
  2211. // Synopsis: some special folders use the desktop.ini file to present
  2212. // special views in explorer (e.g. My Pictures). If a folder is
  2213. // redirected to a network share and a user goes offline without
  2214. // ever looking at the folder in explorer, the desktop.ini file
  2215. // is not in the cache and therefore the special views are lost
  2216. //
  2217. // This function tries to cache the desktop.ini file as soon as
  2218. // the folder is pinned so that special views are not lost even
  2219. // if the user goes offline
  2220. //
  2221. // When the folder is unpinned, this function merely unpins the
  2222. // dekstop.ini file
  2223. //
  2224. // Arguments: [in] pwszPath : the path to the folder
  2225. // [in] shStatus : the CSC status of the share
  2226. // [in] uCommand : Pin/Unpin
  2227. //
  2228. // Returns: ERROR_SUCCESS if everything is successful.
  2229. // a win32 error code otherwise.
  2230. //
  2231. // History: 4/25/1999 RahulTh created
  2232. //
  2233. // Notes: this function should only be called after the folder has been
  2234. // successfully redirected.
  2235. //
  2236. // if desktop.ini is already pinned, this function does not try
  2237. // to pin it again.
  2238. //
  2239. //---------------------------------------------------------------------------
  2240. DWORD CacheDesktopIni (LPCTSTR pwszPath, SHARESTATUS shStatus, CSCPINCOMMAND uCommand)
  2241. {
  2242. int len;
  2243. WCHAR szDesktopIniName[] = L"desktop.ini";
  2244. WCHAR * pwszDesktopIni = NULL;
  2245. BOOL bStatus;
  2246. DWORD Status = ERROR_SUCCESS;
  2247. DWORD dwStatus;
  2248. DWORD dwPinCount;
  2249. DWORD dwHints;
  2250. if (PathLocal == shStatus)
  2251. return ERROR_SUCCESS; //nothing to be done.
  2252. if (ShareOffline == shStatus)
  2253. return ERROR_CSCSHARE_OFFLINE;
  2254. if (!pwszPath || 0 == (len = wcslen (pwszPath)))
  2255. return ERROR_BAD_PATHNAME;
  2256. pwszDesktopIni = (WCHAR *) alloca (sizeof (WCHAR) *
  2257. (len + wcslen(szDesktopIniName) + 2)); //extra char for backslash
  2258. if (NULL == pwszDesktopIni)
  2259. return ERROR_OUTOFMEMORY;
  2260. wcscpy (pwszDesktopIni, pwszPath);
  2261. if (L'\\' != pwszDesktopIni[len - 1])
  2262. {
  2263. pwszDesktopIni[len] = L'\\';
  2264. pwszDesktopIni[len + 1] = L'\0';
  2265. }
  2266. wcscat (pwszDesktopIni, szDesktopIniName);
  2267. if (PinFile == uCommand)
  2268. {
  2269. bStatus = CSCQueryFileStatus (pwszDesktopIni, &dwStatus, &dwPinCount,
  2270. &dwHints);
  2271. //pin only if it has not already been pinned.
  2272. if (!bStatus || dwPinCount <= 0)
  2273. {
  2274. if (bStatus = CSCPinFile(pwszDesktopIni,
  2275. FLAG_CSC_HINT_COMMAND_ALTER_PIN_COUNT,
  2276. NULL, NULL, NULL)
  2277. )
  2278. {
  2279. bStatus = CSCFillSparseFiles(pwszDesktopIni, FALSE,
  2280. CSCCallbackProc, 0);
  2281. }
  2282. if (!bStatus)
  2283. Status = GetLastError();
  2284. }
  2285. }
  2286. else if (UnpinFile == uCommand)
  2287. {
  2288. if (! CSCUnpinFile (pwszDesktopIni, FLAG_CSC_HINT_COMMAND_ALTER_PIN_COUNT,
  2289. NULL, NULL, NULL))
  2290. Status = GetLastError();
  2291. }
  2292. return Status;
  2293. }
  2294. //+--------------------------------------------------------------------------
  2295. //
  2296. // Function: CSCCallbackProc
  2297. //
  2298. // Synopsis: callback function for CSCFillSparseFiles
  2299. //
  2300. // Arguments: see docs
  2301. //
  2302. // Returns: see docs
  2303. //
  2304. // History: 4/26/1999 RahulTh created
  2305. //
  2306. // Notes: just returns a default value for all...
  2307. //
  2308. //---------------------------------------------------------------------------
  2309. DWORD WINAPI
  2310. CSCCallbackProc(LPCTSTR pszName,
  2311. DWORD dwStatus,
  2312. DWORD dwHintFlags,
  2313. DWORD dwPinCount,
  2314. LPWIN32_FIND_DATA pFind32,
  2315. DWORD dwReason,
  2316. DWORD dwParam1,
  2317. DWORD dwParam2,
  2318. DWORD_PTR dwContext)
  2319. {
  2320. return CSCPROC_RETURN_CONTINUE;
  2321. }
  2322. //+--------------------------------------------------------------------------
  2323. //
  2324. // Function: UpdateMyPicsShellLink
  2325. //
  2326. // Synopsis: there is no easy way to get to My Pictures if it is redirected
  2327. // independently of My Documents since the shell does not really
  2328. // address this issue. Therefore, this function is required to
  2329. // make sure that if My Pictures is not located directly under
  2330. // My Documents, there is at least a shell link pointing to the
  2331. // location of My Pictures. This function also makes sure that
  2332. // the shell link is cached in case My Documents is on a network
  2333. // share. This way, if the share were to go offline before the user
  2334. // had a chance to access My Documents, then the shell link would
  2335. // still be accessible.
  2336. //
  2337. // Also, if My Pictures is a direct descendant of My Documents,
  2338. // this function gets rid of the shell link to minimize user
  2339. // confusion.
  2340. //
  2341. // Arguments: [in] pwszMyPicsLocName : localized display name of My Pictures.
  2342. //
  2343. // Returns: S_OK : if everything went smoothly.
  2344. // an HRESULT derived from the error if there is one.
  2345. //
  2346. // History: 5/2/1999 RahulTh created
  2347. // 2/14/2001 RahulTh Fixed shortcut creation problem in free
  2348. // threaded COM by using SHCoCreateInstance
  2349. // to short-circuit COM.
  2350. //
  2351. // Notes: This function shall not be required if the shell comes up with
  2352. // an easy way to get to My Pictures even when it does not lie
  2353. // directly under My Documents.
  2354. //
  2355. //---------------------------------------------------------------------------
  2356. HRESULT UpdateMyPicsShellLinks (HANDLE hUserToken, const WCHAR * pwszMyPicsLocName)
  2357. {
  2358. WCHAR szMyDocsPath [TARGETPATHLIMIT];
  2359. WCHAR szMyPicsPath [TARGETPATHLIMIT];
  2360. WCHAR * pwszMyPicsLink = NULL;
  2361. int MyDocsLen;
  2362. int MyPicsLen;
  2363. HRESULT hr = S_OK;
  2364. SHARESTATUS MyDocsCSCStatus;
  2365. BOOL fMyPicsFollows = TRUE;
  2366. BOOL bStatus;
  2367. DWORD Status = ERROR_SUCCESS;
  2368. IShellLink * psl = NULL;
  2369. IPersistFile * ppf = NULL;
  2370. DWORD dwPinCount;
  2371. DWORD dwHints;
  2372. DWORD dwCSCState;
  2373. BOOL bComInitialized = FALSE;
  2374. //make sure that we have the user token.
  2375. if (!hUserToken)
  2376. {
  2377. hr = E_FAIL;
  2378. goto UpdateMyPicsLink_End;
  2379. }
  2380. //now get the path to My Documents
  2381. hr = SHGetFolderPath(0, CSIDL_PERSONAL | CSIDL_FLAG_DONT_VERIFY,
  2382. hUserToken, 0, szMyDocsPath);
  2383. if (S_OK != hr)
  2384. goto UpdateMyPicsLink_End;
  2385. //now make sure that we can get enough memory to store the path to the
  2386. //shell link.
  2387. MyDocsLen = wcslen (szMyDocsPath);
  2388. if (0 == MyDocsLen)
  2389. {
  2390. hr = HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
  2391. goto UpdateMyPicsLink_End;
  2392. }
  2393. pwszMyPicsLink = (WCHAR *) alloca (sizeof(WCHAR) * (MyDocsLen + wcslen(pwszMyPicsLocName) + 6));
  2394. if (NULL == pwszMyPicsLink)
  2395. {
  2396. hr = E_OUTOFMEMORY;
  2397. goto UpdateMyPicsLink_End;
  2398. }
  2399. //now make sure that the share on which My Docs exists is not offline
  2400. MyDocsCSCStatus = GetCSCStatus (szMyDocsPath);
  2401. if (ShareOffline == MyDocsCSCStatus)
  2402. {
  2403. hr = HRESULT_FROM_WIN32 (ERROR_CSCSHARE_OFFLINE);
  2404. goto UpdateMyPicsLink_End;
  2405. }
  2406. //now construct the path to the shell link to MyPics in the MyDocs folder
  2407. wcscpy (pwszMyPicsLink, szMyDocsPath);
  2408. if (L'\\' != szMyDocsPath[MyDocsLen - 1])
  2409. {
  2410. pwszMyPicsLink[MyDocsLen] = L'\\';
  2411. pwszMyPicsLink[MyDocsLen+1] = L'\0';
  2412. }
  2413. wcscat (pwszMyPicsLink, pwszMyPicsLocName);
  2414. wcscat (pwszMyPicsLink, L".lnk");
  2415. //now obtain the path to My Pictures
  2416. hr = SHGetFolderPath (0, CSIDL_MYPICTURES | CSIDL_FLAG_DONT_VERIFY,
  2417. hUserToken, 0, szMyPicsPath);
  2418. if (S_OK != hr)
  2419. goto UpdateMyPicsLink_End;
  2420. //now find out if MyPics is a descendant of My Docs.
  2421. MyPicsLen = wcslen (szMyPicsPath);
  2422. if (0 == MyPicsLen)
  2423. {
  2424. hr = HRESULT_FROM_WIN32 (ERROR_BAD_PATHNAME);
  2425. goto UpdateMyPicsLink_End;
  2426. }
  2427. if (MyPicsLen <= MyDocsLen ||
  2428. 0 != _wcsnicmp (szMyPicsPath, szMyDocsPath, MyDocsLen)
  2429. )
  2430. {
  2431. fMyPicsFollows = FALSE;
  2432. }
  2433. //delete the shell link if MyPics is supposed to follow MyDocs.
  2434. if (fMyPicsFollows)
  2435. {
  2436. Status = ERROR_SUCCESS;
  2437. if (!DeleteFile (pwszMyPicsLink))
  2438. {
  2439. Status = GetLastError();
  2440. if (ERROR_PATH_NOT_FOUND == Status ||
  2441. ERROR_FILE_NOT_FOUND == Status)
  2442. Status = ERROR_SUCCESS;
  2443. }
  2444. hr = HRESULT_FROM_WIN32 (Status);
  2445. goto UpdateMyPicsLink_End;
  2446. }
  2447. //if we are here, we need to create/update the shell link.
  2448. //
  2449. // Note: We need to use SHCoCreateInstance. This is because the GP engine
  2450. // is now freethreaded whereas the threading model for CLSID_ShellLink is
  2451. // still Apartment. This means that if we use CoCreateInstance, it will
  2452. // create the object on a COM thread in its own apartment. This means that
  2453. // it will run as LocalSystem and not impersonated as the logged on user.
  2454. // This is not what we want, especially when we are creating shortcuts on
  2455. // a network share and we need to go across the wire as the logged on user
  2456. // rather than the machine account in order to authenticate successfully.
  2457. // To get around this problem, we use SHCoCreateInstance() which is an
  2458. // internal shell API that completely short-circuits COM and calls into
  2459. // shell32's DllGetClassObject directly thus creating the objects on the
  2460. // same thread. This API is primarily for shell user *ONLY* to handle crufty
  2461. // compat stuff so use this *VERY* *VERY *SPARINGLY*. If you want to do
  2462. // anything remotely fancy with IShellLink, check with the shell team to
  2463. // make sure that it is still okay to use the SHCoCreateInstance API.
  2464. //
  2465. hr = CoInitialize (NULL);
  2466. if (SUCCEEDED(hr))
  2467. bComInitialized = TRUE;
  2468. if (SUCCEEDED (hr) || RPC_E_CHANGED_MODE == hr) // If we successfully initialized COM or if it was already initialized.
  2469. {
  2470. hr = SHCoCreateInstance(NULL,
  2471. &CLSID_ShellLink,
  2472. NULL,
  2473. IID_IShellLink,
  2474. (LPVOID*)&psl);
  2475. if (FAILED(hr))
  2476. psl = NULL; // For safety.
  2477. }
  2478. if (SUCCEEDED(hr))
  2479. hr = psl->SetPath (szMyPicsPath);
  2480. if (SUCCEEDED(hr))
  2481. hr = psl->SetDescription (pwszMyPicsLocName);
  2482. if (SUCCEEDED(hr))
  2483. hr = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
  2484. if (SUCCEEDED(hr))
  2485. {
  2486. hr = ppf->Save(pwszMyPicsLink, TRUE);
  2487. ppf->Release();
  2488. }
  2489. // Release IShellLink if necessary.
  2490. if (psl)
  2491. psl->Release();
  2492. // Uninitialize COM if necessary.
  2493. if (bComInitialized)
  2494. {
  2495. CoUninitialize();
  2496. bComInitialized = FALSE;
  2497. }
  2498. //also cache the shell link if MyDocs is redirected to a cacheable
  2499. //network share
  2500. if (SUCCEEDED(hr) && ShareOnline == MyDocsCSCStatus)
  2501. {
  2502. Status = ERROR_SUCCESS;
  2503. bStatus = TRUE;
  2504. bStatus = CSCQueryFileStatus (pwszMyPicsLink, &dwCSCState,
  2505. &dwPinCount, &dwHints);
  2506. if (bStatus)
  2507. {
  2508. if (0 == dwPinCount && (!(dwHints & FLAG_CSC_HINT_PIN_USER)))
  2509. {
  2510. if (bStatus = CSCPinFile(pwszMyPicsLink,
  2511. FLAG_CSC_HINT_COMMAND_ALTER_PIN_COUNT,
  2512. NULL, NULL, NULL)
  2513. )
  2514. {
  2515. bStatus = CSCFillSparseFiles(pwszMyPicsLink, FALSE,
  2516. CSCCallbackProc, 0);
  2517. }
  2518. }
  2519. }
  2520. if (!bStatus)
  2521. {
  2522. Status = GetLastError();
  2523. }
  2524. hr = HRESULT_FROM_WIN32 (Status);
  2525. }
  2526. UpdateMyPicsLink_End:
  2527. if (FAILED(hr))
  2528. {
  2529. DebugMsg ((DM_VERBOSE, IDS_MYPICSLINK_FAILED, GetWin32ErrFromHResult(hr)));
  2530. }
  2531. else
  2532. {
  2533. DebugMsg ((DM_VERBOSE, IDS_MYPICSLINK_SUCCEEDED, szMyDocsPath));
  2534. }
  2535. return hr;
  2536. }
  2537. //+--------------------------------------------------------------------------
  2538. //
  2539. // Function: LoadLocalizedFolderNames
  2540. //
  2541. // Synopsis: loads the localized folder names into global objects of
  2542. // CRedirectInfo class.
  2543. //
  2544. // Arguments: none.
  2545. //
  2546. // Returns: ERROR_SUCCESS if everything was successful.
  2547. // an error code otherwise.
  2548. //
  2549. // History: 5/6/1999 RahulTh created
  2550. //
  2551. // Notes: the function bails out at the first failure. Also see notes
  2552. // on CRedirectInfo::LoadLocalizedNames.
  2553. //
  2554. //---------------------------------------------------------------------------
  2555. DWORD LoadLocalizedFolderNames (void)
  2556. {
  2557. DWORD i;
  2558. DWORD Status;
  2559. for (i = 0, Status = ERROR_SUCCESS; i < (DWORD)EndRedirectable; i++)
  2560. {
  2561. Status = gPolicyResultant[i].LoadLocalizedNames();
  2562. if (ERROR_SUCCESS == Status)
  2563. Status = gAddedPolicyResultant[i].LoadLocalizedNames();
  2564. if (ERROR_SUCCESS == Status)
  2565. Status = gDeletedPolicyResultant[i].LoadLocalizedNames();
  2566. if (ERROR_SUCCESS != Status)
  2567. break;
  2568. }
  2569. return Status;
  2570. }
  2571. //+--------------------------------------------------------------------------
  2572. //
  2573. // Function: DeleteCachedConfigFiles
  2574. //
  2575. // Synopsis: deletes the locally cached copies of fdeploy.ini for GPOs
  2576. // in a list of GPOs.
  2577. //
  2578. // Arguments: [in] pGPOList : the list of GPOs
  2579. // [in] pFileDB : a filedb object containing info. about the
  2580. // location of the files etc.
  2581. //
  2582. // Returns: ERROR_SUCCESS if all the files were successfully deleted.
  2583. // an error code otherwise.
  2584. //
  2585. // History: 5/27/1999 RahulTh created
  2586. //
  2587. // Notes: this function tries its best to delete as many files as
  2588. // possible
  2589. //
  2590. //---------------------------------------------------------------------------
  2591. DWORD DeleteCachedConfigFiles (const PGROUP_POLICY_OBJECT pGPOList,
  2592. CFileDB * pFileDB)
  2593. {
  2594. DWORD Status = ERROR_SUCCESS;
  2595. WCHAR * pwszPath = NULL;
  2596. WCHAR * pwszEnd = NULL;
  2597. int len;
  2598. PGROUP_POLICY_OBJECT pGPO;
  2599. pwszPath = (WCHAR *) alloca (sizeof (WCHAR) * ((len = wcslen (pFileDB->GetLocalStoragePath())) + MAX_PATH + 2));
  2600. if (!pwszPath)
  2601. return ERROR_OUTOFMEMORY;
  2602. wcscpy (pwszPath, pFileDB->GetLocalStoragePath());
  2603. wcscat (pwszPath, L"\\");
  2604. pwszEnd = pwszPath + len + 1;
  2605. for (pGPO = pGPOList; pGPO; pGPO = pGPO->pNext)
  2606. {
  2607. wcscpy (pwszEnd, pGPO->szGPOName);
  2608. wcscat (pwszEnd, L".ini");
  2609. if (!DeleteFile (pwszPath) && ERROR_SUCCESS == Status)
  2610. {
  2611. Status = GetLastError();
  2612. if (ERROR_PATH_NOT_FOUND == Status ||
  2613. ERROR_FILE_NOT_FOUND == Status)
  2614. {
  2615. Status = ERROR_SUCCESS;
  2616. }
  2617. }
  2618. }
  2619. return Status;
  2620. }
  2621. //+--------------------------------------------------------------------------
  2622. //
  2623. // Function: SimplifyPath
  2624. //
  2625. // Synopsis: given a path, this function tries to simplify it by
  2626. // canonicalizing it and removing extra slashes by calling
  2627. // _wfullpath
  2628. //
  2629. // Arguments: [in/out] pwszPath : the given path
  2630. //
  2631. // Returns: nothing
  2632. //
  2633. // History: 5/27/1999 RahulTh created
  2634. //
  2635. // Notes: the function tries its best to simplify the path. If it fails,
  2636. // it simply returns the path supplied originally.
  2637. //
  2638. //---------------------------------------------------------------------------
  2639. void SimplifyPath (WCHAR * pwszPath)
  2640. {
  2641. size_t len;
  2642. WCHAR * pwszAbsPath;
  2643. if (!pwszPath || !pwszPath[0])
  2644. return;
  2645. len = wcslen (pwszPath);
  2646. pwszAbsPath = (WCHAR *) alloca (sizeof (WCHAR) * (len + 1));
  2647. if (!pwszAbsPath)
  2648. return;
  2649. if (NULL != _wfullpath (pwszAbsPath, pwszPath, len + 1) &&
  2650. wcslen (pwszAbsPath) <= len)
  2651. {
  2652. wcscpy (pwszPath, pwszAbsPath);
  2653. }
  2654. return;
  2655. }
  2656. //+--------------------------------------------------------------------------
  2657. //
  2658. // Function: PrecreateUnicodeIniFile
  2659. //
  2660. // Synopsis: The WritePrivateProfile* functions do not write in unicode
  2661. // unless the file already exists in unicode format. Therefore,
  2662. // this function is used to precreate a unicode file so that
  2663. // the WritePrivateProfile* functions can preserve the unicodeness.
  2664. //
  2665. // Arguments: [in] lpszFilePath : the full path of the ini file.
  2666. //
  2667. // Returns: ERROR_SUCCESS if successful.
  2668. // an error code otherwise.
  2669. //
  2670. // History: 7/9/1999 RahulTh created
  2671. //
  2672. // Notes:
  2673. //
  2674. //---------------------------------------------------------------------------
  2675. DWORD PrecreateUnicodeIniFile (LPCTSTR lpszFilePath)
  2676. {
  2677. HANDLE hFile;
  2678. WIN32_FILE_ATTRIBUTE_DATA fad;
  2679. DWORD Status = ERROR_ALREADY_EXISTS;
  2680. DWORD dwWritten;
  2681. if (!GetFileAttributesEx (lpszFilePath, GetFileExInfoStandard, &fad))
  2682. {
  2683. if (ERROR_FILE_NOT_FOUND == (Status = GetLastError()))
  2684. {
  2685. hFile = CreateFile(lpszFilePath, GENERIC_WRITE, 0, NULL,
  2686. CREATE_NEW, FILE_ATTRIBUTE_HIDDEN, NULL);
  2687. if (hFile != INVALID_HANDLE_VALUE)
  2688. {
  2689. //add the unicode mask to the beginning of the file so that
  2690. //ReadPrivate* APIs do not accidentally think that this an ANSI
  2691. //file.
  2692. WriteFile(hFile, L"\xfeff\r\n", 3 * sizeof(WCHAR), &dwWritten, NULL);
  2693. //add a few unicode characters just to be safe.
  2694. WriteFile(hFile, L" \r\n", 7 * sizeof(WCHAR),
  2695. &dwWritten, NULL);
  2696. CloseHandle(hFile);
  2697. Status = ERROR_SUCCESS;
  2698. }
  2699. else
  2700. {
  2701. Status = GetLastError();
  2702. }
  2703. }
  2704. }
  2705. return Status;
  2706. }
  2707. //+--------------------------------------------------------------------------
  2708. //
  2709. // Function: IsPathLocal
  2710. //
  2711. // Synopsis: this function determines if a given path is a local path
  2712. // or a UNC path.
  2713. //
  2714. // Arguments: pwszPath : the full path of the file.
  2715. //
  2716. // Returns: FALSE : if it is a UNC path.
  2717. // TRUE : otherwise
  2718. //
  2719. // History: 7/30/1999 RahulTh created
  2720. //
  2721. // Notes: this function basically returns TRUE unless the first
  2722. // characters of the supplied path are '\'.
  2723. //
  2724. //---------------------------------------------------------------------------
  2725. BOOL IsPathLocal (LPCWSTR pwszPath)
  2726. {
  2727. if (NULL == pwszPath || 2 > wcslen (pwszPath))
  2728. return TRUE; //assume local
  2729. if (L'\\' == pwszPath[0] && L'\\' == pwszPath[1])
  2730. return FALSE;
  2731. return TRUE; //local in all other cases.
  2732. }
  2733. //+--------------------------------------------------------------------------
  2734. //
  2735. // Function: ExpandPathSpecial
  2736. //
  2737. // Synopsis: expands a path using a given user name.
  2738. //
  2739. // Arguments: [in] pFileDB : pointer to the CFileDB object
  2740. // [in] pwszPath : pointer to the path to be expanded.
  2741. // [in] pwszUserName : the user name to be used in expansion
  2742. // [out] wszExpandedPath : the expanded path.
  2743. // [in, out] pDesiredBufferSize (optional) : on input, the size
  2744. // of the wszExpandedPath buffer. On output, the size needed
  2745. // to expand the path to that buffer. This may be NULL, in which
  2746. // case the buffer is assumed to be TARGETPATHLIMIT size.
  2747. //
  2748. // Returns: ERROR_SUCCESS : if the expanded path was successfully obtained.
  2749. // STATUS_BUFFER_TOO_SMALL : if the expanded path was too large
  2750. // to fit in the supplied buffer.
  2751. // other win32 error codes based on what goes wrong.
  2752. //
  2753. // History: 9/20/1999 RahulTh created
  2754. //
  2755. // Notes: wszExpandedPath is assumed to be a buffer containing
  2756. // TARGETPATHLIMIT characters, unlesss pDesiredBufferSize
  2757. // is specified. It is the caller's responsibility
  2758. // to allocate/free this memory. This function does not try to
  2759. // validate the memory that wszExpandedPath points to.
  2760. //
  2761. // This function is also not equipped to handle multiple
  2762. // occurrences of the %username% substring in the last path.
  2763. //
  2764. //---------------------------------------------------------------------------
  2765. DWORD ExpandPathSpecial (
  2766. CFileDB * pFileDB,
  2767. const WCHAR * pwszPath,
  2768. const WCHAR * pwszUserName,
  2769. WCHAR * wszExpandedPath,
  2770. ULONG * pDesiredBufferSize
  2771. )
  2772. {
  2773. DWORD Status = ERROR_SUCCESS;
  2774. UNICODE_STRING Path;
  2775. UNICODE_STRING ExpandedPath;
  2776. WCHAR wszLastPath [TARGETPATHLIMIT];
  2777. WCHAR * wszTemp = NULL;
  2778. WCHAR wszSuffix [TARGETPATHLIMIT];
  2779. if (TARGETPATHLIMIT <= wcslen(pwszPath))
  2780. return STATUS_BUFFER_TOO_SMALL;
  2781. wszSuffix[0] = L'\0';
  2782. wszLastPath[0] = L'\0';
  2783. wcscpy (wszLastPath, pwszPath);
  2784. //convert it to lower case. useful while searching for other strings
  2785. //within the string.
  2786. _wcslwr (wszLastPath);
  2787. //
  2788. // If the caller does not specify a user name, just use environment
  2789. // variable substitution to take care of %username% instead of
  2790. // doing it ourselves
  2791. //
  2792. if ( pwszUserName )
  2793. {
  2794. //the username has changed since the last logon. must first substitute
  2795. //the occurence of %username% if any with the supplied user name
  2796. wszTemp = wcsstr (wszLastPath, L"%username%");
  2797. }
  2798. //if the %username% string is not present, nothing more needs to be
  2799. //done. we can just go ahead and expand what we've got.
  2800. if (NULL != wszTemp)
  2801. {
  2802. //the last path contains %username%
  2803. //get the parts that appear before and after the %username% string
  2804. //reuse wszLastPath for the prefix
  2805. *wszTemp = L'\0';
  2806. wcscpy (wszSuffix, wszTemp + 10); //go past %username%
  2807. //make sure that we are not running out of space.
  2808. if (TARGETPATHLIMIT <=
  2809. wcslen (wszLastPath) +
  2810. wcslen (pwszUserName) +
  2811. wcslen (wszSuffix))
  2812. {
  2813. return STATUS_BUFFER_TOO_SMALL;
  2814. }
  2815. wcscat (wszLastPath, pwszUserName);
  2816. wcscat (wszLastPath, wszSuffix);
  2817. }
  2818. //
  2819. // In planning mode, we are only interested in %username% --
  2820. // any other environment variables can remain unexpanded since
  2821. // they may depend on local state to which we do not have access
  2822. // in planning mode.
  2823. //
  2824. if ( pFileDB->GetRsopContext()->IsPlanningModeEnabled() )
  2825. {
  2826. if ( ERROR_SUCCESS == Status )
  2827. {
  2828. lstrcpy( wszExpandedPath, wszLastPath );
  2829. }
  2830. return Status;
  2831. }
  2832. USHORT ExpandedBufferMax;
  2833. ExpandedBufferMax = (USHORT)(pDesiredBufferSize ? *pDesiredBufferSize : TARGETPATHLIMIT);
  2834. //now expand other variables in the path
  2835. Path.Length = (wcslen (wszLastPath) + 1) * sizeof (WCHAR);
  2836. Path.MaximumLength = sizeof (wszLastPath);
  2837. Path.Buffer = wszLastPath;
  2838. ExpandedPath.Length = 0;
  2839. ExpandedPath.MaximumLength = ExpandedBufferMax * sizeof (WCHAR);
  2840. ExpandedPath.Buffer = wszExpandedPath;
  2841. Status = RtlExpandEnvironmentStrings_U (
  2842. pFileDB->GetEnvBlock(),
  2843. &Path,
  2844. &ExpandedPath,
  2845. pDesiredBufferSize
  2846. );
  2847. return Status;
  2848. }
  2849. //+--------------------------------------------------------------------------
  2850. //
  2851. // Function: ExpandHomeDir
  2852. //
  2853. // Synopsis: Expands the HOMEDIR component in the path.
  2854. //
  2855. // Arguments: [in] rID : the id of the folder
  2856. // [in] pwszPath : the unexpanded path
  2857. // [in] bAllowMyPics : allow expansion of homedir for MyPics
  2858. // [out] ppwszExpandedPath : the expanded result
  2859. // [in, optional] pwszHomedir : the value of homedir to be used in substitution
  2860. //
  2861. // Returns: ERROR_SUCCESS : if successful.
  2862. // a Win32 error code otherwise.
  2863. //
  2864. // History: 3/10/2000 RahulTh created
  2865. //
  2866. // Notes: This function has the following additional restrictions:
  2867. // (a) It is a no-op for all folders except MyDocs and MyPics.
  2868. // (b) It only acts on paths that begin with
  2869. // %HOMESHARE%%HOMEPATH%
  2870. //
  2871. // Also, if the function does not return ERROR_SUCCESS, then
  2872. // *ppwszExpandedPath can be null.
  2873. //
  2874. // if the caller does not supply the homedir value for
  2875. // substitution, the value is obtained from the user object.
  2876. //
  2877. //---------------------------------------------------------------------------
  2878. DWORD ExpandHomeDir (IN REDIRECTABLE rID,
  2879. IN const WCHAR * pwszPath,
  2880. BOOL bAllowMyPics,
  2881. OUT WCHAR ** ppwszExpandedPath,
  2882. IN const WCHAR * pwszHomedir // = NULL
  2883. )
  2884. {
  2885. DWORD Status = ERROR_SUCCESS;
  2886. int len;
  2887. const WCHAR * wszSuffix;
  2888. int expandedLen;
  2889. int lenHomedir;
  2890. // First free the supplied buffer if necessary
  2891. if (*ppwszExpandedPath)
  2892. {
  2893. delete [] *ppwszExpandedPath;
  2894. *ppwszExpandedPath = NULL;
  2895. }
  2896. if (! pwszPath || L'\0' == *pwszPath)
  2897. {
  2898. Status = ERROR_BAD_PATHNAME;
  2899. goto ExpandHomeDir_End;
  2900. }
  2901. // Proceed only if the HOMEDIR component is in the right place.
  2902. if (! IsHomedirPath (rID, pwszPath, bAllowMyPics))
  2903. {
  2904. if (! HasHomeVariables (pwszPath))
  2905. {
  2906. goto ExpandHomeDir_ReturnSame;
  2907. }
  2908. else
  2909. {
  2910. // This is not a homedir path, so it is not supposed to have any home variables
  2911. Status = ERROR_BAD_PATHNAME;
  2912. goto ExpandHomeDir_End;
  2913. }
  2914. }
  2915. //
  2916. // If we are here, then we need to substitute the HOMEDIR part
  2917. // with the actual home directory. We use the current homedir value
  2918. // only if the caller hasn't already supplied us with one.
  2919. //
  2920. len = lstrlen (HOMEDIR_STR);
  2921. if (! pwszHomedir)
  2922. pwszHomedir = gUserInfo.GetHomeDir(Status);
  2923. //
  2924. // At this point, pwszHomeDir can be NULL even if Status is ERROR_SUCCESS
  2925. // This happens if the user object does not have a homedir set on it
  2926. // So we must fail even in that case.
  2927. //
  2928. if (! pwszHomedir || ERROR_SUCCESS != Status)
  2929. {
  2930. // Do not clobber status set by GetHomeDir if it had failed.
  2931. Status = (ERROR_SUCCESS == Status) ? ERROR_BAD_PATHNAME : Status;
  2932. goto ExpandHomeDir_End;
  2933. }
  2934. //
  2935. // Now we have everything we need to proceed.
  2936. // First allocate the required buffer.
  2937. //
  2938. lenHomedir = lstrlen (pwszHomedir);
  2939. expandedLen = lenHomedir + lstrlen (&pwszPath[len]);
  2940. *ppwszExpandedPath = new WCHAR [expandedLen + 1];
  2941. if (! *ppwszExpandedPath)
  2942. {
  2943. Status = ERROR_OUTOFMEMORY;
  2944. goto ExpandHomeDir_End;
  2945. }
  2946. // Generate the new path.
  2947. lstrcpy (*ppwszExpandedPath, pwszHomedir);
  2948. // Append the suffix
  2949. wszSuffix = &pwszPath[len];
  2950. // Eliminate duplicate '\' characters
  2951. if (L'\\' == (*ppwszExpandedPath)[lenHomedir - 1] && L'\\' == pwszPath[len])
  2952. wszSuffix++;
  2953. lstrcat (*ppwszExpandedPath, wszSuffix);
  2954. DebugMsg ((DM_VERBOSE, IDS_HOMEDIR_EXPANDED, pwszPath, *ppwszExpandedPath));
  2955. goto ExpandHomeDir_End;
  2956. //
  2957. // If we are here, then, there was no error, but no substitution was
  2958. // necessary either. So we just return the same path.
  2959. //
  2960. ExpandHomeDir_ReturnSame:
  2961. len = lstrlen (pwszPath);
  2962. *ppwszExpandedPath = new WCHAR [len + 1];
  2963. if (! *ppwszExpandedPath)
  2964. {
  2965. Status = ERROR_OUTOFMEMORY;
  2966. goto ExpandHomeDir_End;
  2967. }
  2968. // Copy the path.
  2969. lstrcpy (*ppwszExpandedPath, pwszPath);
  2970. Status = ERROR_SUCCESS;
  2971. ExpandHomeDir_End:
  2972. if (ERROR_SUCCESS != Status)
  2973. {
  2974. DebugMsg ((DM_VERBOSE, IDS_HOMEDIR_EXPAND_FAIL, pwszPath, Status));
  2975. }
  2976. return Status;
  2977. }
  2978. //+--------------------------------------------------------------------------
  2979. //
  2980. // Function: ExpandHomeDirPolicyPath
  2981. //
  2982. // Synopsis: Expands the HOMEDIR component in the path as specified in the
  2983. // ini file (ones that begin with \\%HOMESHARE%%HOMEPATH%)
  2984. //
  2985. // Arguments: [in] rID : the id of the folder
  2986. // [in] pwszPath : the unexpanded path
  2987. // [in] bAllowMyPics : allow expansion of homedir for MyPics
  2988. // [out] ppwszExpandedPath : the expanded result
  2989. // [in, optional] pwszHomedir : the value of homedir to be used in substitution
  2990. //
  2991. // Returns: ERROR_SUCCESS : if successful.
  2992. // a Win32 error code otherwise.
  2993. //
  2994. // History: 3/10/2000 RahulTh created
  2995. //
  2996. // Notes: This function has the following additional restrictions:
  2997. // (a) It is a no-op for all folders except MyDocs and MyPics.
  2998. // (b) It only acts on paths that begin with
  2999. // \\%HOMESHARE%%HOMEPATH% or %HOMESHARE%%HOMEPATH%
  3000. //
  3001. // Also, if the function does not return ERROR_SUCCESS, then
  3002. // *ppwszExpandedPath can be null.
  3003. //
  3004. // if the caller does not supply the homedir value for
  3005. // substitution, the value is obtained from the user object.
  3006. //
  3007. //---------------------------------------------------------------------------
  3008. DWORD ExpandHomeDirPolicyPath (IN REDIRECTABLE rID,
  3009. IN const WCHAR * pwszPath,
  3010. IN BOOL bAllowMyPics,
  3011. OUT WCHAR ** ppwszExpandedPath,
  3012. IN const WCHAR * pwszHomedir // = NULL
  3013. )
  3014. {
  3015. if (IsHomedirPolicyPath(rID, pwszPath, bAllowMyPics))
  3016. {
  3017. return ExpandHomeDir (rID,
  3018. &pwszPath[2],
  3019. bAllowMyPics,
  3020. ppwszExpandedPath,
  3021. pwszHomedir
  3022. );
  3023. }
  3024. else
  3025. {
  3026. return ExpandHomeDir (rID,
  3027. pwszPath,
  3028. bAllowMyPics,
  3029. ppwszExpandedPath,
  3030. pwszHomedir
  3031. );
  3032. }
  3033. }
  3034. //+--------------------------------------------------------------------------
  3035. //
  3036. // Function: IsHomedirPath
  3037. //
  3038. // Synopsis: determines if a given redirection destination is in the homedir.
  3039. // This means all paths that begin with %HOMESHARE%%HOMEPATH
  3040. //
  3041. // Arguments: [in] rID : The folder identifier.
  3042. // [in] pwszPath : The path.
  3043. // [in] bAllowMyPics : allow homedir paths for MyPics folder
  3044. //
  3045. // Returns: TRUE : if it is a homedir path
  3046. // FALSE: otherwise.
  3047. //
  3048. // History: 3/12/2000 RahulTh created
  3049. //
  3050. // Notes: This function returns FALSE for all folders other than
  3051. // MyDocs because that is the only folder for which redirection
  3052. // to the home directory is permitted.
  3053. //
  3054. // See additional notes about bAllowMyPics in the comments above
  3055. // IsHomedirPolicyPath
  3056. //
  3057. //---------------------------------------------------------------------------
  3058. BOOL IsHomedirPath (IN REDIRECTABLE rID, IN LPCWSTR pwszPath, BOOL bAllowMyPics)
  3059. {
  3060. int len;
  3061. if ((MyDocs != rID && (MyPics != rID || !bAllowMyPics)) ||
  3062. ! pwszPath ||
  3063. L'\0' == *pwszPath)
  3064. {
  3065. return FALSE;
  3066. }
  3067. //
  3068. // Make sure that the length of the path is longer than that of
  3069. // %HOMESHARE%%HOMEPATH. If not, there is no way that this can be
  3070. // a homedir path
  3071. //
  3072. len = lstrlen (HOMEDIR_STR);
  3073. if (lstrlen (pwszPath) < len)
  3074. return FALSE;
  3075. // If we are here, we need to compare the two strings
  3076. if (0 == _wcsnicmp (HOMEDIR_STR, pwszPath, len) &&
  3077. (L'\0' == pwszPath[len] || L'\\' == pwszPath[len]) &&
  3078. NULL == wcschr (&pwszPath[len], L'%') // no other variable names allowed
  3079. )
  3080. {
  3081. // If all the conditions above are met, then this is indeed a homedir path
  3082. return TRUE;
  3083. }
  3084. // If we are here, this cannot be a homedir path.
  3085. return FALSE;
  3086. }
  3087. //+--------------------------------------------------------------------------
  3088. //
  3089. // Function: IsHomedirPolicyPath
  3090. //
  3091. // Synopsis: determines if a given redirection destination is in the homedir.
  3092. // This means all paths that begin with \\%HOMESHARE%%HOMEPATH
  3093. //
  3094. // Arguments: [in] rID : The folder identifier.
  3095. // [in] pwszPath : The path.
  3096. // [in] bAllowMyPics : Allow MyPics to have a homedir path
  3097. //
  3098. // Returns: TRUE : if it is a homedir path as specified in the ini file
  3099. // FALSE: otherwise.
  3100. //
  3101. // History: 3/12/2000 RahulTh created
  3102. //
  3103. // Notes: This function returns FALSE for all folders other than
  3104. // MyDocs & MyPics because that is the only folder for which
  3105. // redirection to the home directory is permitted.
  3106. //
  3107. // Note: redirection to HOMEDIR is permitted for MyPics only
  3108. // if it is set to follow MyDocs. Not otherwise. That is why
  3109. // we need the third parameter.
  3110. //
  3111. //---------------------------------------------------------------------------
  3112. BOOL IsHomedirPolicyPath (IN REDIRECTABLE rID,
  3113. IN LPCWSTR pwszPath,
  3114. IN BOOL bAllowMyPics)
  3115. {
  3116. //
  3117. // It is a homedir path as specified by the policy if it begins
  3118. // with \\%HOMESHARE%%HOMEPATH%
  3119. //
  3120. if ((MyDocs == rID || (MyPics == rID && bAllowMyPics)) &&
  3121. pwszPath &&
  3122. lstrlen (pwszPath) > 2 &&
  3123. L'\\' == pwszPath[0] &&
  3124. L'\\' == pwszPath[1] )
  3125. {
  3126. return IsHomedirPath (rID, &pwszPath[2], bAllowMyPics);
  3127. }
  3128. return FALSE;
  3129. }
  3130. //+--------------------------------------------------------------------------
  3131. //
  3132. // Function: HasHomeVariables
  3133. //
  3134. // Synopsis: finds if a given string has any of the home variables
  3135. // i.e. HOMESHARE, HOMEPATH or HOMEDRIVE
  3136. //
  3137. // Arguments: [in] pwszPath : the path string
  3138. //
  3139. // Returns: TRUE: if the path has home variables.
  3140. // FALSE: otherwise
  3141. //
  3142. // History: 3/22/2000 RahulTh created
  3143. //
  3144. // Notes: This function is required because we do not wish to allow
  3145. // these variables in the path except in highly restricted
  3146. // conditions, viz. My Docs redirection that begins with
  3147. // \\%HOMESHARE%%HOMEPATH%
  3148. //
  3149. // Therefore, we need to explicitly check for the existence of
  3150. // variables in paths that don't meet these requirements.
  3151. //
  3152. //---------------------------------------------------------------------------
  3153. BOOL HasHomeVariables (IN LPCWSTR pwszPath)
  3154. {
  3155. WCHAR * pszTmp;
  3156. pszTmp = wcschr (pwszPath, L'%');
  3157. while (pszTmp)
  3158. {
  3159. if (0 == _wcsnicmp (HOMESHARE_VARIABLE, pszTmp, HOMESHARE_VARLEN) ||
  3160. 0 == _wcsnicmp (HOMEDRIVE_VARIABLE, pszTmp, HOMEDRIVE_VARLEN) ||
  3161. 0 == _wcsnicmp (HOMEPATH_VARIABLE, pszTmp, HOMEPATH_VARLEN))
  3162. {
  3163. return TRUE;
  3164. }
  3165. pszTmp = wcschr (pszTmp + 1, L'%');
  3166. }
  3167. // If we are here, we did not find any home variables in the path.
  3168. return FALSE;
  3169. }
  3170. //+--------------------------------------------------------------------------
  3171. //
  3172. // Function: GetWin32ErrFromHResult
  3173. //
  3174. // Synopsis: given an HResult, this function tries to extract the
  3175. // corresponding Win 32 error.
  3176. //
  3177. // Arguments: [in] hr : the hresult value
  3178. //
  3179. // Returns: the Win 32 Error code.
  3180. //
  3181. // History: 3/13/2000 RahulTh created
  3182. //
  3183. // Notes: if hr is not S_OK, the return value will be something other
  3184. // than ERROR_SUCCESS;
  3185. //
  3186. //---------------------------------------------------------------------------
  3187. DWORD GetWin32ErrFromHResult (IN HRESULT hr)
  3188. {
  3189. DWORD Status = ERROR_SUCCESS;
  3190. if (S_OK != hr)
  3191. {
  3192. if (FACILITY_WIN32 == HRESULT_FACILITY(hr))
  3193. {
  3194. Status = HRESULT_CODE(hr);
  3195. }
  3196. else
  3197. {
  3198. Status = GetLastError();
  3199. if (ERROR_SUCCESS == Status)
  3200. {
  3201. //an error had occurred but nobody called SetLastError
  3202. //should not be mistaken as a success.
  3203. Status = (DWORD) hr;
  3204. }
  3205. }
  3206. }
  3207. return Status;
  3208. }
  3209. //+--------------------------------------------------------------------------
  3210. //
  3211. // Function: GetExpandedPath
  3212. //
  3213. // Synopsis: given a redirected path that may contain environment variables,
  3214. // evaluates the variables to produce a fully realized path
  3215. //
  3216. // Arguments: [in] pFileDB : object containing general context information
  3217. // [in] wszSourcePath : the unexpanded path
  3218. // [in] rID : The folder identifier.
  3219. // [in] bAllowMyPics : allow homedir paths for MyPics folder
  3220. // [out] ppwszExpandedPath -- on output, the address of the
  3221. // expanded path, must be freed by the caller
  3222. //
  3223. // Returns: the Win 32 Error code.
  3224. //
  3225. // History: 5/30/2000 AdamEd created
  3226. //
  3227. // Notes:
  3228. //
  3229. //---------------------------------------------------------------------------
  3230. DWORD
  3231. GetExpandedPath(
  3232. IN CFileDB* pFileDB,
  3233. IN WCHAR* wszSourcePath,
  3234. IN int rID,
  3235. IN BOOL bAllowMyPics,
  3236. OUT WCHAR** ppwszExpandedPath)
  3237. {
  3238. WCHAR* wszDestination;
  3239. WCHAR* wszHomeDir;
  3240. DWORD Status;
  3241. const WCHAR* wszUserName;
  3242. *ppwszExpandedPath = NULL;
  3243. wszDestination = NULL;
  3244. wszHomeDir = NULL;
  3245. wszUserName = NULL;
  3246. //
  3247. // In diagnostic mode, we will end up expanding %username% and
  3248. // the %homedir% and %homepath% vars, as well as any other variables that
  3249. // are defined, but in planning mode we will only
  3250. // handle the first 3, and we only do so if a specific user account
  3251. //
  3252. if ( pFileDB->GetRsopContext()->IsPlanningModeEnabled() )
  3253. {
  3254. //
  3255. // In planning mode, the thread context is not that
  3256. // of the desired user, so we must override it
  3257. //
  3258. wszUserName = gUserInfo.GetUserName( Status );
  3259. if ( ERROR_SUCCESS != Status )
  3260. {
  3261. goto GetExpandedPath_Exit;
  3262. }
  3263. if ( ! wszUserName )
  3264. {
  3265. //
  3266. // In planning mode, GetUserName can return success
  3267. // but return a NULL username -- this means that
  3268. // the planning mode target contained only a SOM, not a user
  3269. // name, so we can accept the blank user name and cease
  3270. // further expansion attempts -- we cannot expand %username%
  3271. // or the %home%* variables if we do not have a user account. Thus,
  3272. // we use the unexpanded path.
  3273. //
  3274. wszDestination = StringDuplicate( wszSourcePath );
  3275. if ( ! wszDestination )
  3276. {
  3277. Status = ERROR_NOT_ENOUGH_MEMORY;
  3278. }
  3279. goto GetExpandedPath_Exit;
  3280. }
  3281. }
  3282. Status = ExpandHomeDirPolicyPath(
  3283. (REDIRECTABLE) rID,
  3284. wszSourcePath,
  3285. bAllowMyPics,
  3286. &wszHomeDir);
  3287. if ( ERROR_SUCCESS != Status )
  3288. {
  3289. goto GetExpandedPath_Exit;
  3290. }
  3291. USHORT cchDestination;
  3292. ULONG ReturnedLength;
  3293. NTSTATUS NtStatus;
  3294. cchDestination = TARGETPATHLIMIT;
  3295. wszDestination = new WCHAR [ cchDestination + 1 ];
  3296. if ( ! wszDestination )
  3297. {
  3298. goto GetExpandedPath_Exit;
  3299. }
  3300. ReturnedLength = cchDestination * sizeof( *wszDestination );
  3301. NtStatus = ExpandPathSpecial(
  3302. pFileDB,
  3303. wszHomeDir,
  3304. wszUserName,
  3305. wszDestination,
  3306. &ReturnedLength);
  3307. if ( STATUS_BUFFER_TOO_SMALL == NtStatus )
  3308. {
  3309. delete [] wszDestination;
  3310. wszDestination = new WCHAR [ ReturnedLength / sizeof( *wszDestination ) + 1 ];
  3311. if ( ! wszDestination )
  3312. {
  3313. Status = ERROR_NOT_ENOUGH_MEMORY;
  3314. goto GetExpandedPath_Exit;
  3315. }
  3316. NtStatus = ExpandPathSpecial(
  3317. pFileDB,
  3318. wszHomeDir,
  3319. wszUserName,
  3320. wszDestination,
  3321. &ReturnedLength);
  3322. }
  3323. if ( STATUS_SUCCESS != NtStatus )
  3324. {
  3325. Status = RtlNtStatusToDosError( NtStatus );
  3326. }
  3327. GetExpandedPath_Exit:
  3328. delete [] wszHomeDir;
  3329. if ( ERROR_SUCCESS != Status )
  3330. {
  3331. delete [] wszDestination;
  3332. }
  3333. else
  3334. {
  3335. *ppwszExpandedPath = wszDestination;
  3336. }
  3337. return Status;
  3338. }