Revert "Use native file handle on Windows"

This reverts commit 45056dcbaf077ca55ed5308468bc62aa597d011f.
This commit is contained in:
Janek Bevendorff committed 2026-11-12 20:47:46 +01:00
1 parent 2963964285
commit 0ffab8b9d5
5 files changed
+62 -120

No files matched your search

+4 -4
View File
@@ -1691,6 +1691,10 @@ Backup database located at %2</source>
<source>Could not replace file (error code: %1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Original database backup kept at %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Could not replace file: %1</source>
<translation type="unfinished"></translation>
@@ -1703,10 +1707,6 @@ Backup database located at %2</source>
<source>Could not create a named temporary file: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Could not create temporary file (error code: %1)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DatabaseOpenDialog</name>
+49 -108
View File
@@ -28,13 +28,10 @@
#include "streams/HashingStream.h"
#include <QFileInfo>
#include <QJsonObject>
#include <QRegularExpression>
#include <QSaveFile>
#include <QScopeGuard>
#include <QTemporaryFile>
#include <QTimer>
#include <QVector>
#include <algorithm>
#include <cerrno>
@@ -43,7 +40,6 @@
#ifdef Q_OS_WIN
#include <Windows.h>
#include <fcntl.h>
#include <io.h>
#else
#include <unistd.h>
@@ -51,62 +47,6 @@
namespace
{
#ifdef Q_OS_WIN
/**
* QFile supports long file names. Convert paths to extended path syntax.
*/
QString nativeFilePath(const QString& path)
{
const auto native = QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath());
const auto prefix = R"(\\?\)";
if (native.startsWith(prefix)) {
return native;
}
return prefix + (native.startsWith(R"(\\)") ? R"(UNC\)" + native.mid(2) : native);
}
/**
* Open sibling file with a native handle, which we can keep open to prevent other processes
* from intermittently acquiring a lock on it.
*
* @param path sibling file path
* @param file QFile object to assign handle to
* @param error error string
* @return true on success
*/
bool openSibling(const QString& path, QFile& file, QString& error)
{
const auto nativePath = nativeFilePath(path).toStdWString();
const auto handle = CreateFileW(nativePath.c_str(),
GENERIC_READ | GENERIC_WRITE | DELETE,
0,
nullptr,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (handle == INVALID_HANDLE_VALUE) {
const auto code = GetLastError();
error = Database::tr("Could not create temporary file (error code: %1)").arg(code);
return false;
}
const auto descriptor = _open_osfhandle(reinterpret_cast<intptr_t>(handle), _O_RDWR | _O_BINARY);
if (descriptor == -1) {
error = QString::fromLocal8Bit(std::strerror(errno));
CloseHandle(handle);
QFile::remove(path);
return false;
}
// The descriptor owns the native handle. QFile takes ownership of both on success.
if (!file.open(descriptor, QIODevice::WriteOnly, QFileDevice::AutoCloseHandle)) {
error = file.errorString();
_close(descriptor);
QFile::remove(path);
return false;
}
return true;
}
#endif
/**
* Flush file contents and then force a disk sync.
*
@@ -150,36 +90,46 @@ namespace
* Unlike `QFile::rename()`, this function allows overwrite semantics without a copy / delete fallback.
* Atomicity guarantees depend on the target filesystem.
*
* @param source open source file (must have DELETE access on Windows)
* @param sourcePath source file path
* @param source source file to rename
* @param target target to replace
* @param error error string
* @return true on success
*/
bool replaceFile(QFile& source, const QString& sourcePath, const QString& target, QString& error)
bool replaceFile(const QString& source, const QString& target, QString& error)
{
#ifdef Q_OS_WIN
// Replace directly through the exclusive handle. Never close and reopen the sibling.
// Unlike ReplaceFileW, this does not merge the destination's ACLs or other metadata.
const auto nativeTarget = nativeFilePath(target);
const auto nameBytes = nativeTarget.size() * sizeof(ushort);
const auto bufferSize = sizeof(FILE_RENAME_INFO) + nameBytes;
// Use suitably aligned storage for the variable-length FILE_RENAME_INFO structure.
QVector<quint64> buffer((bufferSize + sizeof(quint64) - 1) / sizeof(quint64), 0);
auto* renameInfo = reinterpret_cast<FILE_RENAME_INFO*>(buffer.data());
renameInfo->ReplaceIfExists = TRUE;
renameInfo->FileNameLength = static_cast<DWORD>(nameBytes);
std::memcpy(renameInfo->FileName, nativeTarget.utf16(), nameBytes);
const auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(source.handle()));
if (!SetFileInformationByHandle(handle, FileRenameInfo, renameInfo, static_cast<DWORD>(bufferSize))) {
const auto code = GetLastError();
error = Database::tr("Could not replace file (error code: %1)").arg(code);
// QFile supports long paths, so convert all paths to extended path syntax first.
const auto toNativePath = [](const QString& path) {
const auto native = QDir::toNativeSeparators(path);
const auto prefix = R"(\\?\)";
if (native.startsWith(prefix)) {
return native;
}
return prefix + (native.startsWith(R"(\\)") ? R"(UNC\)" + native.mid(2) : native);
};
// There is little documentation about the atomicity of file replacements on Windows,
// but ReplaceFile() seems to be atomic at least on NTFS: https://stackoverflow.com/a/2368286
// ReplaceFile() also supports keeping the original file as a backup:
// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew
// MoveFileEx() does not do atomic file replacements.
const auto nativeSource = toNativePath(source).toStdWString();
const auto nativeTarget = toNativePath(target).toStdWString();
const auto backupPath = source + ".bkp";
const auto nativeBackup = toNativePath(backupPath).toStdWString();
const auto renamed =
QFileInfo::exists(target)
? ReplaceFileW(nativeTarget.c_str(), nativeSource.c_str(), nativeBackup.c_str(), 0, nullptr, nullptr)
: MoveFileExW(nativeSource.c_str(), nativeTarget.c_str(), 0);
if (!renamed) {
error = Database::tr("Could not replace file (error code: %1)").arg(GetLastError());
if (QFile::exists(backupPath)) {
error += "\n" + Database::tr("Original database backup kept at %1").arg(backupPath);
}
return false;
}
Q_UNUSED(sourcePath);
QFile::remove(backupPath);
#else
Q_UNUSED(source);
if (::rename(QFile::encodeName(sourcePath).constData(), QFile::encodeName(target).constData()) != 0) {
if (::rename(QFile::encodeName(source).constData(), QFile::encodeName(target).constData()) != 0) {
error = Database::tr("Could not replace file: %1").arg(QString::fromLocal8Bit(std::strerror(errno)));
return false;
}
@@ -399,13 +349,13 @@ bool Database::save(SaveAction savingMethod, const QString& backupFilePath, QStr
* Save the database to a specific file using the specified saving method.
*
* Atomic saves may fail due to a bug in Qt (https://bugreports.qt.io/browse/QTBUG-57299).
* In that case, `TempFile` may be used as an alternative save method. It will instead write
* to a (local) temporary file, stream the serialised contents to a named sibling of the destination,
* sync, and then replace the destination with an atomic rename. Using a temporary file
* has the advantage of keeping a temporary backup copy on the local file system in case of a failure.
* Streaming the byte contents into the destination avoids another Qt bug with `QFile::copy()` /
* `QFile::rename()`, which can trigger on certain remote file systems that don't support hard-links.
* TempFile also tries to keep the sibling handle open to prevent intermittent locking by other processes.
* In that case, `TempFile` may be used as an alternative saving method. It will instead write
* to a temporary file, stream the serialised contents to a named sibling of the destination,
* sync, and then replace the destination with an atomic rename. Streaming the byte contents
* into the destination avoids another Qt bug with `QFile::copy()` / `QFile::rename()`, which can
* trigger on certain file systems that don't support hard-linking an unnamed O_TMPFILE.
* The sibling rename is guaranteed to be atomic on Linux and macOS and may be atomic on
* NTFS file systems on Windows.
*
* Failures to save are reported to the caller, which can decide to offer the user an
* alternative saving method.
@@ -607,31 +557,21 @@ bool Database::performSave(const QString& filePath,
}
// Stream contents from temporary file to sibling. Don't use QFile::copy() or QFile::rename(), since they
// are not atomic and can fail on destination file systems that don't support hard-linking or O_TMPFILE renames.
// are not atomic and can fail on destination file systems that don't support hard-linking O_TMPFILEs.
const auto siblingName =
QStringLiteral(".~%1.tmp.%2").arg(info.fileName()).arg(Random::instance()->randomArray(8).toHex());
const auto siblingPath = info.absoluteDir().filePath(siblingName);
QFile sibling(siblingPath);
#ifdef Q_OS_WIN
if (!openSibling(siblingPath, sibling, fileError)) {
return fail(fileError);
}
#else
if (!sibling.open(QIODevice::WriteOnly | QIODevice::NewOnly)) {
return fail(sibling.errorString());
}
#endif
auto cleanup = qScopeGuard([&] {
sibling.close();
QFile::remove(siblingPath);
sibling.remove();
});
// A QFile opened from a descriptor has no path in its
// file engine on Windows. So, use another (unopened) handle to the sibling to set permissions.
QFile siblingPermissions(siblingPath);
if (!siblingPermissions.setPermissions(QFile::ReadUser | QFile::WriteUser)) {
return fail(siblingPermissions.errorString());
if (!sibling.setPermissions(QFile::ReadUser | QFile::WriteUser)) {
return fail(sibling.errorString());
}
// Stream temp file contents
if (!tempFile.reset()) {
return fail(tempFile.errorString());
}
@@ -644,24 +584,25 @@ bool Database::performSave(const QString& filePath,
return fail(sibling.errorString());
}
}
// Keep original permissions.
if (info.exists() && !siblingPermissions.setPermissions(info.permissions())) {
return fail(siblingPermissions.errorString());
// Keep original permissions if available.
if (info.exists() && !sibling.setPermissions(info.permissions())) {
return fail(sibling.errorString());
}
// Best effort. Qt does not support setting FileBirthTime on Unix.
// Best effort. Setting FileBirthTime is unsupported on Linux and Qt refuses to do it on macOS.
if (!sibling.setFileTime(createTime, QFile::FileBirthTime)) {
sibling.unsetError();
}
if (!syncFile(sibling, fileError)) {
return fail(fileError);
}
sibling.close();
if (sibling.error() != QFile::NoError) {
return fail(sibling.errorString());
}
if (!replaceFile(sibling, siblingPath, filePath, fileError)) {
if (!replaceFile(siblingPath, filePath, fileError)) {
return fail(fileError);
}
sibling.close();
cleanup.dismiss();
m_fileBlockHash = hashingStream.hashingResult();
-1
View File
@@ -102,7 +102,6 @@ DatabaseWidget::DatabaseWidget(QSharedPointer<Database> db, QWidget* parent)
m_db->open(nullptr);
}
m_messageWidget->setObjectName("databaseMessageWidget");
m_messageWidget->setHidden(true);
auto mainLayout = new QVBoxLayout();
+8
View File
@@ -130,6 +130,8 @@ void TestDatabase::testSaveStaged()
QVERIFY(destination.open(QIODevice::WriteOnly | QIODevice::NewOnly));
const auto contents = source.readAll();
QCOMPARE(destination.write(contents), qint64(contents.size()));
QVERIFY(destination.flush());
QVERIFY(destination.setFileTime(QDateTime::currentDateTimeUtc().addDays(-7), QFile::FileModificationTime));
destination.close();
}
const auto originalPermissions = QFile::permissions(target);
@@ -140,7 +142,13 @@ void TestDatabase::testSaveStaged()
QString error;
QVERIFY2(db.open(existing ? target : dbFileName, key, &error), qPrintable(error));
db.metadata()->setName("staged save");
const auto saveStarted = QDateTime::currentDateTimeUtc();
QVERIFY2(db.saveAs(target, static_cast<Database::SaveAction>(action), {}, &error), qPrintable(error));
const auto modified = QFileInfo(target).lastModified().toUTC();
QVERIFY(modified.isValid());
// Allow for filesystems with a two-second timestamp resolution.
QVERIFY(modified >= saveStarted.addSecs(-2));
QVERIFY(modified <= QDateTime::currentDateTimeUtc().addSecs(2));
QVERIFY(!db.isModified());
QVERIFY(error.isEmpty());
if (existing) {
+1 -7
View File
@@ -47,7 +47,6 @@
#include "gui/EntryPreviewWidget.h"
#include "gui/FileDialog.h"
#include "gui/MessageBox.h"
#include "gui/MessageWidget.h"
#include "gui/PasswordGeneratorWidget.h"
#include "gui/PasswordWidget.h"
#include "gui/SearchWidget.h"
@@ -2624,12 +2623,7 @@ void TestGui::checkSaveDatabase()
checkDatabase();
return;
}
const auto* message =
m_tabWidget->currentDatabaseWidget()->findChild<MessageWidget*>("databaseMessageWidget");
const auto detail = message && !message->text().isEmpty()
? message->text()
: QStringLiteral("No save error message available");
QWARN(qPrintable(QStringLiteral("Failed to save database, trying again: %1").arg(detail)));
QWARN("Failed to save database, trying again...");
Tools::wait(250);
} while (++i < 2);