Windows NT 4.0 source code leak
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.

1662 lines
52 KiB

4 years ago
  1. /*++
  2. Copyright (c) 1990 Microsoft Corporation
  3. Module Name:
  4. filefind.c
  5. Abstract:
  6. This module implements Win32 FindFirst/FindNext
  7. Author:
  8. Mark Lucovsky (markl) 26-Sep-1990
  9. Revision History:
  10. --*/
  11. #include "basedll.h"
  12. #define FIND_BUFFER_SIZE 4096
  13. PFINDFILE_HANDLE
  14. BasepInitializeFindFileHandle(
  15. IN HANDLE DirectoryHandle
  16. )
  17. {
  18. PFINDFILE_HANDLE FindFileHandle;
  19. FindFileHandle = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( FIND_TAG ), sizeof(*FindFileHandle));
  20. if ( FindFileHandle ) {
  21. FindFileHandle->DirectoryHandle = DirectoryHandle;
  22. FindFileHandle->FindBufferBase = NULL;
  23. FindFileHandle->FindBufferNext = NULL;
  24. FindFileHandle->FindBufferLength = 0;
  25. FindFileHandle->FindBufferValidLength = 0;
  26. if ( !NT_SUCCESS(RtlInitializeCriticalSection(&FindFileHandle->FindBufferLock)) ){
  27. RtlFreeHeap(RtlProcessHeap(), 0,FindFileHandle);
  28. FindFileHandle = NULL;
  29. }
  30. }
  31. return FindFileHandle;
  32. }
  33. HANDLE
  34. APIENTRY
  35. FindFirstFileA(
  36. LPCSTR lpFileName,
  37. LPWIN32_FIND_DATAA lpFindFileData
  38. )
  39. /*++
  40. Routine Description:
  41. ANSI thunk to FindFirstFileW
  42. --*/
  43. {
  44. HANDLE ReturnValue;
  45. PUNICODE_STRING Unicode;
  46. ANSI_STRING AnsiString;
  47. NTSTATUS Status;
  48. UNICODE_STRING UnicodeString;
  49. WIN32_FIND_DATAW FindFileData;
  50. Unicode = &NtCurrentTeb()->StaticUnicodeString;
  51. RtlInitAnsiString(&AnsiString,lpFileName);
  52. Status = Basep8BitStringToUnicodeString(Unicode,&AnsiString,FALSE);
  53. if ( !NT_SUCCESS(Status) ) {
  54. if ( Status == STATUS_BUFFER_OVERFLOW ) {
  55. SetLastError(ERROR_FILENAME_EXCED_RANGE);
  56. }
  57. else {
  58. BaseSetLastNTError(Status);
  59. }
  60. return INVALID_HANDLE_VALUE;
  61. }
  62. ReturnValue = FindFirstFileExW(
  63. (LPCWSTR)Unicode->Buffer,
  64. FindExInfoStandard,
  65. &FindFileData,
  66. FindExSearchNameMatch,
  67. NULL,
  68. 0
  69. );
  70. if ( ReturnValue == INVALID_HANDLE_VALUE ) {
  71. return ReturnValue;
  72. }
  73. RtlMoveMemory(
  74. lpFindFileData,
  75. &FindFileData,
  76. (ULONG)((ULONG)&FindFileData.cFileName[0] - (ULONG)&FindFileData)
  77. );
  78. RtlInitUnicodeString(&UnicodeString,(PWSTR)FindFileData.cFileName);
  79. AnsiString.Buffer = lpFindFileData->cFileName;
  80. AnsiString.MaximumLength = MAX_PATH;
  81. Status = BasepUnicodeStringTo8BitString(&AnsiString,&UnicodeString,FALSE);
  82. if (NT_SUCCESS(Status)) {
  83. RtlInitUnicodeString(&UnicodeString,(PWSTR)FindFileData.cAlternateFileName);
  84. AnsiString.Buffer = lpFindFileData->cAlternateFileName;
  85. AnsiString.MaximumLength = 14;
  86. Status = BasepUnicodeStringTo8BitString(&AnsiString,&UnicodeString,FALSE);
  87. }
  88. if ( !NT_SUCCESS(Status) ) {
  89. FindClose(ReturnValue);
  90. BaseSetLastNTError(Status);
  91. return INVALID_HANDLE_VALUE;
  92. }
  93. return ReturnValue;
  94. }
  95. HANDLE
  96. APIENTRY
  97. FindFirstFileW(
  98. LPCWSTR lpFileName,
  99. LPWIN32_FIND_DATAW lpFindFileData
  100. )
  101. /*++
  102. Routine Description:
  103. A directory can be searched for the first entry whose name and
  104. attributes match the specified name using FindFirstFile.
  105. This API is provided to open a find file handle and return
  106. information about the first file whose name match the specified
  107. pattern. Once established, the find file handle can be used to
  108. search for other files that match the same pattern. When the find
  109. file handle is no longer needed, it should be closed.
  110. Note that while this interface only returns information for a single
  111. file, an implementation is free to buffer several matching files
  112. that can be used to satisfy subsequent calls to FindNextFile. Also
  113. not that matches are done by name only. This API does not do
  114. attribute based matching.
  115. This API is similar to DOS (int 21h, function 4Eh), and OS/2's
  116. DosFindFirst. For portability reasons, its data structures and
  117. parameter passing is somewhat different.
  118. Arguments:
  119. lpFileName - Supplies the file name of the file to find. The file name
  120. may contain the DOS wild card characters '*' and '?'.
  121. lpFindFileData - On a successful find, this parameter returns information
  122. about the located file:
  123. WIN32_FIND_DATA Structure:
  124. DWORD dwFileAttributes - Returns the file attributes of the found
  125. file.
  126. FILETIME ftCreationTime - Returns the time that the file was created.
  127. A value of 0,0 specifies that the file system containing the
  128. file does not support this time field.
  129. FILETIME ftLastAccessTime - Returns the time that the file was last
  130. accessed. A value of 0,0 specifies that the file system
  131. containing the file does not support this time field.
  132. FILETIME ftLastWriteTime - Returns the time that the file was last
  133. written. A file systems support this time field.
  134. DWORD nFileSizeHigh - Returns the high order 32 bits of the
  135. file's size.
  136. DWORD nFileSizeLow - Returns the low order 32-bits of the file's
  137. size in bytes.
  138. UCHAR cFileName[MAX_PATH] - Returns the null terminated name of
  139. the file.
  140. Return Value:
  141. Not -1 - Returns a find first handle
  142. that can be used in a subsequent call to FindNextFile or FindClose.
  143. 0xffffffff - The operation failed. Extended error status is available
  144. using GetLastError.
  145. --*/
  146. {
  147. return FindFirstFileExW(
  148. lpFileName,
  149. FindExInfoStandard,
  150. lpFindFileData,
  151. FindExSearchNameMatch,
  152. NULL,
  153. 0
  154. );
  155. }
  156. BOOL
  157. APIENTRY
  158. FindNextFileA(
  159. HANDLE hFindFile,
  160. LPWIN32_FIND_DATAA lpFindFileData
  161. )
  162. /*++
  163. Routine Description:
  164. ANSI thunk to FindFileDataW
  165. --*/
  166. {
  167. BOOL ReturnValue;
  168. ANSI_STRING AnsiString;
  169. NTSTATUS Status;
  170. UNICODE_STRING UnicodeString;
  171. WIN32_FIND_DATAW FindFileData;
  172. ReturnValue = FindNextFileW(hFindFile,&FindFileData);
  173. if ( !ReturnValue ) {
  174. return ReturnValue;
  175. }
  176. RtlMoveMemory(
  177. lpFindFileData,
  178. &FindFileData,
  179. (ULONG)((ULONG)&FindFileData.cFileName[0] - (ULONG)&FindFileData)
  180. );
  181. RtlInitUnicodeString(&UnicodeString,(PWSTR)FindFileData.cFileName);
  182. AnsiString.Buffer = lpFindFileData->cFileName;
  183. AnsiString.MaximumLength = MAX_PATH;
  184. Status = BasepUnicodeStringTo8BitString(&AnsiString,&UnicodeString,FALSE);
  185. if (NT_SUCCESS(Status)) {
  186. RtlInitUnicodeString(&UnicodeString,(PWSTR)FindFileData.cAlternateFileName);
  187. AnsiString.Buffer = lpFindFileData->cAlternateFileName;
  188. AnsiString.MaximumLength = 14;
  189. Status = BasepUnicodeStringTo8BitString(&AnsiString,&UnicodeString,FALSE);
  190. }
  191. if ( !NT_SUCCESS(Status) ) {
  192. BaseSetLastNTError(Status);
  193. return FALSE;
  194. }
  195. return ReturnValue;
  196. }
  197. BOOL
  198. APIENTRY
  199. FindNextFileW(
  200. HANDLE hFindFile,
  201. LPWIN32_FIND_DATAW lpFindFileData
  202. )
  203. /*++
  204. Routine Description:
  205. Once a successful call has been made to FindFirstFile, subsequent
  206. matching files can be located using FindNextFile.
  207. This API is used to continue a file search from a previous call to
  208. FindFirstFile. This API returns successfully with the next file
  209. that matches the search pattern established in the original
  210. FindFirstFile call. If no file match can be found NO_MORE_FILES is
  211. returned.
  212. Note that while this interface only returns information for a single
  213. file, an implementation is free to buffer several matching files
  214. that can be used to satisfy subsequent calls to FindNextFile. Also
  215. not that matches are done by name only. This API does not do
  216. attribute based matching.
  217. This API is similar to DOS (int 21h, function 4Fh), and OS/2's
  218. DosFindNext. For portability reasons, its data structures and
  219. parameter passing is somewhat different.
  220. Arguments:
  221. hFindFile - Supplies a find file handle returned in a previous call
  222. to FindFirstFile.
  223. lpFindFileData - On a successful find, this parameter returns information
  224. about the located file.
  225. Return Value:
  226. TRUE - The operation was successful.
  227. FALSE/NULL - The operation failed. Extended error status is available
  228. using GetLastError.
  229. --*/
  230. {
  231. NTSTATUS Status;
  232. IO_STATUS_BLOCK IoStatusBlock;
  233. PFINDFILE_HANDLE FindFileHandle;
  234. BOOL ReturnValue;
  235. PFILE_BOTH_DIR_INFORMATION DirectoryInfo;
  236. if ( hFindFile == BASE_FIND_FIRST_DEVICE_HANDLE ) {
  237. BaseSetLastNTError(STATUS_NO_MORE_FILES);
  238. return FALSE;
  239. }
  240. ReturnValue = TRUE;
  241. FindFileHandle = (PFINDFILE_HANDLE)hFindFile;
  242. RtlEnterCriticalSection(&FindFileHandle->FindBufferLock);
  243. try {
  244. //
  245. // If we haven't called find next yet, then
  246. // allocate the find buffer.
  247. //
  248. if ( !FindFileHandle->FindBufferBase ) {
  249. FindFileHandle->FindBufferBase = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( FIND_TAG ), FIND_BUFFER_SIZE);
  250. if (FindFileHandle->FindBufferBase) {
  251. FindFileHandle->FindBufferNext = FindFileHandle->FindBufferBase;
  252. FindFileHandle->FindBufferLength = FIND_BUFFER_SIZE;
  253. FindFileHandle->FindBufferValidLength = 0;
  254. }
  255. else {
  256. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  257. ReturnValue = FALSE;
  258. goto leavefinally;
  259. }
  260. }
  261. //
  262. // Test to see if there is no data in the find file buffer
  263. //
  264. DirectoryInfo = (PFILE_BOTH_DIR_INFORMATION)FindFileHandle->FindBufferNext;
  265. if ( FindFileHandle->FindBufferBase == (PVOID)DirectoryInfo ) {
  266. Status = NtQueryDirectoryFile(
  267. FindFileHandle->DirectoryHandle,
  268. NULL,
  269. NULL,
  270. NULL,
  271. &IoStatusBlock,
  272. DirectoryInfo,
  273. FindFileHandle->FindBufferLength,
  274. FileBothDirectoryInformation,
  275. FALSE,
  276. NULL,
  277. FALSE
  278. );
  279. //
  280. // ***** Do a kludge hack fix for now *****
  281. //
  282. // Forget about the last, partial, entry.
  283. //
  284. if ( Status == STATUS_BUFFER_OVERFLOW ) {
  285. PULONG Ptr;
  286. PULONG PriorPtr;
  287. Ptr = (PULONG)DirectoryInfo;
  288. PriorPtr = NULL;
  289. while ( *Ptr != 0 ) {
  290. PriorPtr = Ptr;
  291. Ptr += (*Ptr / sizeof(ULONG));
  292. }
  293. if (PriorPtr != NULL) { *PriorPtr = 0; }
  294. Status = STATUS_SUCCESS;
  295. }
  296. if ( !NT_SUCCESS(Status) ) {
  297. BaseSetLastNTError(Status);
  298. ReturnValue = FALSE;
  299. goto leavefinally;
  300. }
  301. }
  302. if ( DirectoryInfo->NextEntryOffset ) {
  303. FindFileHandle->FindBufferNext = (PVOID)(
  304. (PUCHAR)DirectoryInfo + DirectoryInfo->NextEntryOffset);
  305. }
  306. else {
  307. FindFileHandle->FindBufferNext = FindFileHandle->FindBufferBase;
  308. }
  309. //
  310. // Attributes are composed of the attributes returned by NT.
  311. //
  312. lpFindFileData->dwFileAttributes = DirectoryInfo->FileAttributes;
  313. lpFindFileData->ftCreationTime = *(LPFILETIME)&DirectoryInfo->CreationTime;
  314. lpFindFileData->ftLastAccessTime = *(LPFILETIME)&DirectoryInfo->LastAccessTime;
  315. lpFindFileData->ftLastWriteTime = *(LPFILETIME)&DirectoryInfo->LastWriteTime;
  316. lpFindFileData->nFileSizeHigh = DirectoryInfo->EndOfFile.HighPart;
  317. lpFindFileData->nFileSizeLow = DirectoryInfo->EndOfFile.LowPart;
  318. RtlMoveMemory( lpFindFileData->cFileName,
  319. DirectoryInfo->FileName,
  320. DirectoryInfo->FileNameLength );
  321. lpFindFileData->cFileName[DirectoryInfo->FileNameLength >> 1] = UNICODE_NULL;
  322. RtlMoveMemory( lpFindFileData->cAlternateFileName,
  323. DirectoryInfo->ShortName,
  324. DirectoryInfo->ShortNameLength );
  325. lpFindFileData->cAlternateFileName[DirectoryInfo->ShortNameLength >> 1] = UNICODE_NULL;
  326. leavefinally:;
  327. }
  328. finally{
  329. RtlLeaveCriticalSection(&FindFileHandle->FindBufferLock);
  330. }
  331. return ReturnValue;
  332. }
  333. BOOL
  334. FindClose(
  335. HANDLE hFindFile
  336. )
  337. /*++
  338. Routine Description:
  339. A find file context created by FindFirstFile can be closed using
  340. FindClose.
  341. This API is used to inform the system that a find file handle
  342. created by FindFirstFile is no longer needed. On systems that
  343. maintain internal state for each find file context, this API informs
  344. the system that this state no longer needs to be maintained.
  345. Once this call has been made, the hFindFile may not be used in a
  346. subsequent call to either FindNextFile or FindClose.
  347. This API has no DOS counterpart, but is similar to OS/2's
  348. DosFindClose.
  349. Arguments:
  350. hFindFile - Supplies a find file handle returned in a previous call
  351. to FindFirstFile that is no longer needed.
  352. Return Value:
  353. TRUE - The operation was successful.
  354. FALSE/NULL - The operation failed. Extended error status is available
  355. using GetLastError.
  356. --*/
  357. {
  358. NTSTATUS Status;
  359. PFINDFILE_HANDLE FindFileHandle;
  360. HANDLE DirectoryHandle;
  361. if ( hFindFile == BASE_FIND_FIRST_DEVICE_HANDLE ) {
  362. return TRUE;
  363. }
  364. if ( hFindFile == INVALID_HANDLE_VALUE ) {
  365. SetLastError(ERROR_INVALID_HANDLE);
  366. return FALSE;
  367. }
  368. try {
  369. FindFileHandle = (PFINDFILE_HANDLE)hFindFile;
  370. RtlEnterCriticalSection(&FindFileHandle->FindBufferLock);
  371. DirectoryHandle = FindFileHandle->DirectoryHandle;
  372. Status = NtClose(DirectoryHandle);
  373. if ( NT_SUCCESS(Status) ) {
  374. if (FindFileHandle->FindBufferBase) {
  375. RtlFreeHeap(RtlProcessHeap(), 0,FindFileHandle->FindBufferBase);
  376. }
  377. RtlDeleteCriticalSection(&FindFileHandle->FindBufferLock);
  378. RtlFreeHeap(RtlProcessHeap(), 0,FindFileHandle);
  379. return TRUE;
  380. }
  381. else {
  382. RtlLeaveCriticalSection(&FindFileHandle->FindBufferLock);
  383. BaseSetLastNTError(Status);
  384. return FALSE;
  385. }
  386. }
  387. except ( EXCEPTION_EXECUTE_HANDLER ) {
  388. BaseSetLastNTError(GetExceptionCode());
  389. return FALSE;
  390. }
  391. }
  392. HANDLE
  393. WINAPI
  394. FindFirstFileExA(
  395. LPCSTR lpFileName,
  396. FINDEX_INFO_LEVELS fInfoLevelId,
  397. LPVOID lpFindFileData,
  398. FINDEX_SEARCH_OPS fSearchOp,
  399. LPVOID lpSearchFilter,
  400. DWORD dwAdditionalFlags
  401. )
  402. {
  403. HANDLE ReturnValue;
  404. PUNICODE_STRING Unicode;
  405. ANSI_STRING AnsiString;
  406. NTSTATUS Status;
  407. UNICODE_STRING UnicodeString;
  408. WIN32_FIND_DATAW FindFileData;
  409. LPWIN32_FIND_DATAA lpFindFileDataA;
  410. //
  411. // this code assumes that only FindExInfoStandard is supperted by ExW version
  412. // when more info levels are added, the W->A translation code needs to be modified
  413. //
  414. lpFindFileDataA = (LPWIN32_FIND_DATAA)lpFindFileData;
  415. Unicode = &NtCurrentTeb()->StaticUnicodeString;
  416. RtlInitAnsiString(&AnsiString,lpFileName);
  417. Status = Basep8BitStringToUnicodeString(Unicode,&AnsiString,FALSE);
  418. if ( !NT_SUCCESS(Status) ) {
  419. if ( Status == STATUS_BUFFER_OVERFLOW ) {
  420. SetLastError(ERROR_FILENAME_EXCED_RANGE);
  421. }
  422. else {
  423. BaseSetLastNTError(Status);
  424. }
  425. return INVALID_HANDLE_VALUE;
  426. }
  427. ReturnValue = FindFirstFileExW(
  428. (LPCWSTR)Unicode->Buffer,
  429. fInfoLevelId,
  430. (LPVOID)&FindFileData,
  431. fSearchOp,
  432. lpSearchFilter,
  433. dwAdditionalFlags
  434. );
  435. if ( ReturnValue == INVALID_HANDLE_VALUE ) {
  436. return ReturnValue;
  437. }
  438. RtlMoveMemory(
  439. lpFindFileData,
  440. &FindFileData,
  441. (ULONG)((ULONG)&FindFileData.cFileName[0] - (ULONG)&FindFileData)
  442. );
  443. RtlInitUnicodeString(&UnicodeString,(PWSTR)FindFileData.cFileName);
  444. AnsiString.Buffer = lpFindFileDataA->cFileName;
  445. AnsiString.MaximumLength = MAX_PATH;
  446. Status = BasepUnicodeStringTo8BitString(&AnsiString,&UnicodeString,FALSE);
  447. if (NT_SUCCESS(Status)) {
  448. RtlInitUnicodeString(&UnicodeString,(PWSTR)FindFileData.cAlternateFileName);
  449. AnsiString.Buffer = lpFindFileDataA->cAlternateFileName;
  450. AnsiString.MaximumLength = 14;
  451. Status = BasepUnicodeStringTo8BitString(&AnsiString,&UnicodeString,FALSE);
  452. }
  453. if ( !NT_SUCCESS(Status) ) {
  454. FindClose(ReturnValue);
  455. BaseSetLastNTError(Status);
  456. return INVALID_HANDLE_VALUE;
  457. }
  458. return ReturnValue;
  459. }
  460. HANDLE
  461. WINAPI
  462. FindFirstFileExW(
  463. LPCWSTR lpFileName,
  464. FINDEX_INFO_LEVELS fInfoLevelId,
  465. LPVOID lpFindFileData,
  466. FINDEX_SEARCH_OPS fSearchOp,
  467. LPVOID lpSearchFilter,
  468. DWORD dwAdditionalFlags
  469. )
  470. /*++
  471. Routine Description:
  472. A directory can be searched for the first entry whose name and
  473. attributes match the specified name using FindFirstFileEx.
  474. This API is provided to open a find file handle and return
  475. information about the first file whose name matchs the specified
  476. pattern. If the fSearchOp is FindExSearchNameMatch, then that is
  477. the extent of the filtering, and lpSearchFilter MUST be NULL.
  478. Otherwise, additional subfiltering is done depending on this value.
  479. FindExSearchLimitToDirectories - If this search op is specified,
  480. then lpSearchFilter MUST be NULL. For each file that
  481. matches the specified filename, and that is a directory, and
  482. entry for that file is returned.
  483. If the underlying file/io system does not support this type
  484. of filtering, the API will fail with ERROR_NOT_SUPPORTED,
  485. and the application will have to perform its own filtering
  486. by calling this API with FindExSearchNameMatch.
  487. FindExSearchLimitToDevices - If this search op is specified, the
  488. lpFileName MUST be *, and FIND_FIRST_EX_CASE_SENSITIVE
  489. must NOT be specified. Only device names are returned.
  490. Device names are generally accessible through
  491. \\.\name-of-device naming.
  492. The data returned by this API is dependent on the fInfoLevelId.
  493. FindExInfoStandard - The lpFindFileData pointer is the standard
  494. LPWIN32_FIND_DATA structure.
  495. At this time, no other information levels are supported
  496. Once established, the find file handle can be used to search for
  497. other files that match the same pattern with the same filtering
  498. being performed. When the find file handle is no longer needed, it
  499. should be closed.
  500. Note that while this interface only returns information for a single
  501. file, an implementation is free to buffer several matching files
  502. that can be used to satisfy subsequent calls to FindNextFileEx.
  503. This API is a complete superset of existing FindFirstFile. FindFirstFile
  504. could be coded as the following macro:
  505. #define FindFirstFile(a,b)
  506. FindFirstFileEx((a),FindExInfoStandard,(b),FindExSearchNameMatch,NULL,0);
  507. Arguments:
  508. lpFileName - Supplies the file name of the file to find. The file name
  509. may contain the DOS wild card characters '*' and '?'.
  510. fInfoLevelId - Supplies the info level of the returned data.
  511. lpFindFileData - Supplies a pointer whose type is dependent on the value
  512. of fInfoLevelId. This buffer returns the appropriate file data.
  513. fSearchOp - Specified the type of filtering to perform above and
  514. beyond simple wildcard matching.
  515. lpSearchFilter - If the specified fSearchOp needs structured search
  516. information, this pointer points to the search criteria. At
  517. this point in time, both search ops do not require extended
  518. search information, so this pointer is NULL.
  519. dwAdditionalFlags - Supplies additional flag values that control the
  520. search. A flag value of FIND_FIRST_EX_CASE_SENSITIVE can be
  521. used to cause case sensitive searches to occur. The default is
  522. case insensitive.
  523. Return Value:
  524. Not -1 - Returns a find first handle that can be used in a
  525. subsequent call to FindNextFileEx or FindClose.
  526. 0xffffffff - The operation failed. Extended error status is available
  527. using GetLastError.
  528. --*/
  529. {
  530. #define FIND_FIRST_EX_INVALID_FLAGS (~FIND_FIRST_EX_CASE_SENSITIVE)
  531. HANDLE hFindFile;
  532. NTSTATUS Status;
  533. OBJECT_ATTRIBUTES Obja;
  534. UNICODE_STRING FileName;
  535. UNICODE_STRING PathName;
  536. IO_STATUS_BLOCK IoStatusBlock;
  537. PFILE_BOTH_DIR_INFORMATION DirectoryInfo;
  538. struct SEARCH_BUFFER {
  539. FILE_BOTH_DIR_INFORMATION DirInfo;
  540. WCHAR Names[MAX_PATH];
  541. } Buffer;
  542. BOOLEAN TranslationStatus;
  543. RTL_RELATIVE_NAME RelativeName;
  544. PVOID FreeBuffer;
  545. UNICODE_STRING UnicodeInput;
  546. PFINDFILE_HANDLE FindFileHandle;
  547. BOOLEAN EndsInDot;
  548. LPWIN32_FIND_DATAW FindFileData;
  549. //
  550. // check parameters
  551. //
  552. if ( fInfoLevelId >= FindExInfoMaxInfoLevel ||
  553. fSearchOp >= FindExSearchLimitToDevices ||
  554. dwAdditionalFlags & FIND_FIRST_EX_INVALID_FLAGS ) {
  555. SetLastError(fSearchOp == FindExSearchLimitToDevices ? ERROR_NOT_SUPPORTED : ERROR_INVALID_PARAMETER);
  556. return INVALID_HANDLE_VALUE;
  557. }
  558. FindFileData = (LPWIN32_FIND_DATAW)lpFindFileData;
  559. RtlInitUnicodeString(&UnicodeInput,lpFileName);
  560. //
  561. // Bogus code to workaround ~* problem
  562. //
  563. if ( UnicodeInput.Buffer[(UnicodeInput.Length>>1)-1] == (WCHAR)'.' ) {
  564. EndsInDot = TRUE;
  565. }
  566. else {
  567. EndsInDot = FALSE;
  568. }
  569. TranslationStatus = RtlDosPathNameToNtPathName_U(
  570. lpFileName,
  571. &PathName,
  572. &FileName.Buffer,
  573. &RelativeName
  574. );
  575. if ( !TranslationStatus ) {
  576. SetLastError(ERROR_PATH_NOT_FOUND);
  577. return INVALID_HANDLE_VALUE;
  578. }
  579. FreeBuffer = PathName.Buffer;
  580. //
  581. // If there is a a file portion of this name, determine the length
  582. // of the name for a subsequent call to NtQueryDirectoryFile.
  583. //
  584. if (FileName.Buffer) {
  585. FileName.Length =
  586. PathName.Length - (USHORT)((ULONG)FileName.Buffer - (ULONG)PathName.Buffer);
  587. } else {
  588. FileName.Length = 0;
  589. }
  590. FileName.MaximumLength = FileName.Length;
  591. if ( RelativeName.RelativeName.Length &&
  592. RelativeName.RelativeName.Buffer != (PUCHAR)FileName.Buffer ) {
  593. if (FileName.Buffer) {
  594. PathName.Length = (USHORT)((ULONG)FileName.Buffer - (ULONG)RelativeName.RelativeName.Buffer);
  595. PathName.MaximumLength = PathName.Length;
  596. PathName.Buffer = (PWSTR)RelativeName.RelativeName.Buffer;
  597. }
  598. }
  599. else {
  600. RelativeName.ContainingDirectory = NULL;
  601. if (FileName.Buffer) {
  602. PathName.Length = (USHORT)((ULONG)FileName.Buffer - (ULONG)PathName.Buffer);
  603. PathName.MaximumLength = PathName.Length;
  604. }
  605. }
  606. if ( PathName.Buffer[(PathName.Length>>1)-2] != (WCHAR)':' ) {
  607. PathName.Length -= sizeof(UNICODE_NULL);
  608. }
  609. InitializeObjectAttributes(
  610. &Obja,
  611. &PathName,
  612. dwAdditionalFlags & FIND_FIRST_EX_CASE_SENSITIVE ? 0 : OBJ_CASE_INSENSITIVE,
  613. RelativeName.ContainingDirectory,
  614. NULL
  615. );
  616. //
  617. // Open the directory for list access
  618. //
  619. Status = NtOpenFile(
  620. &hFindFile,
  621. FILE_LIST_DIRECTORY | SYNCHRONIZE,
  622. &Obja,
  623. &IoStatusBlock,
  624. FILE_SHARE_READ | FILE_SHARE_WRITE,
  625. FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT
  626. );
  627. if ( !NT_SUCCESS(Status) ) {
  628. ULONG DeviceNameData;
  629. UNICODE_STRING DeviceName;
  630. RtlFreeHeap(RtlProcessHeap(), 0,FreeBuffer);
  631. //
  632. // The full path does not refer to a directory. This could
  633. // be a device. Check for a device name.
  634. //
  635. if ( DeviceNameData = RtlIsDosDeviceName_U(UnicodeInput.Buffer) ) {
  636. DeviceName.Length = (USHORT)(DeviceNameData & 0xffff);
  637. DeviceName.MaximumLength = (USHORT)(DeviceNameData & 0xffff);
  638. DeviceName.Buffer = (PWSTR)
  639. ((PUCHAR)UnicodeInput.Buffer + (DeviceNameData >> 16));
  640. return BaseFindFirstDevice(&DeviceName,FindFileData);
  641. }
  642. if ( Status == STATUS_OBJECT_NAME_NOT_FOUND ) {
  643. Status = STATUS_OBJECT_PATH_NOT_FOUND;
  644. }
  645. if ( Status == STATUS_OBJECT_TYPE_MISMATCH ) {
  646. Status = STATUS_OBJECT_PATH_NOT_FOUND;
  647. }
  648. BaseSetLastNTError(Status);
  649. return INVALID_HANDLE_VALUE;
  650. }
  651. //
  652. // Get an entry
  653. //
  654. //
  655. // If there is no file part, but we are not looking at a device,
  656. // then bail.
  657. //
  658. if ( !FileName.Length ) {
  659. RtlFreeHeap(RtlProcessHeap(), 0,FreeBuffer);
  660. NtClose(hFindFile);
  661. SetLastError(ERROR_FILE_NOT_FOUND);
  662. return INVALID_HANDLE_VALUE;
  663. }
  664. DirectoryInfo = &Buffer.DirInfo;
  665. //
  666. // Special case *.* to * since it is so common. Otherwise transmogrify
  667. // the input name according to the following rules:
  668. //
  669. // - Change all ? to DOS_QM
  670. // - Change all . followed by ? or * to DOS_DOT
  671. // - Change all * followed by a . into DOS_STAR
  672. //
  673. // These transmogrifications are all done in place.
  674. //
  675. if ( (FileName.Length == 6) &&
  676. (RtlCompareMemory(FileName.Buffer, L"*.*", 6) == 6) ) {
  677. FileName.Length = 2;
  678. } else {
  679. ULONG Index;
  680. WCHAR *NameChar;
  681. for ( Index = 0, NameChar = FileName.Buffer;
  682. Index < FileName.Length/sizeof(WCHAR);
  683. Index += 1, NameChar += 1) {
  684. if (Index && (*NameChar == L'.') && (*(NameChar - 1) == L'*')) {
  685. *(NameChar - 1) = DOS_STAR;
  686. }
  687. if ((*NameChar == L'?') || (*NameChar == L'*')) {
  688. if (*NameChar == L'?') { *NameChar = DOS_QM; }
  689. if (Index && *(NameChar-1) == L'.') { *(NameChar-1) = DOS_DOT; }
  690. }
  691. }
  692. if (EndsInDot && *(NameChar - 1) == L'*') { *(NameChar-1) = DOS_STAR; }
  693. }
  694. Status = NtQueryDirectoryFile(
  695. hFindFile,
  696. NULL,
  697. NULL,
  698. NULL,
  699. &IoStatusBlock,
  700. DirectoryInfo,
  701. sizeof(Buffer),
  702. FileBothDirectoryInformation,
  703. TRUE,
  704. &FileName,
  705. FALSE
  706. );
  707. RtlFreeHeap(RtlProcessHeap(), 0,FreeBuffer);
  708. if ( !NT_SUCCESS(Status) ) {
  709. NtClose(hFindFile);
  710. BaseSetLastNTError(Status);
  711. return INVALID_HANDLE_VALUE;
  712. }
  713. //
  714. // Attributes are composed of the attributes returned by NT.
  715. //
  716. FindFileData->dwFileAttributes = DirectoryInfo->FileAttributes;
  717. FindFileData->ftCreationTime = *(LPFILETIME)&DirectoryInfo->CreationTime;
  718. FindFileData->ftLastAccessTime = *(LPFILETIME)&DirectoryInfo->LastAccessTime;
  719. FindFileData->ftLastWriteTime = *(LPFILETIME)&DirectoryInfo->LastWriteTime;
  720. FindFileData->nFileSizeHigh = DirectoryInfo->EndOfFile.HighPart;
  721. FindFileData->nFileSizeLow = DirectoryInfo->EndOfFile.LowPart;
  722. RtlMoveMemory( FindFileData->cFileName,
  723. DirectoryInfo->FileName,
  724. DirectoryInfo->FileNameLength );
  725. FindFileData->cFileName[DirectoryInfo->FileNameLength >> 1] = UNICODE_NULL;
  726. RtlMoveMemory( FindFileData->cAlternateFileName,
  727. DirectoryInfo->ShortName,
  728. DirectoryInfo->ShortNameLength );
  729. FindFileData->cAlternateFileName[DirectoryInfo->ShortNameLength >> 1] = UNICODE_NULL;
  730. FindFileHandle = BasepInitializeFindFileHandle(hFindFile);
  731. if ( !FindFileHandle ) {
  732. NtClose(hFindFile);
  733. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  734. return INVALID_HANDLE_VALUE;
  735. }
  736. return (HANDLE)FindFileHandle;
  737. }
  738. HANDLE
  739. BaseFindFirstDevice(
  740. PUNICODE_STRING FileName,
  741. LPWIN32_FIND_DATAW lpFindFileData
  742. )
  743. /*++
  744. Routine Description:
  745. This function is called when find first file encounters a device
  746. name. This function returns a successful psuedo file handle and
  747. fills in the find file data with all zeros and the devic name.
  748. Arguments:
  749. FileName - Supplies the device name of the file to find.
  750. lpFindFileData - On a successful find, this parameter returns information
  751. about the located file.
  752. Return Value:
  753. Always returns a static find file handle value of
  754. BASE_FIND_FIRST_DEVICE_HANDLE
  755. --*/
  756. {
  757. RtlZeroMemory(lpFindFileData,sizeof(*lpFindFileData));
  758. lpFindFileData->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
  759. RtlMoveMemory(
  760. &lpFindFileData->cFileName[0],
  761. FileName->Buffer,
  762. FileName->MaximumLength
  763. );
  764. return BASE_FIND_FIRST_DEVICE_HANDLE;
  765. }
  766. HANDLE
  767. APIENTRY
  768. FindFirstChangeNotificationA(
  769. LPCSTR lpPathName,
  770. BOOL bWatchSubtree,
  771. DWORD dwNotifyFilter
  772. )
  773. /*++
  774. Routine Description:
  775. ANSI thunk to FindFirstChangeNotificationW
  776. --*/
  777. {
  778. PUNICODE_STRING Unicode;
  779. ANSI_STRING AnsiString;
  780. NTSTATUS Status;
  781. Unicode = &NtCurrentTeb()->StaticUnicodeString;
  782. RtlInitAnsiString(&AnsiString,lpPathName);
  783. Status = RtlAnsiStringToUnicodeString(Unicode,&AnsiString,FALSE);
  784. if ( !NT_SUCCESS(Status) ) {
  785. if ( Status == STATUS_BUFFER_OVERFLOW ) {
  786. SetLastError(ERROR_FILENAME_EXCED_RANGE);
  787. }
  788. else {
  789. BaseSetLastNTError(Status);
  790. }
  791. return FALSE;
  792. }
  793. return ( FindFirstChangeNotificationW(
  794. (LPCWSTR)Unicode->Buffer,
  795. bWatchSubtree,
  796. dwNotifyFilter
  797. )
  798. );
  799. }
  800. //
  801. // this is a hack... darrylh, please remove when NT supports null
  802. // buffers to change notify
  803. //
  804. char staticchangebuff[sizeof(FILE_NOTIFY_INFORMATION) + 16];
  805. IO_STATUS_BLOCK staticIoStatusBlock;
  806. HANDLE
  807. APIENTRY
  808. FindFirstChangeNotificationW(
  809. LPCWSTR lpPathName,
  810. BOOL bWatchSubtree,
  811. DWORD dwNotifyFilter
  812. )
  813. /*++
  814. Routine Description:
  815. This API is used to create a change notification handle and to set
  816. up the initial change notification filter conditions.
  817. If successful, this API returns a waitable notification handle. A
  818. wait on a notification handle is successful when a change matching
  819. the filter conditions occurs in the directory or subtree being
  820. watched.
  821. Once a change notification object is created and the initial filter
  822. conditions are set, the appropriate directory or subtree is
  823. monitored by the system for changes that match the specified filter
  824. conditions. When one of these changes occurs, a change notification
  825. wait is satisfied. If a change occurs without an outstanding change
  826. notification request, it is remembered by the system and will
  827. satisfy the next change notification wait.
  828. Note that this means that after a call to
  829. FindFirstChangeNotification is made, the application should wait on
  830. the notification handle before making another call to
  831. FindNextChangeNotification.
  832. Arguments:
  833. lpPathName - Supplies the pathname of the directory to be watched.
  834. This path must specify the pathname of a directory.
  835. bWatchSubtree - Supplies a boolean value that if TRUE causes the
  836. system to monitor the directory tree rooted at the specified
  837. directory. A value of FALSE causes the system to monitor only
  838. the specified directory.
  839. dwNotifyFilter - Supplies a set of flags that specify the filter
  840. conditions the system uses to satisfy a change notification
  841. wait.
  842. FILE_NOTIFY_CHANGE_FILENAME - Any file name changes that occur
  843. in a directory or subtree being watched will satisfy a
  844. change notification wait. This includes renames, creations,
  845. and deletes.
  846. FILE_NOTIFY_CHANGE_DIRNAME - Any directory name changes that occur
  847. in a directory or subtree being watched will satisfy a
  848. change notification wait. This includes directory creations
  849. and deletions.
  850. FILE_NOTIFY_CHANGE_ATTRIBUTES - Any attribute changes that occur
  851. in a directory or subtree being watched will satisfy a
  852. change notification wait.
  853. FILE_NOTIFY_CHANGE_SIZE - Any file size changes that occur in a
  854. directory or subtree being watched will satisfy a change
  855. notification wait. File sizes only cause a change when the
  856. on disk structure is updated. For systems with extensive
  857. caching this may only occur when the system cache is
  858. sufficiently flushed.
  859. FILE_NOTIFY_CHANGE_LAST_WRITE - Any last write time changes that
  860. occur in a directory or subtree being watched will satisfy a
  861. change notification wait. Last write time change only cause
  862. a change when the on disk structure is updated. For systems
  863. with extensive caching this may only occur when the system
  864. cache is sufficiently flushed.
  865. FILE_NOTIFY_CHANGE_SECURITY - Any security descriptor changes
  866. that occur in a directory or subtree being watched will
  867. satisfy a change notification wait.
  868. Return Value:
  869. Not -1 - Returns a find change notification handle. The handle is a
  870. waitable handle. A wait is satisfied when one of the filter
  871. conditions occur in a directory or subtree being monitored. The
  872. handle may also be used in a subsequent call to
  873. FindNextChangeNotify and in FindCloseChangeNotify.
  874. 0xffffffff - The operation failed. Extended error status is available
  875. using GetLastError.
  876. --*/
  877. {
  878. NTSTATUS Status;
  879. OBJECT_ATTRIBUTES Obja;
  880. HANDLE Handle;
  881. UNICODE_STRING FileName;
  882. IO_STATUS_BLOCK IoStatusBlock;
  883. BOOLEAN TranslationStatus;
  884. RTL_RELATIVE_NAME RelativeName;
  885. PVOID FreeBuffer;
  886. TranslationStatus = RtlDosPathNameToNtPathName_U(
  887. lpPathName,
  888. &FileName,
  889. NULL,
  890. &RelativeName
  891. );
  892. if ( !TranslationStatus ) {
  893. SetLastError(ERROR_PATH_NOT_FOUND);
  894. return FALSE;
  895. }
  896. FreeBuffer = FileName.Buffer;
  897. if ( RelativeName.RelativeName.Length ) {
  898. FileName = *(PUNICODE_STRING)&RelativeName.RelativeName;
  899. }
  900. else {
  901. RelativeName.ContainingDirectory = NULL;
  902. }
  903. InitializeObjectAttributes(
  904. &Obja,
  905. &FileName,
  906. OBJ_CASE_INSENSITIVE,
  907. RelativeName.ContainingDirectory,
  908. NULL
  909. );
  910. //
  911. // Open the file
  912. //
  913. Status = NtOpenFile(
  914. &Handle,
  915. (ACCESS_MASK)FILE_LIST_DIRECTORY | SYNCHRONIZE,
  916. &Obja,
  917. &IoStatusBlock,
  918. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  919. FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT
  920. );
  921. RtlFreeHeap(RtlProcessHeap(), 0,FreeBuffer);
  922. if ( !NT_SUCCESS(Status) ) {
  923. BaseSetLastNTError(Status);
  924. return INVALID_HANDLE_VALUE;
  925. }
  926. //
  927. // call change notify
  928. //
  929. Status = NtNotifyChangeDirectoryFile(
  930. Handle,
  931. NULL,
  932. NULL,
  933. NULL,
  934. &staticIoStatusBlock,
  935. staticchangebuff, // should be NULL
  936. sizeof(staticchangebuff),
  937. dwNotifyFilter,
  938. (BOOLEAN)bWatchSubtree
  939. );
  940. if ( !NT_SUCCESS(Status) ) {
  941. BaseSetLastNTError(Status);
  942. NtClose(Handle);
  943. Handle = INVALID_HANDLE_VALUE;
  944. }
  945. return Handle;
  946. }
  947. BOOL
  948. APIENTRY
  949. FindNextChangeNotification(
  950. HANDLE hChangeHandle
  951. )
  952. /*++
  953. Routine Description:
  954. This API is used to request that a change notification handle
  955. be signaled the next time the system dectects an appropriate
  956. change.
  957. If a change occurs prior to this call that would otherwise satisfy
  958. a change request, it is remembered by the system and will satisfy
  959. this request.
  960. Once a successful change notification request has been made, the
  961. application should wait on the change notification handle to
  962. pick up the change.
  963. If an application calls this API with a change request outstanding,
  964. .
  965. .
  966. FindNextChangeNotification(h);
  967. FindNextChangeNotification(h);
  968. WaitForSingleObject(h,-1);
  969. .
  970. .
  971. it may miss a change notification.
  972. Arguments:
  973. hChangeHandle - Supplies a change notification handle created
  974. using FindFirstChangeNotification.
  975. Return Value:
  976. TRUE - The change notification request was registered. A wait on the
  977. change handle should be issued to pick up the change notification.
  978. FALSE - The operation failed. Extended error status is available
  979. using GetLastError.
  980. --*/
  981. {
  982. NTSTATUS Status;
  983. BOOL ReturnValue;
  984. ReturnValue = TRUE;
  985. //
  986. // call change notify
  987. //
  988. Status = NtNotifyChangeDirectoryFile(
  989. hChangeHandle,
  990. NULL,
  991. NULL,
  992. NULL,
  993. &staticIoStatusBlock,
  994. staticchangebuff, // should be NULL
  995. sizeof(staticchangebuff),
  996. FILE_NOTIFY_CHANGE_NAME, // not needed bug workaround
  997. TRUE // not needed bug workaround
  998. );
  999. if ( !NT_SUCCESS(Status) ) {
  1000. BaseSetLastNTError(Status);
  1001. ReturnValue = FALSE;
  1002. }
  1003. return ReturnValue;
  1004. }
  1005. BOOL
  1006. APIENTRY
  1007. FindCloseChangeNotification(
  1008. HANDLE hChangeHandle
  1009. )
  1010. /*++
  1011. Routine Description:
  1012. This API is used close a change notification handle and to tell the
  1013. system to stop monitoring changes on the notification handle.
  1014. Arguments:
  1015. hChangeHandle - Supplies a change notification handle created
  1016. using FindFirstChangeNotification.
  1017. Return Value:
  1018. TRUE - The change notification handle was closed.
  1019. FALSE - The operation failed. Extended error status is available
  1020. using GetLastError.
  1021. --*/
  1022. {
  1023. return CloseHandle(hChangeHandle);
  1024. }
  1025. VOID
  1026. WINAPI
  1027. BasepIoCompletion(
  1028. PVOID ApcContext,
  1029. PIO_STATUS_BLOCK IoStatusBlock,
  1030. DWORD Reserved
  1031. );
  1032. BOOL
  1033. WINAPI
  1034. ReadDirectoryChangesW(
  1035. HANDLE hDirectory,
  1036. LPVOID lpBuffer,
  1037. DWORD nBufferLength,
  1038. BOOL bWatchSubtree,
  1039. DWORD dwNotifyFilter,
  1040. LPDWORD lpBytesReturned,
  1041. LPOVERLAPPED lpOverlapped,
  1042. LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
  1043. )
  1044. /*++
  1045. Routine Description:
  1046. This rountine allows you to read changes that occur in a directory
  1047. or a tree rooted at the specified directory. It is similar to the
  1048. FindxxxChangeNotification family of APIs, but this API can return
  1049. structured data describing the changes occuring within a directory.
  1050. This API requires the caller to pass in an open directory handle to
  1051. the directory that is to be read. The handle must be opened with
  1052. FILE_LIST_DIRECTORY acces. GENERIC_READ includes this and may also
  1053. be used. The directory may be opened for overlapped access. This
  1054. technique should be used whenever you call this API asynchronously
  1055. (by specifying and lpOverlapped value). Opening a directory in
  1056. Win32 is easy. Use CreateFile, pass in the name of a directory, and
  1057. make sure you specify FILE_FLAG_BACKUP_SEMANTICS. This will allow
  1058. you to open a directory. This technique will not force a directory
  1059. to be opened. It simply allows you to open a directory. Calling
  1060. this API with a handle to a regular file will fail.
  1061. The following code fragment illustrates how to open a directory using
  1062. CreateFile.
  1063. hDir = CreateFile(
  1064. DirName,
  1065. FILE_LIST_DIRECTORY,
  1066. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  1067. NULL,
  1068. OPEN_EXISTING,
  1069. FILE_FLAG_BACKUP_SEMANTICS | (fASync ? FILE_FLAG_OVERLAPPED : 0),
  1070. NULL
  1071. );
  1072. This API returns it's data in a structured format. The structure is defined by
  1073. the FILE_NOTIFY_INFORMATION structure.
  1074. typedef struct _FILE_NOTIFY_INFORMATION {
  1075. DWORD NextEntryOffset;
  1076. DWORD Action;
  1077. DWORD FileNameLength;
  1078. WCHAR FileName[1];
  1079. } FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;
  1080. The lpBuffer/nBufferLength parameters are used to describe the
  1081. callers buffer to the system. This API fills in the buffer either
  1082. syncronously or asynchronously depending on how the directory is
  1083. opened and the presence of the lpOverlapped parameter.
  1084. Upon successful I/O completion, a formated buffer, and number of
  1085. bytes transfered into the buffer is available to the caller. If the
  1086. number of bytes transfered is 0, this means that the system was
  1087. unable to provide detailed information on all of the changes that
  1088. occured in the directory or tree. The application should manually
  1089. compute this information by enumerating the directory or tree.
  1090. Otherwise, structured data is returned to the caller.
  1091. Each record contains:
  1092. NextEntryOffest - This is the number of bytes to be skipped to get
  1093. to the next record. A value of 0 indicates that this is the last
  1094. record.
  1095. Action - This is used to describe the type of change that occured:
  1096. FILE_ACTION_ADDED - The file was added to the directory
  1097. FILE_ACTION_REMOVED - The file was removed from the
  1098. directory
  1099. FILE_ACTION_MODIFIED - The file was modified (time change,
  1100. attribute change...)
  1101. FILE_ACTION_RENAMED_OLD_NAME - The file was renamed and this
  1102. is the old name.
  1103. FILE_ACTION_RENAMED_NEW_NAME - The file was renamed and this
  1104. is the new name.
  1105. FileNameLength - This is the length in bytes of the file name portion
  1106. of this record. Note that the file name is NOT null terminated. This
  1107. length does not include a trailing NULL.
  1108. FileName - This variable length portion of the recorn contains a file name
  1109. relative to the directory handle. The name is in the UNICODE character
  1110. format and is NOT NULL terminated.
  1111. The caller of this API can specify a filter that describes to sort
  1112. of changes that should trigger a read completion on thie directory.
  1113. The first call to this API on a directory establishes the filter to
  1114. be used for that call and all subsequent calls.
  1115. The caller can also tell the system to watch for changes in the
  1116. directory, or the entire subtree under the directory. Again, the
  1117. first call to this API establishes this condition.
  1118. This call can complete either synchronously or asynchronously.
  1119. For synchronous completion, the directory should be opened without
  1120. the FILE_FLAG_OVERLAPPED flag. The I/O will complete when the
  1121. callers buffer either fills up or overflows. When this condition
  1122. occurs, the caller may parse the returned buffer. If the
  1123. *lpBytesReturned value is 0, this means that the buffer was too
  1124. small to hold all of the changes, and the caller will have to
  1125. manually enumerate the directory or tree.
  1126. For asynchronous completion, the directory should be opened with the
  1127. FILE_FLAG_OVERLAPPED flag, and an lpOverlapped parameter must be
  1128. specified. I/O completion is returned to the caller via
  1129. GetOverlappedResult(), GetQueuedCompletionStatus(), or via an I/O
  1130. completion callback.
  1131. To receive notification via GetOverlappedResult(), DO NOT specify an
  1132. lpCompletionRoutine. Set the hEvent field of the overlapped
  1133. structure to an hEvent unique to this I/O operation. Pick up your I/O completion
  1134. using GetOverlappedResult().
  1135. To receive notification via GetQueuedCompletionSTatus(), DO NOT
  1136. specify an lpCompletionRoutine. Associate the directory handle with
  1137. a completion port using CreateIoCompletionPort(). Pick up your I/O
  1138. completion using GetQueuedCompletionStatus(). To disable a
  1139. completion packet from being used on an associated directory, set
  1140. the low order bit of the hEvent in the lpOverlapped structure and
  1141. use GetOverlappedResult().
  1142. To receive notification via an I/O completion callback, DO NOT
  1143. associate the directory with a completion port. Specify an
  1144. lpCompletionRoutine. This function will be called whenever an
  1145. outstanding I/O completes while you are in an alertable wait. If an
  1146. I/O completes, but you are not waiting, the I/O notification stays
  1147. pending and will occur when you wait. Only the thread that issues
  1148. the I/O is notified. The hEvent field of the overlapped structure is not
  1149. used by the system and may be used by the caller.
  1150. Arguments:
  1151. hDirectory - SUpplies an open handle to a directory to be watched.
  1152. The directory must be opened with FILE_LIST_DIRECTORY access.
  1153. lpBuffer - Supplies the address of a buffer that will be used to return the
  1154. results of the read. The format of this buffer is described above.
  1155. nBufferLength - Supplies the length of the buffer.
  1156. bWatchSubtree - Supplies a boolean value that if TRUE causes the
  1157. system to monitor the directory tree rooted at the specified
  1158. directory. A value of FALSE causes the system to monitor only
  1159. the specified directory.
  1160. dwNotifyFilter - Supplies a set of flags that specify the filter
  1161. conditions the system uses to satisfy a read.
  1162. FILE_NOTIFY_CHANGE_FILENAME - Any file name changes that occur
  1163. in a directory or subtree being watched will satisfy a read.
  1164. This includes renames, creations, and deletes.
  1165. FILE_NOTIFY_CHANGE_DIRNAME - Any directory name changes that
  1166. occur in a directory or subtree being watched will satisfy a
  1167. read. This includes directory creations and deletions.
  1168. FILE_NOTIFY_CHANGE_ATTRIBUTES - Any attribute changes that occur
  1169. in a directory or subtree being watched will satisfy a
  1170. read.
  1171. FILE_NOTIFY_CHANGE_SIZE - Any file size changes that occur in a
  1172. directory or subtree being watched will satisfy a read.
  1173. File sizes only cause a change when the on disk structure is
  1174. updated. For systems with extensive caching this may only
  1175. occur when the system cache is sufficiently flushed.
  1176. FILE_NOTIFY_CHANGE_LAST_WRITE - Any last write time changes that
  1177. occur in a directory or subtree being watched will satisfy a
  1178. read. Last write time change only cause a change when the
  1179. on disk structure is updated. For systems with extensive
  1180. caching this may only occur when the system cache is
  1181. sufficiently flushed.
  1182. FILE_NOTIFY_CHANGE_LAST_ACCESS - Any last access time changes that
  1183. occur in a directory or subtree being watched will satisfy a
  1184. read. Last access time change only cause a change when the
  1185. on disk structure is updated. For systems with extensive
  1186. caching this may only occur when the system cache is
  1187. sufficiently flushed.
  1188. FILE_NOTIFY_CHANGE_CREATION - Any creation time changes that
  1189. occur in a directory or subtree being watched will satisfy a
  1190. read. Last creation time change only cause a change when the
  1191. on disk structure is updated. For systems with extensive
  1192. caching this may only occur when the system cache is
  1193. sufficiently flushed.
  1194. FILE_NOTIFY_CHANGE_SECURITY - Any security descriptor changes
  1195. that occur in a directory or subtree being watched will
  1196. satisfy a read.
  1197. lpBytesReturned - For synchronous calls, this returns the number of
  1198. bytes transfered into the buffer. A successful call coupled
  1199. with a value of 0 means that the buffer was too small, and the
  1200. caller must manually enumerate the directory/tree. For
  1201. asynchronous calls, this value is undefined. The system does
  1202. not attempt to store anything here. The caller must use an
  1203. asynchronous notification technique to pick up I/O completion
  1204. and number of bytes transfered.
  1205. lpOverlapped - Supplies an overlapped structure to be used in
  1206. conjunction with asynchronous I/O completion notification. The
  1207. offset fields of this structure are not used. Using this on a
  1208. directory that was not opened with FILE_FLAG_OVERLAPPED is
  1209. undefined.
  1210. lpCompletionRoutine - Supplies the address of a completion routine
  1211. that is called when this I/O completes, AND the thread that
  1212. issues the I/O enters an alertable wait. The threads wait will
  1213. be interrupted with a return code of WAIT_IO_COMPLETION, and
  1214. this I/O completion routine will be called. The routine is
  1215. passed the error code of the operation, the number of bytes
  1216. transfered, and the address of the lpOverlapped structure used
  1217. in the call. An error will occur if this parameter is specified
  1218. on a directory handle that is associated with a completion port.
  1219. Return Value:
  1220. TRUE - For synchronous calls, the operation succeeded.
  1221. lpBytesReturned is the number of bytes transferred into your
  1222. buffer. A value of 0 means that your buffer was too small to
  1223. hold all of the changes that occured and that you need to
  1224. enumerate the directory yourself to see the changes. For
  1225. asyncronous calls, the operation was queued successfully.
  1226. Results will be delivered using asynch I/O notification
  1227. (GetOverlappedResult(), GetQueuedCompletionStatus(), or your
  1228. completion callback routine).
  1229. FALSE - An error occured. GetLastError() can be used to obtain detailed
  1230. error status.
  1231. --*/
  1232. {
  1233. NTSTATUS Status;
  1234. BOOL ReturnValue;
  1235. IO_STATUS_BLOCK IoStatusBlock;
  1236. HANDLE Event;
  1237. PIO_APC_ROUTINE ApcRoutine;
  1238. PVOID ApcContext;
  1239. ReturnValue = TRUE;
  1240. if ( ARGUMENT_PRESENT(lpOverlapped) ) {
  1241. if ( ARGUMENT_PRESENT(lpCompletionRoutine) ) {
  1242. //
  1243. // completion is via APC routine
  1244. //
  1245. Event = NULL;
  1246. ApcRoutine = BasepIoCompletion;
  1247. ApcContext = (PVOID) lpCompletionRoutine;
  1248. }
  1249. else {
  1250. //
  1251. // completion is via completion port or get overlapped result
  1252. //
  1253. Event = lpOverlapped->hEvent;
  1254. ApcRoutine = NULL;
  1255. ApcContext = (DWORD)lpOverlapped->hEvent & 1 ? NULL : lpOverlapped;
  1256. }
  1257. lpOverlapped->Internal = (DWORD)STATUS_PENDING;
  1258. Status = NtNotifyChangeDirectoryFile(
  1259. hDirectory,
  1260. Event,
  1261. ApcRoutine,
  1262. ApcContext,
  1263. (PIO_STATUS_BLOCK)&lpOverlapped->Internal,
  1264. lpBuffer,
  1265. nBufferLength,
  1266. dwNotifyFilter,
  1267. (BOOLEAN)bWatchSubtree
  1268. );
  1269. //
  1270. // Anything other than an error means that I/O completion will
  1271. // occur and caller only gets return data via completion mechanism
  1272. //
  1273. if ( NT_ERROR(Status) ) {
  1274. BaseSetLastNTError(Status);
  1275. ReturnValue = FALSE;
  1276. }
  1277. }
  1278. else {
  1279. Status = NtNotifyChangeDirectoryFile(
  1280. hDirectory,
  1281. NULL,
  1282. NULL,
  1283. NULL,
  1284. &IoStatusBlock,
  1285. lpBuffer,
  1286. nBufferLength,
  1287. dwNotifyFilter,
  1288. (BOOLEAN)bWatchSubtree
  1289. );
  1290. if ( Status == STATUS_PENDING) {
  1291. //
  1292. // Operation must complete before return & IoStatusBlock destroyed
  1293. //
  1294. Status = NtWaitForSingleObject( hDirectory, FALSE, NULL );
  1295. if ( NT_SUCCESS(Status)) {
  1296. Status = IoStatusBlock.Status;
  1297. }
  1298. }
  1299. if ( NT_SUCCESS(Status) ) {
  1300. *lpBytesReturned = IoStatusBlock.Information;
  1301. }
  1302. else {
  1303. BaseSetLastNTError(Status);
  1304. ReturnValue = FALSE;
  1305. }
  1306. }
  1307. return ReturnValue;
  1308. }