diff options
Diffstat (limited to 'zen')
-rw-r--r-- | zen/FindFilePlus/find_file_plus.cpp | 141 | ||||
-rw-r--r-- | zen/FindFilePlus/find_file_plus.h | 2 | ||||
-rw-r--r-- | zen/FindFilePlus/load_dll.h | 1 | ||||
-rw-r--r-- | zen/file_handling.cpp | 10 | ||||
-rw-r--r-- | zen/file_id_def.h | 10 | ||||
-rw-r--r-- | zen/file_traverser.cpp | 135 |
6 files changed, 200 insertions, 99 deletions
diff --git a/zen/FindFilePlus/find_file_plus.cpp b/zen/FindFilePlus/find_file_plus.cpp index becfe553..e613177b 100644 --- a/zen/FindFilePlus/find_file_plus.cpp +++ b/zen/FindFilePlus/find_file_plus.cpp @@ -10,16 +10,18 @@ #include "load_dll.h" #include <zen/scope_guard.h> +#include <cstdio> + using namespace dll; using namespace findplus; namespace { -struct FileError +struct NtFileError //exception class { - FileError(ULONG errorCode) : win32Error(errorCode) {} - ULONG win32Error; + NtFileError(NTSTATUS errorCode) : ntError(errorCode) {} + NTSTATUS ntError; }; @@ -91,8 +93,8 @@ bool findplus::initDllBinding() //evaluate in ::DllMain() when attaching process //http://msdn.microsoft.com/en-us/library/ff563638(v=VS.85).aspx //verify dynamic dll binding - return ntOpenFile && - ntClose && + return ntOpenFile && + ntClose && ntQueryDirectoryFile && rtlNtStatusToDosError && rtlFreeUnicodeString && @@ -108,9 +110,15 @@ public: FileSearcher(const wchar_t* dirname); //throw FileError ~FileSearcher(); - void readdir(FileInformation& output); //throw FileError + void readDir(FileInformation& output) { (this->*readDirFun)(output); } //throw FileError + + bool tryFallbackToDefaultQuery(); //call if readDir() throws STATUS_NOT_SUPPORTED or similar private: + template <class QueryPolicy> void readDirImpl(FileInformation& output); //throw FileError + //handle fallback, if retrieving file id is not supported by file system layer + void (FileSearcher::*readDirFun)(FileInformation& output); + UNICODE_STRING ntPathName; //it seems hDir implicitly keeps a reference to this, at least ::FindFirstFile() does no cleanup before ::FindClose()! HANDLE hDir; @@ -124,9 +132,43 @@ private: }; +namespace +{ +/* +Common C-style policy handling directory traversal: + +struct QueryPolicy +{ + typedef ... RawFileInfo; + static const FILE_INFORMATION_CLASS fileInformationClass = ...; + static void extractFileId(const RawFileInfo& rawInfo, FileInformation& fileInfo); +}; +*/ + +struct DirQueryDefault +{ + typedef FILE_BOTH_DIR_INFORMATION RawFileInfo; + static const FILE_INFORMATION_CLASS fileInformationClass = FileBothDirectoryInformation; + static void extractFileId(const RawFileInfo& rawInfo, FileInformation& fileInfo) { fileInfo.fileId.QuadPart = 0; } +}; + +struct DirQueryFileId +{ + typedef FILE_ID_BOTH_DIR_INFORMATION RawFileInfo; + static const FILE_INFORMATION_CLASS fileInformationClass = FileIdBothDirectoryInformation; + static void extractFileId(const RawFileInfo& rawInfo, FileInformation& fileInfo) + { + fileInfo.fileId.QuadPart = rawInfo.FileId.QuadPart; //may be 0 even in this context, e.g. for mapped FTP drive! + static_assert(sizeof(fileInfo.fileId) == sizeof(rawInfo.FileId), "dang!"); + } +}; +} + + FileSearcher::FileSearcher(const wchar_t* dirname) : hDir(NULL), - nextEntryOffset(0) + nextEntryOffset(0), + readDirFun(&FileSearcher::readDirImpl<DirQueryFileId>) //start optimistically { ntPathName.Buffer = NULL; ntPathName.Length = 0; @@ -136,7 +178,8 @@ FileSearcher::FileSearcher(const wchar_t* dirname) : //-------------------------------------------------------------------------------------------------------------- //convert dosFileName, e.g. C:\Users or \\?\C:\Users to ntFileName \??\C:\Users - //in contrast to ::FindFirstFile() we don't evaluate the relativeName, however tests indicate ntFileName is *always* filled with an absolute name, even if dosFileName is relative + //in contrast to ::FindFirstFile() implementation we don't evaluate the relativeName, + //however tests indicate ntFileName is *always* filled with an absolute name, even if dosFileName is relative //NOTE: RtlDosPathNameToNtPathName_U may be used on all XP/Win7/Win8 for compatibility // RtlDosPathNameToNtPathName_U: used by Windows XP available with OS version 3.51 (Windows NT) and higher @@ -145,7 +188,7 @@ FileSearcher::FileSearcher(const wchar_t* dirname) : &ntPathName, //__out ntFileName, NULL, //__out_optFilePart, NULL)) //__out_opt relativeName - empty if dosFileName is absolute - throw FileError(rtlNtStatusToDosError(STATUS_OBJECT_PATH_NOT_FOUND)); //translates to ERROR_PATH_NOT_FOUND, same behavior like ::FindFirstFileEx() + throw NtFileError(STATUS_OBJECT_PATH_NOT_FOUND); //translates to ERROR_PATH_NOT_FOUND, same behavior like ::FindFirstFileEx() OBJECT_ATTRIBUTES objAttr = {}; InitializeObjectAttributes(&objAttr, //[out] POBJECT_ATTRIBUTES initializedAttributes, @@ -163,7 +206,7 @@ FileSearcher::FileSearcher(const wchar_t* dirname) : FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, //__in ULONG shareAccess, - 7 on Win7/Win8, 3 on XP FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT); //__in ULONG openOptions - 4021 used on all XP/Win7/Win8 if (!NT_SUCCESS(rv)) - throw FileError(rtlNtStatusToDosError(rv)); + throw NtFileError(rv); } guardConstructor.dismiss(); @@ -179,16 +222,33 @@ FileSearcher::~FileSearcher() if (ntPathName.Buffer) rtlFreeUnicodeString(&ntPathName); //cleanup identical to ::FindFirstFile() - //note that most if this function seems inlined by the linker, so that its assembly looks equivalent to "RtlFreeHeap(GetProcessHeap(), 0, ntPathName.Buffer)" + //note that most of this function seems inlined by the linker, so that its assembly looks equivalent to "RtlFreeHeap(GetProcessHeap(), 0, ntPathName.Buffer)" +} + + +inline +bool FileSearcher::tryFallbackToDefaultQuery() +{ + if (readDirFun == &FileSearcher::readDirImpl<DirQueryDefault>) + return false; //already default + + //Note: NtQueryDirectoryFile() may not respect "restartScan" for some weird Win2000 file system drivers, so we won't bother + //Samba before v3.0.22 (Mar 30, 2006) seems to have a bug which sucessfully returns 128 elements via NtQueryDirectoryFile() + //and FileIdBothDirectoryInformation, then fails with STATUS_INVALID_LEVEL. + //Although traversal is NOT finished yet, it will further return STATUS_NO_MORE_FILES, even if falling back to FileBothDirectoryInformation!!! + + readDirFun = &FileSearcher::readDirImpl<DirQueryDefault>; + return true; } -void FileSearcher::readdir(FileInformation& output) +template <class QueryPolicy> +void FileSearcher::readDirImpl(FileInformation& output) //throw FileError { //although FILE_ID_FULL_DIR_INFORMATION should suffice for our purposes, there are problems on Windows XP for certain directories, e.g. "\\Vboxsvr\build" //making NtQueryDirectoryFile() return with STATUS_INVALID_PARAMETER while other directories, e.g. "C:\" work fine for some reason //FILE_ID_BOTH_DIR_INFORMATION on the other hand works on XP/Win7/Win8 - //performance: there is no noticable difference between FILE_ID_BOTH_DIR_INFORMATION and FILE_ID_FULL_DIR_INFORMATION + //performance: there is no noticeable difference between FILE_ID_BOTH_DIR_INFORMATION and FILE_ID_FULL_DIR_INFORMATION /* corresponding first access in ::FindFirstFileW() @@ -216,18 +276,26 @@ void FileSearcher::readdir(FileInformation& output) &status, //__out PIO_STATUS_BLOCK ioStatusBlock, &buffer, //__out_bcount(Length) PVOID fileInformation, BUFFER_SIZE, //__in ULONG length, ::FindNextFileW() on all XP/Win7/Win8 uses sizeof(FILE_BOTH_DIR_INFORMATION) + sizeof(TCHAR) * 2000 == 0x1000 - FileIdBothDirectoryInformation, //__in FILE_INFORMATION_CLASS fileInformationClass - all XP/Win7/Win8 use "FileBothDirectoryInformation" + QueryPolicy::fileInformationClass, //__in FILE_INFORMATION_CLASS fileInformationClass - all XP/Win7/Win8 use "FileBothDirectoryInformation" false, //__in BOOLEAN returnSingleEntry, NULL, //__in_opt PUNICODE_STRING mask, false); //__in BOOLEAN restartScan if (!NT_SUCCESS(rv)) - throw FileError(rtlNtStatusToDosError(rv)); //throws STATUS_NO_MORE_FILES when finished + { + if (rv == STATUS_NO_SUCH_FILE) //harmonize ntQueryDirectoryFile() error handling! failure to find a file on first call returns STATUS_NO_SUCH_FILE, + rv = STATUS_NO_MORE_FILES; //while on subsequent accesses return STATUS_NO_MORE_FILES + //note: not all directories contain "., .." entries! E.g. a drive's root directory or NetDrive + ftp.gnu.org\CRYPTO.README" + //-> addon: this is NOT a directory, it looks like on in NetDrive, but it's a file in Opera + + throw NtFileError(rv); //throws STATUS_NO_MORE_FILES when finished + } - if (status.Information == 0) //except for the first call to call ::NtQueryDirectoryFile(): - throw FileError(rtlNtStatusToDosError(STATUS_BUFFER_OVERFLOW)); //if buffer size is too small, return value is STATUS_SUCCESS and Information == 0 -> we don't expect this! + if (status.Information == 0) //except for the first call to call ::NtQueryDirectoryFile(): + throw NtFileError(STATUS_BUFFER_OVERFLOW); //if buffer size is too small, return value is STATUS_SUCCESS and Information == 0 -> we don't expect this! } - const FILE_ID_BOTH_DIR_INFORMATION& dirInfo = *reinterpret_cast<FILE_ID_BOTH_DIR_INFORMATION*>(reinterpret_cast<char*>(buffer) + nextEntryOffset); + typedef typename QueryPolicy::RawFileInfo RawFileInfo; + const RawFileInfo& dirInfo = *reinterpret_cast<RawFileInfo*>(reinterpret_cast<char*>(buffer) + nextEntryOffset); if (dirInfo.NextEntryOffset == 0) nextEntryOffset = 0; //our offset is relative to the beginning of the buffer @@ -241,15 +309,16 @@ void FileSearcher::readdir(FileInformation& output) return tmp; }; + QueryPolicy::extractFileId(dirInfo, output); + output.creationTime = toFileTime(dirInfo.CreationTime); output.lastWriteTime = toFileTime(dirInfo.LastWriteTime); output.fileSize.QuadPart = dirInfo.EndOfFile.QuadPart; - output.fileId.QuadPart = dirInfo.FileId.QuadPart; output.fileAttributes = dirInfo.FileAttributes; output.shortNameLength = dirInfo.FileNameLength / sizeof(TCHAR); //FileNameLength is in bytes! if (dirInfo.FileNameLength + sizeof(TCHAR) > sizeof(output.shortName)) //this may actually happen if ::NtQueryDirectoryFile() decides to return a - throw FileError(rtlNtStatusToDosError(STATUS_BUFFER_OVERFLOW)); //short name of length MAX_PATH + 1, 0-termination is not required! + throw NtFileError(STATUS_BUFFER_OVERFLOW); //short name of length MAX_PATH + 1, 0-termination is not required! ::memcpy(output.shortName, dirInfo.FileName, dirInfo.FileNameLength); output.shortName[output.shortNameLength] = 0; //NOTE: FILE_ID_BOTH_DIR_INFORMATION::FileName in general is NOT 0-terminated! It is on XP/Win7, but NOT on Win8! @@ -257,7 +326,6 @@ void FileSearcher::readdir(FileInformation& output) static_assert(sizeof(output.creationTime) == sizeof(dirInfo.CreationTime), "dang!"); static_assert(sizeof(output.lastWriteTime) == sizeof(dirInfo.LastWriteTime), "dang!"); static_assert(sizeof(output.fileSize) == sizeof(dirInfo.EndOfFile), "dang!"); - static_assert(sizeof(output.fileId) == sizeof(dirInfo.FileId), "dang!"); static_assert(sizeof(output.fileAttributes) == sizeof(dirInfo.FileAttributes), "dang!"); } @@ -268,10 +336,10 @@ FindHandle findplus::openDir(const wchar_t* dirname) { return new FileSearcher(dirname); //throw FileError } - catch (const FileError& err) + catch (const NtFileError& e) { - setWin32Error(err.win32Error); - return NULL; + setWin32Error(rtlNtStatusToDosError(e.ntError)); + return nullptr; } } @@ -280,12 +348,28 @@ bool findplus::readDir(FindHandle hnd, FileInformation& output) { try { - hnd->readdir(output); //throw FileError + hnd->readDir(output); //throw FileError return true; } - catch (const FileError& err) + catch (const NtFileError& e) { - setWin32Error(err.win32Error); + /* + fallback to default directory query method, if FileIdBothDirectoryInformation is not properly implemented + this is required for NetDrive mounted Webdav, e.g. www.box.net and NT4, 2000 remote drives, et al. + */ + if (e.ntError != STATUS_NO_MORE_FILES) + if (e.ntError == STATUS_INVALID_LEVEL || + e.ntError == STATUS_NOT_SUPPORTED || + e.ntError == STATUS_INVALID_PARAMETER || + e.ntError == STATUS_INVALID_NETWORK_RESPONSE || + e.ntError == STATUS_INVALID_INFO_CLASS || + e.ntError == STATUS_ACCESS_VIOLATION) //FileIdBothDirectoryInformation on XP accessing UDF + { + if (hnd->tryFallbackToDefaultQuery()) + return readDir(hnd, output); //implementation of tryFallbackToDefaultQuery() promises, that we don't land in an endless recursion here! + } + + setWin32Error(rtlNtStatusToDosError(e.ntError)); return false; } } @@ -293,6 +377,5 @@ bool findplus::readDir(FindHandle hnd, FileInformation& output) void findplus::closeDir(FindHandle hnd) { - if (hnd) //play a little "nice" - delete hnd; + delete hnd; } diff --git a/zen/FindFilePlus/find_file_plus.h b/zen/FindFilePlus/find_file_plus.h index 72b76dbb..33e9a178 100644 --- a/zen/FindFilePlus/find_file_plus.h +++ b/zen/FindFilePlus/find_file_plus.h @@ -34,7 +34,7 @@ struct FileInformation FILETIME creationTime; FILETIME lastWriteTime; ULARGE_INTEGER fileSize; - ULARGE_INTEGER fileId; + ULARGE_INTEGER fileId; //optional: may be 0 if not supported DWORD fileAttributes; DWORD shortNameLength; WCHAR shortName[MAX_PATH + 1]; //shortName is 0-terminated diff --git a/zen/FindFilePlus/load_dll.h b/zen/FindFilePlus/load_dll.h index 350de9f8..24ce7174 100644 --- a/zen/FindFilePlus/load_dll.h +++ b/zen/FindFilePlus/load_dll.h @@ -39,7 +39,6 @@ private: - void* /*FARPROC*/ loadSymbol(const wchar_t* libraryName, const char* functionName); } diff --git a/zen/file_handling.cpp b/zen/file_handling.cpp index 1e44afb7..d6804e34 100644 --- a/zen/file_handling.cpp +++ b/zen/file_handling.cpp @@ -2008,12 +2008,12 @@ void rawCopyStream(const Zstring& sourceFile, FileOutput fileOut(targetFile, FileOutput::ACC_CREATE_NEW); //throw FileError, ErrorTargetPathMissing, ErrorTargetExisting std::vector<char>& buffer = []() -> std::vector<char>& - { - static boost::thread_specific_ptr<std::vector<char>> cpyBuf; - if (!cpyBuf.get()) - cpyBuf.reset(new std::vector<char>(512 * 1024)); //512 kb seems to be a reasonable buffer size + { + static boost::thread_specific_ptr<std::vector<char>> cpyBuf; + if (!cpyBuf.get()) + cpyBuf.reset(new std::vector<char>(512 * 1024)); //512 kb seems to be a reasonable buffer size return *cpyBuf; - }(); + }(); //copy contents of sourceFile to targetFile UInt64 totalBytesTransferred; diff --git a/zen/file_id_def.h b/zen/file_id_def.h index b2029879..7e729eb1 100644 --- a/zen/file_id_def.h +++ b/zen/file_id_def.h @@ -29,13 +29,16 @@ FileId extractFileID(const BY_HANDLE_FILE_INFORMATION& fileInfo) ULARGE_INTEGER uint = {}; uint.HighPart = fileInfo.nFileIndexHigh; uint.LowPart = fileInfo.nFileIndexLow; - return std::make_pair(fileInfo.dwVolumeSerialNumber, uint.QuadPart); + + return fileInfo.dwVolumeSerialNumber != 0 && uint.QuadPart != 0 ? + FileId(fileInfo.dwVolumeSerialNumber, uint.QuadPart) : FileId(); } inline FileId extractFileID(DWORD dwVolumeSerialNumber, ULARGE_INTEGER fileId) { - return std::make_pair(dwVolumeSerialNumber, fileId.QuadPart); + return dwVolumeSerialNumber != 0 && fileId.QuadPart != 0 ? + FileId(dwVolumeSerialNumber, fileId.QuadPart) : FileId(); } namespace impl @@ -57,7 +60,8 @@ typedef std::pair<decltype(impl::StatDummy::st_dev), decltype(impl::StatDummy::s inline FileId extractFileID(const struct stat& fileInfo) { - return std::make_pair(fileInfo.st_dev, fileInfo.st_ino); + return fileInfo.st_dev != 0 && fileInfo.st_ino != 0 ? + FileId(fileInfo.st_dev, fileInfo.st_ino) : FileId(); } #endif } diff --git a/zen/file_traverser.cpp b/zen/file_traverser.cpp index 8a8a8b6f..236581a3 100644 --- a/zen/file_traverser.cpp +++ b/zen/file_traverser.cpp @@ -31,13 +31,13 @@ namespace //implement "retry" in a generic way: template <class Command> inline //function object expecting to throw FileError if operation fails -void tryReportingError(Command cmd, zen::TraverseCallback& callback) +bool tryReportingError(Command cmd, zen::TraverseCallback& callback) //return "true" on success, "false" if error was ignored { for (;;) try { cmd(); - return; + return true; } catch (const FileError& e) { @@ -46,7 +46,7 @@ void tryReportingError(Command cmd, zen::TraverseCallback& callback) case TraverseCallback::TRAV_ERROR_RETRY: break; case TraverseCallback::TRAV_ERROR_IGNORE: - return; + return false; default: assert(false); break; @@ -119,18 +119,17 @@ const DllFun<findplus::OpenDirFunc> openDir (findplus::getDllName(), findplus:: const DllFun<findplus::ReadDirFunc> readDir (findplus::getDllName(), findplus::readDirFuncName ); //load at startup: avoid pre C++11 static initialization MT issues const DllFun<findplus::CloseDirFunc> closeDir(findplus::getDllName(), findplus::closeDirFuncName); // - /* Common C-style interface for Win32 FindFirstFile(), FindNextFile() and FileFilePlus openDir(), closeDir(): -struct X //see "policy based design" +struct TraverserPolicy //see "policy based design" { -typedef ... Handle; +typedef ... DirHandle; typedef ... FindData; -static Handle create(const Zstring& directoryPf, FindData& fileInfo); //throw FileError - concession to FindFirstFile(): implement two operations: 1. open handle, 2. retrieve first data set -static void destroy(Handle hnd); //throw() -static bool next(Handle hnd, const Zstring& directory, WIN32_FIND_DATA& fileInfo) //throw FileError +static void create(const Zstring& directory, DirHandle& hnd); //throw FileError - *no* concession to FindFirstFile(): open handle only, *no* return of data! +static void destroy(DirHandle hnd); //throw() +static bool getEntry(DirHandle hnd, const Zstring& directory, FindData& fileInfo) //throw FileError -//helper routines +//FindData "member" functions static void extractFileInfo (const FindData& fileInfo, const DWORD* volumeSerial, TraverseCallback::FileInfo& output); static Int64 getModTime (const FindData& fileInfo); static const FILETIME& getModTimeRaw (const FindData& fileInfo); //yet another concession to DST hack @@ -140,35 +139,54 @@ static bool isDirectory (const FindData& fileInfo); static bool isSymlink (const FindData& fileInfo); } -Note: Win32 FindFirstFile(), FindNextFile() is a weaker abstraction than FileFilePlus openDir(), readDir(), closeDir() and Unix opendir(), closedir(), stat(), - so unfortunately we have to use former as a greatest common divisor +Note: Win32 FindFirstFile(), FindNextFile() is a weaker abstraction than FileFilePlus openDir(), readDir(), closeDir() and Unix opendir(), closedir(), stat() */ struct Win32Traverser { - typedef HANDLE Handle; + struct DirHandle + { + DirHandle() : searchHandle(NULL), firstRead(true) {} + + HANDLE searchHandle; + bool firstRead; + WIN32_FIND_DATA firstData; + }; + typedef WIN32_FIND_DATA FindData; - static Handle create(const Zstring& directory, FindData& fileInfo) //throw FileError + static void create(const Zstring& directory, DirHandle& hnd) //throw FileError { const Zstring& directoryPf = endsWith(directory, FILE_NAME_SEPARATOR) ? directory : directory + FILE_NAME_SEPARATOR; - HANDLE output = ::FindFirstFile(applyLongPathPrefix(directoryPf + L'*').c_str(), &fileInfo); + hnd.searchHandle = ::FindFirstFile(applyLongPathPrefix(directoryPf + L'*').c_str(), &hnd.firstData); //no noticable performance difference compared to FindFirstFileEx with FindExInfoBasic, FIND_FIRST_EX_CASE_SENSITIVE and/or FIND_FIRST_EX_LARGE_FETCH - if (output == INVALID_HANDLE_VALUE) + if (hnd.searchHandle == INVALID_HANDLE_VALUE) throw FileError(_("Error traversing directory:") + L"\n\"" + directory + L"\"" + L"\n\n" + zen::getLastErrorFormatted()); - //::GetLastError() == ERROR_FILE_NOT_FOUND -> actually NOT okay, even for an empty directory this should not occur (., ..) - return output; + + //::GetLastError() == ERROR_FILE_NOT_FOUND -> *usually* NOT okay: + //however it is unclear whether this indicates a missing directory or a completely empty directory + // note: not all directories contain "., .." entries! E.g. a drive's root directory or NetDrive + ftp.gnu.org\CRYPTO.README" + // -> addon: this is NOT a directory, it looks like one in NetDrive, but it's a file in Opera! + //we have to guess it's former and let the error propagate + // -> FindFirstFile() is a nice example of violation of API design principle of single responsibility and its consequences } - static void destroy(Handle hnd) { ::FindClose(hnd); } //throw() + static void destroy(const DirHandle& hnd) { ::FindClose(hnd.searchHandle); } //throw() - static bool next(Handle hnd, const Zstring& directory, FindData& fileInfo) //throw FileError + static bool getEntry(DirHandle& hnd, const Zstring& directory, FindData& fileInfo) //throw FileError { - if (!::FindNextFile(hnd, &fileInfo)) + if (hnd.firstRead) + { + hnd.firstRead = false; + ::memcpy(&fileInfo, &hnd.firstData, sizeof(fileInfo)); + return true; + } + + if (!::FindNextFile(hnd.searchHandle, &fileInfo)) { if (::GetLastError() == ERROR_NO_MORE_FILES) //not an error situation return false; @@ -178,7 +196,6 @@ struct Win32Traverser return true; } - //helper routines template <class FindData> static void extractFileInfo(const FindData& fileInfo, const DWORD* volumeSerial, TraverseCallback::FileInfo& output) { @@ -208,27 +225,27 @@ struct Win32Traverser struct FilePlusTraverser { - typedef findplus::FindHandle Handle; + struct DirHandle + { + DirHandle() : searchHandle(NULL) {} + + findplus::FindHandle searchHandle; + }; + typedef findplus::FileInformation FindData; - static Handle create(const Zstring& directory, FindData& fileInfo) //throw FileError + static void create(const Zstring& directory, DirHandle& hnd) //throw FileError { - Handle output = ::openDir(applyLongPathPrefix(directory).c_str()); - if (output == NULL) + hnd.searchHandle = ::openDir(applyLongPathPrefix(directory).c_str()); + if (hnd.searchHandle == NULL) throw FileError(_("Error traversing directory:") + L"\n\"" + directory + L"\"" + L"\n\n" + zen::getLastErrorFormatted()); - - bool rv = next(output, directory, fileInfo); //throw FileError - if (!rv) //we expect at least two successful reads, even for an empty directory: ., .. - throw FileError(_("Error traversing directory:") + L"\n\"" + directory + L"\"" + L"\n\n" + zen::getLastErrorFormatted(ERROR_NO_MORE_FILES)); - - return output; } - static void destroy(Handle hnd) { ::closeDir(hnd); } //throw() + static void destroy(DirHandle hnd) { ::closeDir(hnd.searchHandle); } //throw() - static bool next(Handle hnd, const Zstring& directory, FindData& fileInfo) //throw FileError + static bool getEntry(DirHandle hnd, const Zstring& directory, FindData& fileInfo) //throw FileError { - if (!::readDir(hnd, fileInfo)) + if (!::readDir(hnd.searchHandle, fileInfo)) { if (::GetLastError() == ERROR_NO_MORE_FILES) //not an error situation return false; @@ -238,7 +255,6 @@ struct FilePlusTraverser return true; } - //helper routines template <class FindData> static void extractFileInfo(const FindData& fileInfo, const DWORD* volumeSerial, TraverseCallback::FileInfo& output) { @@ -305,31 +321,43 @@ private: throw FileError(_("Endless loop when traversing directory:") + L"\n\"" + directory + L"\""); }, sink); - typename Trav::FindData fileInfo = {}; - - typename Trav::Handle searchHandle = 0; + typename Trav::DirHandle searchHandle; - tryReportingError([&] + const bool openSuccess = tryReportingError([&] { typedef Trav Trav; //f u VS! - searchHandle = Trav::create(directory, fileInfo); //throw FileError + Trav::create(directory, searchHandle); //throw FileError }, sink); - if (searchHandle == 0) + if (!openSuccess) return; //ignored error ZEN_ON_BLOCK_EXIT(typedef Trav Trav; Trav::destroy(searchHandle)); - do + typename Trav::FindData fileInfo = {}; + + while ([&]() -> bool + { + bool moreData = false; + + typedef Trav Trav1; //f u VS! + tryReportingError([&] { - //don't return "." and ".." + typedef Trav1 Trav; //f u VS! + moreData = Trav::getEntry(searchHandle, directory, fileInfo); //throw FileError + }, sink); + + return moreData; + }()) + { + //skip "." and ".." const Zchar* const shortName = Trav::getShortName(fileInfo); if (shortName[0] == L'.' && - (shortName[1] == L'\0' || (shortName[1] == L'.' && shortName[2] == L'\0'))) + (shortName[1] == L'\0' || (shortName[1] == L'.' && shortName[2] == L'\0'))) continue; const Zstring& fullName = endsWith(directory, FILE_NAME_SEPARATOR) ? - directory + shortName : - directory + FILE_NAME_SEPARATOR + shortName; + directory + shortName : + directory + FILE_NAME_SEPARATOR + shortName; if (Trav::isSymlink(fileInfo) && !followSymlinks_) //evaluate symlink directly { @@ -383,19 +411,6 @@ private: sink.onFile(shortName, fullName, details); } } - while ([&]() -> bool - { - bool moreData = false; - - typedef Trav Trav1; //f u VS! - tryReportingError([&] - { - typedef Trav1 Trav; //f u VS! - moreData = Trav::next(searchHandle, directory, fileInfo); //throw FileError - }, sink); - - return moreData; - }()); } |