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.

2155 lines
67 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. smbsrch.c
  5. Abstract:
  6. This module contains routines for processing the Search SMB.
  7. Author:
  8. David Treadwell (davidtr) 13-Feb-1990
  9. Revision History:
  10. --*/
  11. #include "precomp.h"
  12. #include "smbsrch.tmh"
  13. #pragma hdrstop
  14. #define BugCheckFileId SRV_FILE_SMBSRCH
  15. #define VOLUME_BUFFER_SIZE \
  16. FIELD_OFFSET(FILE_FS_VOLUME_INFORMATION,VolumeLabel) + \
  17. MAXIMUM_FILENAME_LENGTH * sizeof(WCHAR)
  18. #ifdef ALLOC_PRAGMA
  19. #pragma alloc_text( PAGE, SrvSmbSearch )
  20. #endif
  21. SMB_PROCESSOR_RETURN_TYPE
  22. SrvSmbSearch (
  23. SMB_PROCESSOR_PARAMETERS
  24. )
  25. /*++
  26. Routine Description:
  27. This routine processes the various search SMBs, including the core
  28. Search and the LM 1.0 Find, Find Unique, and Find Close.
  29. Arguments:
  30. SMB_PROCESSOR_PARAMETERS - See smbtypes.h for a description
  31. of the parameters to SMB processor routines.
  32. Return Value:
  33. SMB_PROCESSOR_RETURN_TYPE - See smbtypes.h
  34. --*/
  35. {
  36. PREQ_SEARCH request;
  37. PRESP_SEARCH response;
  38. NTSTATUS status = STATUS_SUCCESS;
  39. SMB_STATUS SmbStatus = SmbStatusInProgress;
  40. UNICODE_STRING fileName;
  41. PSRV_DIRECTORY_INFORMATION directoryInformation = NULL;
  42. CLONG availableSpace;
  43. CLONG totalBytesWritten;
  44. BOOLEAN calledQueryDirectory;
  45. BOOLEAN findFirst;
  46. BOOLEAN isUnicode;
  47. BOOLEAN filterLongNames;
  48. BOOLEAN isCoreSearch;
  49. PTABLE_ENTRY entry = NULL;
  50. SHORT sidIndex;
  51. SHORT sequence;
  52. PSMB_RESUME_KEY resumeKey = NULL;
  53. PCCHAR s;
  54. PSMB_DIRECTORY_INFORMATION smbDirInfo;
  55. USHORT smbFileAttributes;
  56. PSEARCH search = NULL;
  57. PDIRECTORY_CACHE dirCache, dc;
  58. USHORT count;
  59. USHORT maxCount;
  60. USHORT i;
  61. USHORT resumeKeyLength;
  62. UCHAR command;
  63. CCHAR j;
  64. CLONG nonPagedBufferSize;
  65. ULONG resumeFileIndex;
  66. WCHAR nameBuffer[8 + 1 + 3 + 1];
  67. OEM_STRING oemString;
  68. PTREE_CONNECT treeConnect;
  69. PSESSION session;
  70. PCONNECTION connection;
  71. PPAGED_CONNECTION pagedConnection;
  72. HANDLE RootDirectoryHandle;
  73. WCHAR unicodeResumeName[ sizeof( dirCache->UnicodeResumeName ) / sizeof( WCHAR ) ];
  74. USHORT unicodeResumeNameLength = 0;
  75. PAGED_CODE( );
  76. if (WorkContext->PreviousSMB == EVENT_TYPE_SMB_LAST_EVENT)
  77. WorkContext->PreviousSMB = EVENT_TYPE_SMB_SEARCH;
  78. SrvWmiStartContext(WorkContext);
  79. connection = WorkContext->Connection;
  80. pagedConnection = connection->PagedConnection;
  81. //
  82. // HackHack: Check the flags2 field if dos client. Some dos clients
  83. // set flags2 to 0xffff.
  84. //
  85. isUnicode = SMB_IS_UNICODE( WorkContext );
  86. if ( isUnicode && IS_DOS_DIALECT(connection->SmbDialect) ) {
  87. WorkContext->RequestHeader->Flags2 = 0;
  88. isUnicode = FALSE;
  89. }
  90. filterLongNames =
  91. ((SmbGetAlignedUshort( &WorkContext->RequestHeader->Flags2 ) &
  92. SMB_FLAGS2_KNOWS_LONG_NAMES) == 0) ||
  93. IS_DOS_DIALECT(connection->SmbDialect);
  94. IF_SMB_DEBUG(SEARCH1) {
  95. SrvPrint2( "Search request header at 0x%p, response header at 0x%p\n",
  96. WorkContext->RequestHeader, WorkContext->ResponseHeader );
  97. SrvPrint2( "Search request params at 0x%p, response params%p\n",
  98. WorkContext->RequestParameters,
  99. WorkContext->ResponseParameters );
  100. }
  101. request = (PREQ_SEARCH)WorkContext->RequestParameters;
  102. response = (PRESP_SEARCH)WorkContext->ResponseParameters;
  103. command = WorkContext->RequestHeader->Command;
  104. //
  105. // Set up a pointer in the SMB buffer where we will write
  106. // information about files. The +3 is to account for the
  107. // SMB_FORMAT_VARIABLE and the word that holds the data length.
  108. //
  109. smbDirInfo = (PSMB_DIRECTORY_INFORMATION)(response->Buffer + 3);
  110. fileName.Buffer = NULL;
  111. //
  112. // If a session block has not already been assigned to the current
  113. // work context , verify the UID. If verified, the address of the
  114. // session block corresponding to this user is stored in the
  115. // WorkContext block and the session block is referenced.
  116. //
  117. // Find tree connect corresponding to given TID if a tree connect
  118. // pointer has not already been put in the WorkContext block by an
  119. // AndX command.
  120. //
  121. status = SrvVerifyUidAndTid(
  122. WorkContext,
  123. &session,
  124. &treeConnect,
  125. ShareTypeDisk
  126. );
  127. if ( !NT_SUCCESS(status) ) {
  128. IF_DEBUG(SMB_ERRORS) {
  129. SrvPrint0( "SrvSmbSearch: Invalid UID or TID\n" );
  130. }
  131. SrvSetSmbError( WorkContext, status );
  132. SmbStatus = SmbStatusSendResponse;
  133. goto Cleanup;
  134. }
  135. isCoreSearch = (BOOLEAN)(command == SMB_COM_SEARCH);
  136. if( session->IsSessionExpired )
  137. {
  138. status = SESSION_EXPIRED_STATUS_CODE;
  139. SrvSetSmbError( WorkContext, status );
  140. SmbStatus = SmbStatusSendResponse;
  141. goto Cleanup;
  142. }
  143. //
  144. // Get necessary information from the request SMB before we start
  145. // overwriting it.
  146. //
  147. maxCount = SmbGetUshort( &request->MaxCount );
  148. //
  149. // If they aren't asking for any files, then they are confused!
  150. //
  151. if( maxCount == 0 ) {
  152. //
  153. // We would log this, but certain linux clients mistakenly do this
  154. // over and over and over...
  155. //
  156. status = STATUS_INVALID_SMB;
  157. goto error_exit;
  158. }
  159. //
  160. // If this is a core search, we don't want to get too many files,
  161. // as we have to cache information about them between requests.
  162. //
  163. //
  164. // A buffer of nonpaged pool is required by SrvQueryDirectoryFile.
  165. // We need to use the SMB buffer for found file names and
  166. // information, so allocate a buffer from nonpaged pool.
  167. //
  168. // If we don't need to return many files, we don't need to allocate
  169. // a large buffer. The buffer size is the configurable size or
  170. // enough to hold two more than the number of files we need to
  171. // return. We get space to hold two extra files in case some files
  172. // do not meet the search criteria (eg directories).
  173. //
  174. if ( isCoreSearch ) {
  175. maxCount = MIN( maxCount, (USHORT)MAX_DIRECTORY_CACHE_SIZE );
  176. nonPagedBufferSize = MIN_SEARCH_BUFFER_SIZE;
  177. } else {
  178. if ( maxCount > MAX_FILES_FOR_MED_SEARCH ) {
  179. nonPagedBufferSize = MAX_SEARCH_BUFFER_SIZE;
  180. } else if ( maxCount > MAX_FILES_FOR_MIN_SEARCH ) {
  181. nonPagedBufferSize = MED_SEARCH_BUFFER_SIZE;
  182. } else {
  183. nonPagedBufferSize = MIN_SEARCH_BUFFER_SIZE;
  184. }
  185. }
  186. //
  187. // The response to a search is never unicode, though the request may be.
  188. //
  189. if( isUnicode ) {
  190. USHORT flags2 = SmbGetAlignedUshort( &WorkContext->RequestHeader->Flags2 );
  191. flags2 &= ~SMB_FLAGS2_UNICODE;
  192. SmbPutAlignedUshort( &WorkContext->ResponseHeader->Flags2, flags2 );
  193. }
  194. //
  195. // If there was a resume key, verify the SID. If there was no
  196. // resume key, allocate a search block. The first two bytes after
  197. // the format token are the length of the resume key. If they are
  198. // both zero, then the request was a find first.
  199. //
  200. count = SmbGetUshort( &request->ByteCount );
  201. if( isUnicode ) {
  202. PWCHAR p;
  203. for( p = (PWCHAR)((PCCHAR)request->Buffer+1), i = 0;
  204. i < count && SmbGetUshort(p) != UNICODE_NULL;
  205. p++, i += sizeof(*p) );
  206. s = (PCCHAR)(p + 1); // skip past the null to the next char
  207. } else {
  208. for ( s = (PCCHAR)request->Buffer, i = 0;
  209. i < count && *s != (CCHAR)SMB_FORMAT_VARIABLE;
  210. s++, i += sizeof(*s) );
  211. }
  212. //
  213. // If there was no SMB_FORMAT_VARIABLE token in the buffer, fail.
  214. //
  215. if ( i == count || *s != (CCHAR)SMB_FORMAT_VARIABLE ) {
  216. IF_DEBUG(SMB_ERRORS) {
  217. SrvPrint0( "SrvSmbSearch: no SMB_FORMAT_VARIABLE token.\n" );
  218. }
  219. SrvLogInvalidSmb( WorkContext );
  220. status = STATUS_INVALID_SMB;
  221. goto error_exit;
  222. }
  223. resumeKeyLength = SmbGetUshort( (PSMB_USHORT)(s+1) );
  224. if ( resumeKeyLength == 0 ) {
  225. //
  226. // There was no resume key, so either a Find First or a Find
  227. // Unique was intended. If it was actually a Find Close, return
  228. // an error to the client.
  229. //
  230. if ( command == SMB_COM_FIND_CLOSE ) {
  231. IF_DEBUG(SMB_ERRORS) {
  232. SrvPrint0( "SrvSmbSearch: Find Close sent w/o resume key.\n" );
  233. }
  234. status = STATUS_INVALID_SMB;
  235. SrvLogInvalidSmb( WorkContext );
  236. goto error_exit;
  237. }
  238. IF_SMB_DEBUG(SEARCH2) SrvPrint0( "FIND FIRST\n" );
  239. findFirst = TRUE;
  240. calledQueryDirectory = FALSE;
  241. //
  242. // Initialize the string containing the path name. The +1 is to
  243. // account for the ASCII token in the Buffer field of the
  244. // request SMB.
  245. //
  246. status = SrvCanonicalizePathName(
  247. WorkContext,
  248. treeConnect->Share,
  249. NULL,
  250. (PVOID)(request->Buffer + 1),
  251. END_OF_REQUEST_SMB( WorkContext ),
  252. FALSE,
  253. isUnicode,
  254. &fileName
  255. );
  256. if( !NT_SUCCESS( status ) ) {
  257. goto error_exit;
  258. }
  259. //
  260. // If the volume attribute bit is set, just return the volume name.
  261. //
  262. if ( SmbGetUshort( &request->SearchAttributes )
  263. == SMB_FILE_ATTRIBUTE_VOLUME ) {
  264. //
  265. // Use NtQueryVolumeInformationFile to get the volume name.
  266. //
  267. IO_STATUS_BLOCK ioStatusBlock;
  268. PFILE_FS_VOLUME_INFORMATION volumeInformation;
  269. //
  270. // Allocate enough space to store the volume information structure
  271. // and MAXIMUM_FILENAME_LENGTH bytes for the volume label name.
  272. //
  273. volumeInformation = ALLOCATE_HEAP( VOLUME_BUFFER_SIZE, BlockTypeVolumeInformation );
  274. if ( volumeInformation == NULL ) {
  275. INTERNAL_ERROR(
  276. ERROR_LEVEL_EXPECTED,
  277. "SrvSmbSearch: Unable to allocate memory from server heap",
  278. NULL,
  279. NULL
  280. );
  281. status = STATUS_INSUFF_SERVER_RESOURCES;
  282. goto error_exit;
  283. }
  284. RtlZeroMemory( volumeInformation, VOLUME_BUFFER_SIZE );
  285. //
  286. // Get the Share root handle.
  287. //
  288. status = SrvGetShareRootHandle( treeConnect->Share );
  289. if ( !NT_SUCCESS(status) ) {
  290. IF_DEBUG(ERRORS) {
  291. SrvPrint1( "SrvSmbSearch: SrvGetShareRootHandle failed %x.\n",
  292. status );
  293. }
  294. FREE_HEAP( volumeInformation );
  295. goto error_exit;
  296. }
  297. //
  298. // Handle SnapShot case
  299. //
  300. status = SrvSnapGetRootHandle( WorkContext, &RootDirectoryHandle );
  301. if( !NT_SUCCESS(status) )
  302. {
  303. FREE_HEAP( volumeInformation );
  304. goto error_exit;
  305. }
  306. status = NtQueryVolumeInformationFile(
  307. RootDirectoryHandle,
  308. &ioStatusBlock,
  309. volumeInformation,
  310. VOLUME_BUFFER_SIZE,
  311. FileFsVolumeInformation
  312. );
  313. //
  314. // If the media was changed and we can come up with a new share root handle,
  315. // then we should retry the operation
  316. //
  317. if( SrvRetryDueToDismount( treeConnect->Share, status ) ) {
  318. status = SrvSnapGetRootHandle( WorkContext, &RootDirectoryHandle );
  319. if( !NT_SUCCESS(status) )
  320. {
  321. FREE_HEAP( volumeInformation );
  322. goto error_exit;
  323. }
  324. status = NtQueryVolumeInformationFile(
  325. RootDirectoryHandle,
  326. &ioStatusBlock,
  327. volumeInformation,
  328. VOLUME_BUFFER_SIZE,
  329. FileFsVolumeInformation
  330. );
  331. }
  332. //
  333. // Release the share root handle
  334. //
  335. SrvReleaseShareRootHandle( WorkContext->TreeConnect->Share );
  336. if ( !NT_SUCCESS(status) ) {
  337. INTERNAL_ERROR(
  338. ERROR_LEVEL_UNEXPECTED,
  339. "SrvSmbSearch: NtQueryVolumeInformationFile returned %X",
  340. status,
  341. NULL
  342. );
  343. SrvLogServiceFailure( SRV_SVC_NT_QUERY_VOL_INFO_FILE, status );
  344. FREE_HEAP( volumeInformation );
  345. goto error_exit;
  346. }
  347. IF_SMB_DEBUG(SEARCH2) {
  348. SrvPrint2( "NtQueryVolumeInformationFile succeeded, name = %ws, "
  349. "length %ld\n", volumeInformation->VolumeLabel,
  350. volumeInformation->VolumeLabelLength );
  351. }
  352. //
  353. // Check if we have a volume label
  354. //
  355. if ( volumeInformation->VolumeLabelLength > 0 ) {
  356. //
  357. // Build the response SMB.
  358. //
  359. response->WordCount = 1;
  360. SmbPutUshort( &response->Count, 1 );
  361. SmbPutUshort(
  362. &response->ByteCount,
  363. 3 + sizeof(SMB_DIRECTORY_INFORMATION)
  364. );
  365. response->Buffer[0] = SMB_FORMAT_VARIABLE;
  366. SmbPutUshort(
  367. (PSMB_USHORT)(response->Buffer+1),
  368. sizeof(SMB_DIRECTORY_INFORMATION)
  369. );
  370. //
  371. // *** Is there anything that we must set in the resume key?
  372. //
  373. smbDirInfo->FileAttributes = SMB_FILE_ATTRIBUTE_VOLUME;
  374. SmbZeroTime( &smbDirInfo->LastWriteTime );
  375. SmbZeroDate( &smbDirInfo->LastWriteDate );
  376. SmbPutUlong( &smbDirInfo->FileSize, 0 );
  377. {
  378. UNICODE_STRING unicodeString;
  379. OEM_STRING oemString;
  380. //
  381. // Volume labels may be longer than 11 bytes, but we
  382. // truncate then to this length in order to make sure that
  383. // the label will fit into the 8.3+NULL -byte space in the
  384. // SMB_DIRECTORY_INFORMATION structure. Also, the LM 1.2
  385. // ring 3 and Pinball servers do this.
  386. //
  387. unicodeString.Length =
  388. (USHORT) MIN(
  389. volumeInformation->VolumeLabelLength,
  390. 11 * sizeof(WCHAR) );
  391. unicodeString.MaximumLength = 13;
  392. unicodeString.Buffer = volumeInformation->VolumeLabel;
  393. oemString.MaximumLength = 13;
  394. oemString.Buffer = (PCHAR)smbDirInfo->FileName;
  395. RtlUnicodeStringToOemString(
  396. &oemString,
  397. &unicodeString,
  398. FALSE
  399. );
  400. //
  401. // If the volume label is greater than 8 characters, it
  402. // needs to be turned into 8.3 format.
  403. //
  404. if( oemString.Length > 8 ) {
  405. //
  406. // Slide the last three characters one position to the
  407. // right and insert a '.' to formulate an 8.3 name
  408. //
  409. smbDirInfo->FileName[11] = smbDirInfo->FileName[10];
  410. smbDirInfo->FileName[10] = smbDirInfo->FileName[9];
  411. smbDirInfo->FileName[9] = smbDirInfo->FileName[8];
  412. smbDirInfo->FileName[8] = '.';
  413. oemString.Length++;
  414. }
  415. smbDirInfo->FileName[oemString.Length] = '\0';
  416. //
  417. // Blank pad space after the volume label.
  418. //
  419. for ( i = (USHORT)(oemString.Length + 1);
  420. i < 13;
  421. i++ ) {
  422. smbDirInfo->FileName[i] = ' ';
  423. }
  424. }
  425. //
  426. // Store the resume key in the response packet. DOS redirs
  427. // actually use this!
  428. //
  429. {
  430. UNICODE_STRING baseFileName;
  431. SrvGetBaseFileName( &fileName, &baseFileName );
  432. SrvUnicodeStringTo8dot3(
  433. &baseFileName,
  434. (PSZ)smbDirInfo->ResumeKey.FileName,
  435. FALSE
  436. );
  437. //
  438. // I set Sid = 1 because the next 5 bytes should
  439. // be nonzero and we don't really have a sid.
  440. //
  441. smbDirInfo->ResumeKey.Sid = 0x01;
  442. SmbPutUlong( &smbDirInfo->ResumeKey.FileIndex, 0);
  443. }
  444. } else {
  445. //
  446. // There is no volume label.
  447. //
  448. response->WordCount = 1;
  449. SmbPutUshort( &response->Count, 0 );
  450. SmbPutUshort( &response->ByteCount, 3 );
  451. response->Buffer[0] = SMB_FORMAT_VARIABLE;
  452. SmbPutUshort( (PSMB_USHORT)(response->Buffer+1), 0 );
  453. }
  454. WorkContext->ResponseParameters =
  455. NEXT_LOCATION(
  456. response,
  457. RESP_SEARCH,
  458. SmbGetUshort( &response->ByteCount )
  459. );
  460. FREE_HEAP( volumeInformation );
  461. if ( !isUnicode &&
  462. fileName.Buffer != NULL &&
  463. fileName.Buffer != nameBuffer ) {
  464. RtlFreeUnicodeString( &fileName );
  465. }
  466. SmbStatus = SmbStatusSendResponse;
  467. goto Cleanup;
  468. }
  469. //
  470. // If this is a core search without patterns, short circuit the
  471. // whole thing right here.
  472. //
  473. if( isCoreSearch && fileName.Length <= sizeof( nameBuffer ) &&
  474. ( fileName.Length == 0 ||
  475. !FsRtlDoesNameContainWildCards( &fileName )) ) {
  476. IO_STATUS_BLOCK ioStatus;
  477. OBJECT_ATTRIBUTES objectAttributes;
  478. ULONG attributes;
  479. ULONG inclusiveSearchAttributes, exclusiveSearchAttributes;
  480. USHORT searchAttributes;
  481. UNICODE_STRING baseFileName;
  482. BOOLEAN returnDirectories, returnDirectoriesOnly;
  483. FILE_NETWORK_OPEN_INFORMATION fileInformation;
  484. PSZ dirInfoName;
  485. SMB_DATE dosDate;
  486. SMB_TIME dosTime;
  487. UNICODE_STRING foundFileName;
  488. UNICODE_STRING ObjectNameString;
  489. PUNICODE_STRING filePathName;
  490. BOOLEAN FreePathName = FALSE;
  491. ObjectNameString.Buffer = fileName.Buffer;
  492. ObjectNameString.Length = fileName.Length;
  493. ObjectNameString.MaximumLength = fileName.Length;
  494. if( fileName.Length == 0 ) {
  495. //
  496. // Since we are opening the root of the share, set the attribute to
  497. // case insensitive, as this is how we opened the share when it was added
  498. //
  499. status = SrvSnapGetNameString( WorkContext, &filePathName, &FreePathName );
  500. if( !NT_SUCCESS(status) )
  501. {
  502. goto error_exit;
  503. }
  504. ObjectNameString = *filePathName;
  505. attributes = OBJ_CASE_INSENSITIVE;
  506. } else {
  507. attributes =
  508. (WorkContext->RequestHeader->Flags & SMB_FLAGS_CASE_INSENSITIVE ||
  509. WorkContext->Session->UsingUppercasePaths ) ?
  510. OBJ_CASE_INSENSITIVE : 0;
  511. }
  512. SrvInitializeObjectAttributes_U(
  513. &objectAttributes,
  514. &ObjectNameString,
  515. attributes,
  516. NULL,
  517. NULL
  518. );
  519. status = IMPERSONATE( WorkContext );
  520. if( NT_SUCCESS( status ) ) {
  521. status = SrvGetShareRootHandle( treeConnect->Share );
  522. if( NT_SUCCESS( status ) ) {
  523. //
  524. // The file name is always relative to the share root
  525. //
  526. status = SrvSnapGetRootHandle( WorkContext, &objectAttributes.RootDirectory );
  527. if( !NT_SUCCESS(status) )
  528. {
  529. goto SnapError;
  530. }
  531. //
  532. // Get the attributes of the object
  533. //
  534. if( IoFastQueryNetworkAttributes(
  535. &objectAttributes,
  536. FILE_READ_ATTRIBUTES,
  537. 0,
  538. &ioStatus,
  539. &fileInformation
  540. ) == FALSE ) {
  541. SrvLogServiceFailure( SRV_SVC_IO_FAST_QUERY_NW_ATTRS, 0 );
  542. ioStatus.Status = STATUS_OBJECT_PATH_NOT_FOUND;
  543. }
  544. status = ioStatus.Status;
  545. //
  546. // If the media was changed and we can come up with a new share root handle,
  547. // then we should retry the operation
  548. //
  549. if( SrvRetryDueToDismount( treeConnect->Share, status ) ) {
  550. status = SrvSnapGetRootHandle( WorkContext, &objectAttributes.RootDirectory );
  551. if( !NT_SUCCESS(status) )
  552. {
  553. goto SnapError;
  554. }
  555. //
  556. // Get the attributes of the object
  557. //
  558. if( IoFastQueryNetworkAttributes(
  559. &objectAttributes,
  560. FILE_READ_ATTRIBUTES,
  561. 0,
  562. &ioStatus,
  563. &fileInformation
  564. ) == FALSE ) {
  565. SrvLogServiceFailure( SRV_SVC_IO_FAST_QUERY_NW_ATTRS, 0 );
  566. ioStatus.Status = STATUS_OBJECT_PATH_NOT_FOUND;
  567. }
  568. }
  569. SrvReleaseShareRootHandle( treeConnect->Share );
  570. }
  571. SnapError:
  572. REVERT();
  573. }
  574. // Free up the string
  575. if( FreePathName )
  576. {
  577. FREE_HEAP( filePathName );
  578. filePathName = NULL;
  579. }
  580. if( !NT_SUCCESS( status ) ) {
  581. //
  582. // Do error mapping to keep the DOS clients happy
  583. //
  584. if ( status == STATUS_NO_SUCH_FILE ||
  585. status == STATUS_OBJECT_NAME_NOT_FOUND ) {
  586. status = STATUS_NO_MORE_FILES;
  587. }
  588. goto error_exit;
  589. }
  590. searchAttributes = SmbGetUshort( &request->SearchAttributes );
  591. searchAttributes &= SMB_FILE_ATTRIBUTE_READONLY |
  592. SMB_FILE_ATTRIBUTE_HIDDEN |
  593. SMB_FILE_ATTRIBUTE_SYSTEM |
  594. SMB_FILE_ATTRIBUTE_VOLUME |
  595. SMB_FILE_ATTRIBUTE_DIRECTORY |
  596. SMB_FILE_ATTRIBUTE_ARCHIVE;
  597. //
  598. // The file or directory exists, now we need to see if it matches the
  599. // criteria given by the client
  600. //
  601. SRV_SMB_ATTRIBUTES_TO_NT(
  602. searchAttributes & 0xff,
  603. &returnDirectories,
  604. &inclusiveSearchAttributes
  605. );
  606. inclusiveSearchAttributes |= FILE_ATTRIBUTE_NORMAL |
  607. FILE_ATTRIBUTE_ARCHIVE |
  608. FILE_ATTRIBUTE_READONLY;
  609. SRV_SMB_ATTRIBUTES_TO_NT(
  610. searchAttributes >> 8,
  611. &returnDirectoriesOnly,
  612. &exclusiveSearchAttributes
  613. );
  614. exclusiveSearchAttributes &= ~FILE_ATTRIBUTE_NORMAL;
  615. //
  616. // See if the returned file meets our objectives
  617. //
  618. if(
  619. //
  620. // If we're only supposed to return directories, then we don't want it
  621. //
  622. returnDirectoriesOnly
  623. ||
  624. //
  625. // If there are bits set in FileAttributes that are
  626. // not set in inclusiveSearchAttributes, then we don't want it
  627. //
  628. ((fileInformation.FileAttributes << 24 ) |
  629. ( inclusiveSearchAttributes << 24 )) !=
  630. ( inclusiveSearchAttributes << 24 )
  631. ||
  632. //
  633. // If the file doesn't have attribute bits specified as exclusive
  634. // bits, we don't want it
  635. //
  636. ( ((fileInformation.FileAttributes << 24 ) |
  637. (exclusiveSearchAttributes << 24 )) !=
  638. (fileInformation.FileAttributes << 24) )
  639. ) {
  640. //
  641. // Just as though the file was never there!
  642. //
  643. status = STATUS_OBJECT_PATH_NOT_FOUND;
  644. goto error_exit;
  645. }
  646. //
  647. // We want this entry!
  648. // Fill in the response
  649. //
  650. //
  651. // Switch over to a private name buffer, to avoid overwriting info
  652. // in the SMB buffer.
  653. //
  654. RtlCopyMemory( nameBuffer, fileName.Buffer, fileName.Length );
  655. foundFileName.Buffer = nameBuffer;
  656. foundFileName.Length = fileName.Length;
  657. foundFileName.MaximumLength = fileName.MaximumLength;
  658. SrvGetBaseFileName( &foundFileName, &baseFileName );
  659. SrvUnicodeStringTo8dot3(
  660. &baseFileName,
  661. (PSZ)smbDirInfo->ResumeKey.FileName,
  662. TRUE
  663. );
  664. //
  665. // Resume Key doesn't matter, since the client will not come back. But
  666. // just in case it does, make sure we have a bum resume key
  667. //
  668. SET_RESUME_KEY_INDEX( (PSMB_RESUME_KEY)smbDirInfo, 0xff );
  669. SET_RESUME_KEY_SEQUENCE( (PSMB_RESUME_KEY)smbDirInfo, 0xff );
  670. SmbPutUlong( &((PSMB_RESUME_KEY)smbDirInfo)->FileIndex, 0 );
  671. SmbPutUlong( (PSMB_ULONG)&((PSMB_RESUME_KEY)smbDirInfo)->Consumer[0], 0 );
  672. //
  673. // Fill in the name (even though they knew what it was!)
  674. //
  675. oemString.Buffer = smbDirInfo->FileName;
  676. oemString.MaximumLength = sizeof( smbDirInfo->FileName );
  677. RtlUpcaseUnicodeStringToOemString( &oemString, &baseFileName, FALSE );
  678. //
  679. // Null terminate and blank-pad the name
  680. //
  681. oemString.Buffer[ oemString.Length ] = '\0';
  682. for( i=(USHORT)oemString.Length+1; i < sizeof( smbDirInfo->FileName); i++ ) {
  683. oemString.Buffer[i] = ' ';
  684. }
  685. SRV_NT_ATTRIBUTES_TO_SMB(
  686. fileInformation.FileAttributes,
  687. fileInformation.FileAttributes & FILE_ATTRIBUTE_DIRECTORY,
  688. &smbFileAttributes
  689. );
  690. smbDirInfo->FileAttributes = (UCHAR)smbFileAttributes;
  691. SrvTimeToDosTime(
  692. &fileInformation.LastWriteTime,
  693. &dosDate,
  694. &dosTime
  695. );
  696. SmbPutDate( &smbDirInfo->LastWriteDate, dosDate );
  697. SmbPutTime( &smbDirInfo->LastWriteTime, dosTime );
  698. SmbPutUlong( &smbDirInfo->FileSize, fileInformation.EndOfFile.LowPart );
  699. totalBytesWritten = sizeof(SMB_DIRECTORY_INFORMATION);
  700. count = 1;
  701. goto done_core;
  702. }
  703. directoryInformation = ALLOCATE_NONPAGED_POOL(
  704. nonPagedBufferSize,
  705. BlockTypeDirectoryInfo
  706. );
  707. if ( directoryInformation == NULL ) {
  708. INTERNAL_ERROR(
  709. ERROR_LEVEL_EXPECTED,
  710. "SrvSmbSearch: unable to allocate nonpaged pool",
  711. NULL,
  712. NULL
  713. );
  714. status = STATUS_INSUFF_SERVER_RESOURCES;
  715. goto error_exit;
  716. }
  717. directoryInformation->DirectoryHandle = NULL;
  718. IF_SMB_DEBUG(SEARCH2) {
  719. SrvPrint2( "Allocated buffer space of %ld bytes at 0x%p\n",
  720. nonPagedBufferSize, directoryInformation );
  721. }
  722. //
  723. // Allocate a search block. The search block is used to retain
  724. // state information between search or find SMBs. The search
  725. // blocks for core and regular searches are slightly different,
  726. // hence the BOOLEAN parameter to SrvAllocateSearch.
  727. //
  728. //
  729. // If we've reached our max, start closing searches.
  730. //
  731. if ( SrvStatistics.CurrentNumberOfOpenSearches >= SrvMaxOpenSearches ) {
  732. SrvForceTimeoutSearches( connection );
  733. }
  734. SrvAllocateSearch(
  735. &search,
  736. &fileName,
  737. isCoreSearch
  738. );
  739. if ( search == NULL ) {
  740. IF_DEBUG(ERRORS) {
  741. SrvPrint0( "SrvSmbSearch: unable to allocate search block.\n" );
  742. }
  743. status = STATUS_INSUFF_SERVER_RESOURCES;
  744. goto error_exit;
  745. }
  746. search->Pid = SmbGetAlignedUshort(
  747. &WorkContext->RequestHeader->Pid
  748. );
  749. //
  750. // Set up referenced session and tree connect pointers and
  751. // increment the count of open files on the session. This
  752. // prevents an idle session with an open search from being
  753. // autodisconnected.
  754. //
  755. ACQUIRE_LOCK( &connection->Lock );
  756. if ( isCoreSearch ) {
  757. pagedConnection->CurrentNumberOfCoreSearches++;
  758. }
  759. search->Session = WorkContext->Session;
  760. SrvReferenceSession( WorkContext->Session );
  761. search->TreeConnect = WorkContext->TreeConnect;
  762. SrvReferenceTreeConnect( WorkContext->TreeConnect );
  763. //
  764. // If this is not a find unique, put the search block in the
  765. // search table. Otherwise, just set the sidIndex and sequence
  766. // variables to 0 to distinguish between a valid resumable
  767. // search block.
  768. //
  769. if ( command == SMB_COM_FIND_UNIQUE ) {
  770. WorkContext->Session->CurrentSearchOpenCount++;
  771. RELEASE_LOCK( &connection->Lock );
  772. sequence = sidIndex = -1;
  773. } else {
  774. NTSTATUS TableStatus;
  775. PTABLE_HEADER searchTable = &pagedConnection->SearchTable;
  776. //
  777. // If there are no free entries in the table, attempt to
  778. // grow the table. If we are unable to grow the table,
  779. // attempt to timeout a search block using the shorter
  780. // timeout period. If this fails, reject the request.
  781. //
  782. if ( searchTable->FirstFreeEntry == -1
  783. &&
  784. SrvGrowTable(
  785. searchTable,
  786. SrvInitialSearchTableSize,
  787. SrvMaxSearchTableSize,
  788. &TableStatus ) == FALSE
  789. &&
  790. SrvTimeoutSearches(
  791. NULL,
  792. connection,
  793. TRUE ) == 0
  794. ) {
  795. IF_DEBUG(ERRORS)
  796. SrvPrint0( "SrvSmbSearch: Connection searchTable full.\n" );
  797. RELEASE_LOCK( &connection->Lock );
  798. if( TableStatus == STATUS_INSUFF_SERVER_RESOURCES )
  799. {
  800. SrvLogTableFullError( SRV_TABLE_SEARCH );
  801. status = STATUS_OS2_NO_MORE_SIDS;
  802. }
  803. else
  804. {
  805. status = TableStatus;
  806. }
  807. goto error_exit;
  808. } else if ( GET_BLOCK_STATE( session ) != BlockStateActive ) {
  809. //
  810. //
  811. // If the session is closing do not insert this search
  812. // on the search list, because the list may already
  813. // have been cleaned up.
  814. //
  815. RELEASE_LOCK( &connection->Lock );
  816. status = STATUS_SMB_BAD_UID;
  817. goto error_exit;
  818. } else if ( GET_BLOCK_STATE( treeConnect ) != BlockStateActive ) {
  819. //
  820. // Tree connect is closing. Don't insert the search block
  821. // so the tree connect can be cleaned up immediately.
  822. //
  823. RELEASE_LOCK( &connection->Lock );
  824. status = STATUS_SMB_BAD_TID;
  825. goto error_exit;
  826. }
  827. //
  828. // increment the count of open searches
  829. //
  830. WorkContext->Session->CurrentSearchOpenCount++;
  831. sidIndex = searchTable->FirstFreeEntry;
  832. //
  833. // A free SID was found. Remove it from the free list and set
  834. // its owner and sequence number.
  835. //
  836. entry = &searchTable->Table[sidIndex];
  837. searchTable->FirstFreeEntry = entry->NextFreeEntry;
  838. DEBUG entry->NextFreeEntry = -2;
  839. if ( searchTable->LastFreeEntry == sidIndex ) {
  840. searchTable->LastFreeEntry = -1;
  841. }
  842. INCREMENT_SID_SEQUENCE( entry->SequenceNumber );
  843. //
  844. // SID = sequence | sidIndex == 0 is illegal. If this is
  845. // the current value, increment the sequence.
  846. //
  847. if ( entry->SequenceNumber == 0 && sidIndex == 0 ) {
  848. INCREMENT_SID_SEQUENCE( entry->SequenceNumber );
  849. }
  850. sequence = entry->SequenceNumber;
  851. entry->Owner = search;
  852. RELEASE_LOCK( &connection->Lock );
  853. }
  854. //
  855. // Fill in other fields of the search block.
  856. //
  857. search->SearchAttributes =
  858. SmbGetUshort( &request->SearchAttributes );
  859. search->TableIndex = sidIndex;
  860. IF_SMB_DEBUG(SEARCH2) {
  861. SrvPrint3( "Allocated search block at 0x%p. Index = 0x%lx, sequence = 0x%lx\n", search, sidIndex, sequence );
  862. }
  863. } else {
  864. //
  865. // The resume key length was nonzero, so this should be a find
  866. // next. Check the resume key length to be safe.
  867. //
  868. USHORT resumeSequence;
  869. if ( resumeKeyLength != sizeof(SMB_RESUME_KEY) ) {
  870. IF_DEBUG(SMB_ERRORS) {
  871. SrvPrint2( "Resume key length was incorrect--was %ld instead "
  872. "of %ld\n", resumeKeyLength, sizeof(SMB_RESUME_KEY) );
  873. }
  874. SrvLogInvalidSmb( WorkContext );
  875. status = STATUS_INVALID_SMB;
  876. goto error_exit;
  877. }
  878. findFirst = FALSE;
  879. resumeKey = (PSMB_RESUME_KEY)(s + 3);
  880. //
  881. // Set up the sequence number and index. These are used for the
  882. // return resume keys.
  883. //
  884. sequence = SID_SEQUENCE( resumeKey );
  885. sidIndex = SID_INDEX( resumeKey );
  886. directoryInformation = ALLOCATE_NONPAGED_POOL(
  887. nonPagedBufferSize,
  888. BlockTypeDirectoryInfo
  889. );
  890. if ( directoryInformation == NULL ) {
  891. INTERNAL_ERROR(
  892. ERROR_LEVEL_EXPECTED,
  893. "SrvSmbSearch: unable to allocate nonpaged pool",
  894. NULL,
  895. NULL
  896. );
  897. status = STATUS_INSUFF_SERVER_RESOURCES;
  898. goto error_exit;
  899. }
  900. directoryInformation->DirectoryHandle = NULL;
  901. IF_SMB_DEBUG(SEARCH2) {
  902. SrvPrint2( "Allocated buffer space of %ld bytes at 0x%p\n",
  903. nonPagedBufferSize, directoryInformation );
  904. }
  905. //
  906. // Verify the SID in the resume key. SrvVerifySid also fills in
  907. // fields of directoryInformation so it is ready to be used by
  908. // SrvQueryDirectoryFile.
  909. //
  910. search = SrvVerifySid(
  911. WorkContext,
  912. sidIndex,
  913. sequence,
  914. directoryInformation,
  915. nonPagedBufferSize
  916. );
  917. if ( search == NULL ) {
  918. if (0) IF_DEBUG(SMB_ERRORS) {
  919. SrvPrint2( "SrvSmbSearch: Invalid resume key (SID): index = "
  920. "%lx, seq. = %lx\n",
  921. sidIndex, sequence );
  922. }
  923. status = STATUS_INVALID_PARAMETER;
  924. goto error_exit;
  925. }
  926. //
  927. // If this is a core search, take the search block off its last-use
  928. // list. We will return it to the end of the list when we are
  929. // done processing this SMB.
  930. //
  931. if ( isCoreSearch ) {
  932. USHORT dirCacheIndex;
  933. ACQUIRE_LOCK( &connection->Lock );
  934. //
  935. // If the reference count on the search block is not 2,
  936. // somebody messed up and we could run into problems,
  937. // because the timeout code assumes that dereferencing a
  938. // search block will kill it. The reference count is 2--one
  939. // for our pointer, one for the active status.
  940. //
  941. ASSERT( search->BlockHeader.ReferenceCount == 2 );
  942. //
  943. // If the search block has already been taken off the LRU
  944. // list, then the client has attempted two simultaneous core
  945. // searches with the same search block. This is an error on
  946. // the part of the client.
  947. //
  948. if ( search->LastUseListEntry.Flink == NULL ) {
  949. RELEASE_LOCK( &connection->Lock );
  950. status = STATUS_INVALID_SMB;
  951. IF_DEBUG(SMB_ERRORS) {
  952. SrvPrint0( "SrvSmbSearch: Attempt to do two simultaneuos core searches on same search block.\n" );
  953. }
  954. SrvLogInvalidSmb( WorkContext );
  955. goto error_exit;
  956. }
  957. SrvRemoveEntryList(
  958. &pagedConnection->CoreSearchList,
  959. &search->LastUseListEntry
  960. );
  961. DECREMENT_DEBUG_STAT2( SrvDbgStatistics.CoreSearches );
  962. //
  963. // Set the entry pointer fields to NULL so that if another
  964. // core search comes in for this search block we will know
  965. // there is an error.
  966. //
  967. search->LastUseListEntry.Flink = NULL;
  968. search->LastUseListEntry.Blink = NULL;
  969. //
  970. // Get the information from the directory cache
  971. // corresponding to this file and put it into the resume key
  972. // so that SrvQueryDirectoryFile has the proper information
  973. // in the resume key. Core clients do not return the
  974. // correct file name in the resume key, and have special
  975. // requirements for the file index in the resume key.
  976. //
  977. resumeFileIndex = SmbGetUlong( &resumeKey->FileIndex );
  978. resumeSequence = (USHORT)((resumeFileIndex & 0xFFFF0000) >> 16);
  979. dirCacheIndex = (USHORT)(resumeFileIndex & (USHORT)0xFFFF);
  980. //
  981. // If the directory cache pointer in the search block
  982. // indicates that there is no directory cache, then we
  983. // returned no files last time, so return no files this
  984. // time. This is due to DOS weirdness.
  985. //
  986. if ( search->DirectoryCache == NULL ||
  987. dirCacheIndex >= search->NumberOfCachedFiles ) {
  988. IF_SMB_DEBUG(SEARCH2) {
  989. SrvPrint0( "Core request for rewind when no dircache exists.\n" );
  990. }
  991. //
  992. // Put the search block back on the LRU list if the
  993. // session and tree connect is still active.
  994. //
  995. if ((GET_BLOCK_STATE( session ) == BlockStateActive) &&
  996. (GET_BLOCK_STATE( treeConnect ) == BlockStateActive)) {
  997. KeQuerySystemTime( &search->LastUseTime );
  998. SrvInsertTailList(
  999. &pagedConnection->CoreSearchList,
  1000. &search->LastUseListEntry
  1001. );
  1002. INCREMENT_DEBUG_STAT2( SrvDbgStatistics.CoreSearches );
  1003. RELEASE_LOCK( &connection->Lock );
  1004. } else {
  1005. RELEASE_LOCK( &connection->Lock );
  1006. //
  1007. // Not needed any more since session is closing.
  1008. //
  1009. SrvCloseSearch( search );
  1010. }
  1011. //
  1012. // Remove our pointer's reference.
  1013. //
  1014. SrvDereferenceSearch( search );
  1015. //
  1016. // Build the response SMB.
  1017. //
  1018. response->WordCount = 1;
  1019. SmbPutUshort( &response->Count, 0 );
  1020. SmbPutUshort( &response->ByteCount, 3 );
  1021. response->Buffer[0] = SMB_FORMAT_VARIABLE;
  1022. SmbPutUshort( (PSMB_USHORT)(response->Buffer+1), 0 );
  1023. WorkContext->ResponseParameters = NEXT_LOCATION(
  1024. response,
  1025. RESP_SEARCH,
  1026. 3
  1027. );
  1028. DEALLOCATE_NONPAGED_POOL( directoryInformation );
  1029. SmbStatus = SmbStatusSendResponse;
  1030. goto Cleanup;
  1031. }
  1032. dirCache = &search->DirectoryCache[dirCacheIndex];
  1033. IF_SMB_DEBUG(SEARCH2) {
  1034. SrvPrint3( "Accessing dircache, real file = %ws, index = 0x%lx, "
  1035. "cache index = %ld\n",
  1036. dirCache->UnicodeResumeName, dirCache->FileIndex,
  1037. dirCacheIndex );
  1038. }
  1039. SmbPutUlong( &resumeKey->FileIndex, dirCache->FileIndex );
  1040. unicodeResumeNameLength = dirCache->UnicodeResumeNameLength;
  1041. ASSERT( unicodeResumeNameLength <= sizeof( unicodeResumeName ) );
  1042. RtlCopyMemory( unicodeResumeName,
  1043. dirCache->UnicodeResumeName,
  1044. unicodeResumeNameLength );
  1045. //
  1046. // Free the directory cache--it is no longer needed.
  1047. //
  1048. FREE_HEAP( search->DirectoryCache );
  1049. search->DirectoryCache = NULL;
  1050. search->NumberOfCachedFiles = 0;
  1051. RELEASE_LOCK( &connection->Lock );
  1052. } else if ( command == SMB_COM_FIND_CLOSE ) {
  1053. //
  1054. // If this is a find close request, close the search block and
  1055. // dereference it. Close out the directory query, and send the
  1056. // response SMB.
  1057. //
  1058. IF_SMB_DEBUG(SEARCH2) {
  1059. SrvPrint1( "FIND CLOSE: Closing search block at 0x%p\n",
  1060. search );
  1061. }
  1062. SrvCloseQueryDirectory( directoryInformation );
  1063. search->DirectoryHandle = NULL;
  1064. SrvCloseSearch( search );
  1065. //
  1066. // Dereference the search block. SrvCloseSearch has already
  1067. // dereferenced it once, so it will be deallocated when we
  1068. // dereference it here.
  1069. //
  1070. SrvDereferenceSearch( search );
  1071. DEALLOCATE_NONPAGED_POOL( directoryInformation );
  1072. response->WordCount = 1;
  1073. SmbPutUshort( &response->ByteCount, 3 );
  1074. response->Buffer[0] = SMB_FORMAT_VARIABLE;
  1075. SmbPutUshort( (PSMB_USHORT)(response->Buffer+1), 0 );
  1076. WorkContext->ResponseParameters = NEXT_LOCATION(
  1077. response,
  1078. RESP_SEARCH,
  1079. 0
  1080. );
  1081. SmbStatus = SmbStatusSendResponse;
  1082. goto Cleanup;
  1083. }
  1084. IF_SMB_DEBUG(SEARCH2) {
  1085. SrvPrint1( "FIND NEXT: Resuming search with file %s\n",
  1086. resumeKey->FileName );
  1087. }
  1088. //
  1089. // Set the filename string so that SrvQueryDirectoryFile knows
  1090. // what search to resume on.
  1091. //
  1092. if( unicodeResumeNameLength != 0 ) {
  1093. fileName.Buffer = unicodeResumeName;
  1094. fileName.Length = fileName.MaximumLength = unicodeResumeNameLength;
  1095. } else {
  1096. fileName.Buffer = nameBuffer;
  1097. Srv8dot3ToUnicodeString(
  1098. (PSZ)resumeKey->FileName,
  1099. &fileName
  1100. );
  1101. }
  1102. //
  1103. // Set calledQueryDirectory to TRUE will indicate to
  1104. // SrvQueryDirectoryFile that it does not need to parse the
  1105. // input name for the directory in which the search occurs, nor
  1106. // does it need to open the directory.
  1107. //
  1108. calledQueryDirectory = TRUE;
  1109. //
  1110. // Get the resume file index in an aligned field for later use.
  1111. //
  1112. resumeFileIndex = SmbGetUlong( &resumeKey->FileIndex );
  1113. IF_SMB_DEBUG(SEARCH2) {
  1114. SrvPrint1( "Found search block at 0x%p\n", search );
  1115. }
  1116. }
  1117. IF_SMB_DEBUG(SEARCH2) {
  1118. SrvPrint2( "Sequence # = %ld, index = %ld\n", sequence, sidIndex );
  1119. }
  1120. //
  1121. // Find the amount of space we have available for writing file
  1122. // entries into. The total buffer size available (includes space
  1123. // for the SMB header and parameters) is the minimum of our buffer
  1124. // size and the client's buffer size. The available space is the
  1125. // total buffer space less the amount we will need for the SMB
  1126. // header and parameters.
  1127. //
  1128. IF_SMB_DEBUG(SEARCH2) {
  1129. SrvPrint4( "BL = %ld, MBS = %ld, r->B = 0x%p, RB->Buffer = 0x%p\n",
  1130. WorkContext->ResponseBuffer->BufferLength,
  1131. session->MaxBufferSize, (PSZ)response->Buffer,
  1132. (PSZ)WorkContext->ResponseBuffer->Buffer );
  1133. }
  1134. availableSpace =
  1135. MIN(
  1136. WorkContext->ResponseBuffer->BufferLength,
  1137. (CLONG)session->MaxBufferSize
  1138. ) -
  1139. PTR_DIFF(response->Buffer, WorkContext->ResponseBuffer->Buffer );
  1140. IF_SMB_DEBUG(SEARCH2) {
  1141. SrvPrint1( "Available buffer space: %ld\n", availableSpace );
  1142. }
  1143. //
  1144. // Simplify the search patterns if possible. This makes the filesystems more
  1145. // efficient, as they special case the '*' pattern
  1146. //
  1147. if ( (fileName.Length >= (12 * sizeof(WCHAR))) &&
  1148. (RtlEqualMemory(
  1149. &fileName.Buffer[fileName.Length/sizeof(WCHAR) - 12],
  1150. StrQuestionMarks,
  1151. 12 * sizeof(WCHAR)))) {
  1152. if( fileName.Length == (12 * sizeof( WCHAR )) ||
  1153. fileName.Buffer[ fileName.Length/sizeof(WCHAR) - 13 ] == L'\\' ) {
  1154. //
  1155. // The search name ends in ????????.???, replace it with *
  1156. //
  1157. fileName.Buffer[fileName.Length/sizeof(WCHAR)-12] = L'*';
  1158. fileName.Length -= 11 * sizeof(WCHAR);
  1159. }
  1160. } else if ((fileName.Length >= (3 * sizeof(WCHAR))) &&
  1161. (RtlEqualMemory(
  1162. &fileName.Buffer[fileName.Length/sizeof(WCHAR) - 3],
  1163. StrStarDotStar,
  1164. 3 * sizeof(WCHAR)))) {
  1165. if( fileName.Length == (3 * sizeof( WCHAR )) ||
  1166. fileName.Buffer[ fileName.Length/sizeof(WCHAR) - 4 ] == L'\\' ) {
  1167. //
  1168. // The search name ends in *.*, replace it with *
  1169. //
  1170. fileName.Length -= 2 * sizeof(WCHAR);
  1171. }
  1172. }
  1173. if( isCoreSearch ) {
  1174. dirCache = (PDIRECTORY_CACHE)ALLOCATE_HEAP(
  1175. maxCount * sizeof(DIRECTORY_CACHE),
  1176. BlockTypeDirCache
  1177. );
  1178. if( dirCache == NULL ) {
  1179. INTERNAL_ERROR(
  1180. ERROR_LEVEL_EXPECTED,
  1181. "SrvSmbSearch: Unable to allocate %d bytes from heap",
  1182. maxCount * sizeof(DIRECTORY_CACHE),
  1183. NULL
  1184. );
  1185. status = STATUS_INSUFF_SERVER_RESOURCES;
  1186. goto error_exit;
  1187. }
  1188. RtlZeroMemory( dirCache, maxCount * sizeof(DIRECTORY_CACHE) );
  1189. }
  1190. //
  1191. // Now we can start getting files. We do this until one of three
  1192. // conditions is met:
  1193. //
  1194. // 1) There are no more files to return.
  1195. // 2) We have obtained as many files as were requested.
  1196. // 3) The SMB buffer is full.
  1197. //
  1198. count = 0;
  1199. totalBytesWritten = 0;
  1200. dc = dirCache;
  1201. do {
  1202. PSZ dirInfoName;
  1203. UNICODE_STRING name;
  1204. PFILE_BOTH_DIR_INFORMATION bothDirInfo;
  1205. SMB_DATE dosDate;
  1206. SMB_TIME dosTime;
  1207. ULONG effectiveBufferSize;
  1208. //
  1209. // Since the file information returned by NtQueryDirectoryFile is
  1210. // about twice the size of the information we must return in the SMB
  1211. // (SMB_DIRECTORY_INFORMATION), use a buffer size equal to twice the
  1212. // available space if the available space is getting small. This
  1213. // optimization means that NtQueryDirectoryFile will return unused
  1214. // files less often. For example, if there is only space left in
  1215. // the SMB buffer for a single file entry, it does not make sense
  1216. // for NtQueryDirectoryFile to completely fill up the buffer--all it
  1217. // really needs to return is a single file.
  1218. //
  1219. effectiveBufferSize = MIN( nonPagedBufferSize, availableSpace * 2 );
  1220. //
  1221. // Make sure that there is at least enough room to hold a single
  1222. // file.
  1223. //
  1224. effectiveBufferSize = MAX( effectiveBufferSize, MIN_SEARCH_BUFFER_SIZE );
  1225. status = SrvQueryDirectoryFile(
  1226. WorkContext,
  1227. (BOOLEAN)!calledQueryDirectory,
  1228. TRUE, // filter long names
  1229. FALSE, // not for backup intent
  1230. FileBothDirectoryInformation,
  1231. 0,
  1232. &fileName,
  1233. (PULONG)( (findFirst || count != 0) ?
  1234. NULL : &resumeFileIndex ),
  1235. search->SearchAttributes,
  1236. directoryInformation,
  1237. effectiveBufferSize
  1238. );
  1239. calledQueryDirectory = TRUE;
  1240. if ( status == STATUS_NO_SUCH_FILE ) {
  1241. status = STATUS_NO_MORE_FILES;
  1242. } else if ( status == STATUS_OBJECT_NAME_NOT_FOUND ) {
  1243. status = STATUS_OBJECT_PATH_NOT_FOUND;
  1244. }
  1245. if ( status == STATUS_NO_MORE_FILES ) {
  1246. if ( findFirst && count == 0 ) {
  1247. //
  1248. // If no files matched on the find first, close out
  1249. // the search.
  1250. //
  1251. IF_SMB_DEBUG(SEARCH1) {
  1252. SrvPrint1( "SrvSmbSearch: no matching files (%wZ).\n",
  1253. &fileName );
  1254. }
  1255. if( isCoreSearch ) {
  1256. FREE_HEAP( dirCache );
  1257. }
  1258. goto error_exit;
  1259. }
  1260. break;
  1261. } else if ( !NT_SUCCESS(status) ) {
  1262. IF_DEBUG(ERRORS) {
  1263. SrvPrint1(
  1264. "SrvSmbSearch: SrvQueryDirectoryFile returned %X\n",
  1265. status
  1266. );
  1267. }
  1268. if( isCoreSearch ) {
  1269. FREE_HEAP( dirCache );
  1270. }
  1271. goto error_exit;
  1272. }
  1273. //
  1274. // Set the resumeKey pointer to NULL. If this is a find next, we
  1275. // have already resumed/rewound the search, so calls to
  1276. // NtQueryDirectoryFile during this search should continue where
  1277. // the last search left off.
  1278. //
  1279. resumeKey = NULL;
  1280. //
  1281. // If this is a Find command, then put the 8dot3 (no ".")
  1282. // representation of the file name into the resume key. If
  1283. // this is a search command, then put the 8dot3 representation of
  1284. // the search specification in the resume key.
  1285. //
  1286. bothDirInfo = (PFILE_BOTH_DIR_INFORMATION)
  1287. directoryInformation->CurrentEntry;
  1288. IF_SMB_DEBUG(SEARCH2) {
  1289. SrvPrint3( "SrvQueryDirectoryFile--name %ws, length = %ld, "
  1290. "status = %X\n",
  1291. bothDirInfo->FileName,
  1292. bothDirInfo->FileNameLength,
  1293. status );
  1294. SrvPrint1( "smbDirInfo = 0x%p\n", smbDirInfo );
  1295. }
  1296. //
  1297. // Use the FileName, unless it is not legal 8.3
  1298. //
  1299. name.Buffer = bothDirInfo->FileName;
  1300. name.Length = (SHORT)bothDirInfo->FileNameLength;
  1301. if( bothDirInfo->ShortNameLength != 0 ) {
  1302. if( !SrvIsLegalFatName( bothDirInfo->FileName,
  1303. bothDirInfo->FileNameLength ) ) {
  1304. //
  1305. // FileName is not legal 8.3, so switch to the
  1306. // ShortName
  1307. //
  1308. name.Buffer = bothDirInfo->ShortName;
  1309. name.Length = (SHORT)bothDirInfo->ShortNameLength;
  1310. }
  1311. }
  1312. name.MaximumLength = name.Length;
  1313. if ( isCoreSearch ) {
  1314. UNICODE_STRING baseFileName;
  1315. SrvGetBaseFileName( &search->SearchName, &baseFileName );
  1316. SrvUnicodeStringTo8dot3(
  1317. &baseFileName,
  1318. (PSZ)smbDirInfo->ResumeKey.FileName,
  1319. filterLongNames
  1320. );
  1321. //
  1322. // Save the unicode version of the 8.3 name in the dirCache
  1323. //
  1324. dc->UnicodeResumeNameLength = name.Length;
  1325. RtlCopyMemory( dc->UnicodeResumeName, name.Buffer, name.Length );
  1326. dc->FileIndex = bothDirInfo->FileIndex;
  1327. ++dc;
  1328. } else {
  1329. SrvUnicodeStringTo8dot3(
  1330. &name,
  1331. (PSZ)smbDirInfo->ResumeKey.FileName,
  1332. filterLongNames
  1333. );
  1334. }
  1335. //
  1336. // Generate the resume key for this file.
  1337. //
  1338. // *** This must be done AFTER setting the file name in the resume
  1339. // key, as setting the resume key name would overwrite some
  1340. // of the sequence bytes which are stored in the high bits
  1341. // of the file name bytes.
  1342. //
  1343. SET_RESUME_KEY_INDEX( (PSMB_RESUME_KEY)smbDirInfo, sidIndex );
  1344. SET_RESUME_KEY_SEQUENCE( (PSMB_RESUME_KEY)smbDirInfo, sequence );
  1345. //
  1346. // Put the file index in the resume key.
  1347. //
  1348. SmbPutUlong(
  1349. &((PSMB_RESUME_KEY)smbDirInfo)->FileIndex,
  1350. bothDirInfo->FileIndex
  1351. );
  1352. SmbPutUlong(
  1353. (PSMB_ULONG)&((PSMB_RESUME_KEY)smbDirInfo)->Consumer[0],
  1354. 0
  1355. );
  1356. //
  1357. // Load the file name into the SMB_DIRECTORY_INFORMATION structure.
  1358. //
  1359. dirInfoName = (PSZ)smbDirInfo->FileName;
  1360. oemString.Buffer = dirInfoName;
  1361. oemString.MaximumLength = (USHORT)RtlUnicodeStringToOemSize( &name );
  1362. if ( filterLongNames ) {
  1363. //
  1364. // If the client doesn't understand long names, upcase the file
  1365. // name. This is necessary for compatibility reasons. Note
  1366. // that the FAT file system returns upcased names anyway.
  1367. //
  1368. RtlUpcaseUnicodeStringToOemString( &oemString, &name, FALSE );
  1369. } else {
  1370. RtlUnicodeStringToOemString( &oemString, &name, FALSE );
  1371. }
  1372. //
  1373. // Blank-pad the end of the filename in order to be compatible with
  1374. // prior redirectors.
  1375. //
  1376. // !!! It is not certain whether this is required.
  1377. //
  1378. for ( i = (USHORT)(oemString.MaximumLength); i < 13; i++ ) {
  1379. dirInfoName[i] = ' ';
  1380. }
  1381. //
  1382. // Fill in other fields in the file entry.
  1383. //
  1384. SRV_NT_ATTRIBUTES_TO_SMB(
  1385. bothDirInfo->FileAttributes,
  1386. bothDirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY,
  1387. &smbFileAttributes
  1388. );
  1389. smbDirInfo->FileAttributes = (UCHAR)smbFileAttributes;
  1390. SrvTimeToDosTime(
  1391. &bothDirInfo->LastWriteTime,
  1392. &dosDate,
  1393. &dosTime
  1394. );
  1395. SmbPutDate( &smbDirInfo->LastWriteDate, dosDate );
  1396. SmbPutTime( &smbDirInfo->LastWriteTime, dosTime );
  1397. //
  1398. // *** NT file sizes are LARGE_INTEGERs (64 bits), SMB file sizes
  1399. // are longwords (32 bits). We just return the low 32 bits
  1400. // of the NT file size, because that is all we can do.
  1401. //
  1402. SmbPutUlong( &smbDirInfo->FileSize, bothDirInfo->EndOfFile.LowPart );
  1403. //
  1404. // Find the space left in the SMB buffer.
  1405. //
  1406. availableSpace -= sizeof(SMB_DIRECTORY_INFORMATION);
  1407. totalBytesWritten += sizeof(SMB_DIRECTORY_INFORMATION);
  1408. //
  1409. // Set up the smbDirInfo pointer for the next file. There is
  1410. // no padding for alignment between files, so just increment
  1411. // the pointer.
  1412. //
  1413. smbDirInfo++;
  1414. count++;
  1415. } while ( ( availableSpace > sizeof(SMB_DIRECTORY_INFORMATION) ) &&
  1416. ( count < maxCount ) );
  1417. IF_SMB_DEBUG(SEARCH2) {
  1418. SrvPrint0( "Stopped putting entries in buffer. Reason:\n" );
  1419. if ( status == STATUS_NO_MORE_FILES ) {
  1420. SrvPrint0( "status = STATUS_NO_MORE_FILES\n" );
  1421. } else if ( count >= maxCount ) {
  1422. SrvPrint2( "count = %ld, maxCount = %ld\n", count, maxCount );
  1423. } else {
  1424. SrvPrint1( "Available space = %ld\n", availableSpace );
  1425. }
  1426. }
  1427. //
  1428. // Store information in the search block.
  1429. //
  1430. search->DirectoryHandle = directoryInformation->DirectoryHandle;
  1431. search->Wildcards = directoryInformation->Wildcards;
  1432. //
  1433. // If this was a core search, store information about the files that
  1434. // were returned in a directory cache. Also, modify the information
  1435. // in the SMB buffer, as it is slightly different for core searches.
  1436. //
  1437. if ( isCoreSearch ) {
  1438. if ( count == 0 ) {
  1439. FREE_HEAP( dirCache );
  1440. IF_SMB_DEBUG(SEARCH1) {
  1441. SrvPrint3( "SrvSmbSearch: prematurely closing search %p, index %lx sequence %lx\n",
  1442. search, sidIndex, sequence );
  1443. }
  1444. SrvCloseSearch( search );
  1445. goto done_core;
  1446. }
  1447. //
  1448. // Modify the CoreSequence field of the search block. This is
  1449. // done because core searches demand that the FileIndex field of
  1450. // the resume key always increase.
  1451. //
  1452. search->CoreSequence++;
  1453. //
  1454. // Set up the pointer to the file information now stored in the
  1455. // SMB buffer and save the location of the directory cache.
  1456. // Store the number of files in the directory cache.
  1457. //
  1458. smbDirInfo = (PSMB_DIRECTORY_INFORMATION)(response->Buffer + 3);
  1459. search->DirectoryCache = dirCache;
  1460. search->NumberOfCachedFiles = count;
  1461. //
  1462. // Loop through the files changing information about the files
  1463. // in the SMB buffer to conform to what the core client expects.
  1464. //
  1465. for ( i = 0; i < count; i++ ) {
  1466. SmbPutUlong(
  1467. &smbDirInfo->ResumeKey.FileIndex,
  1468. (search->CoreSequence << 16) + i
  1469. );
  1470. smbDirInfo++;
  1471. dirCache++;
  1472. }
  1473. //
  1474. // If this was a core search, put the search block back on the
  1475. // appropriate search block list. If no files were found for this
  1476. // SMB, put the search block on the complete list. Also, set the
  1477. // last use time field of the search block.
  1478. //
  1479. // If this is a find first to which we responded with
  1480. // one file AND either more than one file was requested or this
  1481. // is a unique search (no wildcards) AND there was space in the
  1482. // buffer for more, close out the search. This saves the memory
  1483. // associated with an open handle and frees up the search table
  1484. // entry. Also close the search if zero files are being returned.
  1485. //
  1486. // We can do this safely because we know that the client would
  1487. // not be able to do a rewind or resume with these conditions
  1488. // and get back anything other than NO_MORE_FILES, which is what
  1489. // we'll return if the client attempts to resume or rewind to an
  1490. // invalid SID.
  1491. //
  1492. if ( (count == 1
  1493. &&
  1494. findFirst
  1495. &&
  1496. ( maxCount > 1 || !search->Wildcards )
  1497. &&
  1498. availableSpace > sizeof(SMB_DIRECTORY_INFORMATION) ) ) {
  1499. IF_SMB_DEBUG(SEARCH1) {
  1500. SrvPrint3( "SrvSmbSearch: prematurely closing search %p, index %lx sequence %lx\n",
  1501. search, sidIndex, sequence );
  1502. }
  1503. SrvCloseSearch( search );
  1504. } else {
  1505. PLIST_ENTRY hashEntry;
  1506. //
  1507. // Put the search on the core search list.
  1508. //
  1509. ACQUIRE_LOCK( &connection->Lock );
  1510. if ( GET_BLOCK_STATE( session ) != BlockStateActive ) {
  1511. //
  1512. // The session is closing. Do not insert this search
  1513. // on the search list, because the list may already
  1514. // have been cleaned up.
  1515. //
  1516. RELEASE_LOCK( &connection->Lock );
  1517. status = STATUS_SMB_BAD_UID;
  1518. goto error_exit;
  1519. } else if ( GET_BLOCK_STATE( treeConnect ) != BlockStateActive ) {
  1520. //
  1521. // Tree connect is closing. Don't insert the search block
  1522. // so the tree connect can be cleaned up immediately.
  1523. //
  1524. RELEASE_LOCK( &connection->Lock );
  1525. status = STATUS_SMB_BAD_TID;
  1526. goto error_exit;
  1527. }
  1528. KeQuerySystemTime( &search->LastUseTime );
  1529. SrvInsertTailList(
  1530. &pagedConnection->CoreSearchList,
  1531. &search->LastUseListEntry
  1532. );
  1533. INCREMENT_DEBUG_STAT2( SrvDbgStatistics.CoreSearches );
  1534. //
  1535. // Insert this into the hash table.
  1536. //
  1537. hashEntry = &search->HashTableEntry;
  1538. if ( hashEntry->Flink == NULL ) {
  1539. SrvAddToSearchHashTable(
  1540. pagedConnection,
  1541. search
  1542. );
  1543. } else {
  1544. PLIST_ENTRY listHead;
  1545. listHead = &pagedConnection->SearchHashTable[
  1546. search->HashTableIndex].ListHead;
  1547. if ( listHead->Flink != hashEntry ) {
  1548. //
  1549. // remove it and put it back on the front of the queue.
  1550. //
  1551. SrvRemoveEntryList(
  1552. listHead,
  1553. hashEntry
  1554. );
  1555. SrvInsertHeadList(
  1556. listHead,
  1557. hashEntry
  1558. );
  1559. }
  1560. }
  1561. RELEASE_LOCK( &connection->Lock );
  1562. //
  1563. // Make sure the reference count will be 2. 1 for out pointer,
  1564. // and one for the active status.
  1565. //
  1566. ASSERT( search->BlockHeader.ReferenceCount == 2 );
  1567. }
  1568. } else if ( command == SMB_COM_FIND_UNIQUE ) {
  1569. //
  1570. // If this was a find unique, get rid of the search block by
  1571. // closing the query directory and the search block.
  1572. //
  1573. search->DirectoryHandle = NULL;
  1574. SrvCloseQueryDirectory( directoryInformation );
  1575. SrvCloseSearch( search );
  1576. }
  1577. done_core:
  1578. //
  1579. // Set up the response SMB.
  1580. //
  1581. response->WordCount = 1;
  1582. SmbPutUshort( &response->Count, count );
  1583. SmbPutUshort( &response->ByteCount, (USHORT)(totalBytesWritten+3) );
  1584. response->Buffer[0] = SMB_FORMAT_VARIABLE;
  1585. SmbPutUshort(
  1586. (PSMB_USHORT)(response->Buffer+1),
  1587. (USHORT)totalBytesWritten
  1588. );
  1589. WorkContext->ResponseParameters = NEXT_LOCATION(
  1590. response,
  1591. RESP_SEARCH,
  1592. SmbGetUshort( &response->ByteCount )
  1593. );
  1594. //
  1595. // Remove our pointer's reference.
  1596. //
  1597. if( search ) {
  1598. search->InUse = FALSE;
  1599. SrvDereferenceSearch( search );
  1600. }
  1601. if ( !isUnicode &&
  1602. fileName.Buffer != NULL &&
  1603. fileName.Buffer != nameBuffer &&
  1604. fileName.Buffer != unicodeResumeName ) {
  1605. RtlFreeUnicodeString( &fileName );
  1606. }
  1607. if( directoryInformation ) {
  1608. DEALLOCATE_NONPAGED_POOL( directoryInformation );
  1609. }
  1610. SmbStatus = SmbStatusSendResponse;
  1611. goto Cleanup;
  1612. error_exit:
  1613. if ( search != NULL ) {
  1614. //
  1615. // If findFirst == TRUE, then we allocated a search block which
  1616. // we have to close.
  1617. // If findFirst == TRUE and calledQueryDirectory == TRUE, then
  1618. // we also opened the directory handle and need to close it.
  1619. // If findFirst == FALSE, then then we got an existing search
  1620. // block with an existing directory handle.
  1621. //
  1622. if ( findFirst) {
  1623. if ( calledQueryDirectory ) {
  1624. SrvCloseQueryDirectory( directoryInformation );
  1625. search->DirectoryHandle = NULL;
  1626. }
  1627. SrvCloseSearch( search );
  1628. }
  1629. search->InUse = FALSE;
  1630. //
  1631. // Remove our pointer's reference.
  1632. //
  1633. SrvDereferenceSearch( search );
  1634. }
  1635. //
  1636. // Deallocate the directory information block. We do not need
  1637. // to close the directoryhandle here since we should have already
  1638. // closed it (if we need to) in the preceding code.
  1639. //
  1640. if ( directoryInformation != NULL ) {
  1641. DEALLOCATE_NONPAGED_POOL( directoryInformation );
  1642. }
  1643. if ( !isUnicode &&
  1644. fileName.Buffer != NULL &&
  1645. fileName.Buffer != nameBuffer &&
  1646. fileName.Buffer != unicodeResumeName ) {
  1647. RtlFreeUnicodeString( &fileName );
  1648. }
  1649. if( status == STATUS_PATH_NOT_COVERED ) {
  1650. SrvSetSmbError( WorkContext, status );
  1651. } else {
  1652. SrvSetSmbError(
  1653. WorkContext,
  1654. isCoreSearch && (status != STATUS_OBJECT_PATH_NOT_FOUND) ?
  1655. STATUS_NO_MORE_FILES : status
  1656. );
  1657. }
  1658. SmbStatus = SmbStatusSendResponse;
  1659. Cleanup:
  1660. SrvWmiEndContext(WorkContext);
  1661. return SmbStatus;
  1662. } // SrvSmbSearch