From 2b88b84516fef4a53fa3c122176d1d21d394ebf3 Mon Sep 17 00:00:00 2001 From: seaweeduk <2912658+seaweeduk@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:57:17 +0000 Subject: [PATCH 1/2] Settings survive a crash while they are being saved --- src/file_util.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ src/file_util.h | 6 ++++++ src/first_run.cpp | 6 +++--- src/menu_stash_lists.cpp | 7 ++---- src/offline.cpp | 17 ++++++--------- src/places.cpp | 15 +++---------- src/places.h | 1 - src/presets.cpp | 17 ++++++++------- src/remote.cpp | 15 +------------ src/settings.cpp | 14 +----------- src/sftp.cpp | 25 ++-------------------- src/video_memory.cpp | 3 ++- 12 files changed, 81 insertions(+), 91 deletions(-) diff --git a/src/file_util.cpp b/src/file_util.cpp index be0db53..106e3e2 100644 --- a/src/file_util.cpp +++ b/src/file_util.cpp @@ -3,12 +3,17 @@ #include "stash_text.h" #include "remote.h" +#include #include #include #include +#include +#include #include +#include #include +#include #include #include #include @@ -264,6 +269,47 @@ std::future mediaNeighbor(const std::string& current, int step, boo return result; } +bool replaceFile(const fs::path& path, const std::string& contents, bool ownerOnly) { + static std::atomic made{0}; + std::error_code ec; + fs::path target = path; + if (fs::is_symlink(path, ec)) { + const fs::path resolved = fs::canonical(path, ec); + if (!ec) target = resolved; + } + // A new file each call, never an existing one or a link: another instance may be saving too. + const fs::path temp = target.string() + ".new." + std::to_string(getpid()) + "." + std::to_string(made++); + const int fd = ::open(temp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, ownerOnly ? 0600 : 0666); + if (fd < 0) return false; + bool ok = !ownerOnly || fchmod(fd, 0600) == 0; + for (size_t at = 0; ok && at < contents.size();) { + const auto n = ::write(fd, contents.data() + at, contents.size() - at); + if (n < 0 && errno == EINTR) continue; + ok = n > 0; + if (ok) at += n; + } + int synced; + while ((synced = ::fsync(fd)) != 0 && errno == EINTR) { + } + ok = synced == 0 && ok; + ok = ::close(fd) == 0 && ok; + if (ok) { + fs::rename(temp, target, ec); + ok = !ec; + } + if (!ok) { + fs::remove(temp, ec); + return false; + } + // The rename too, through a power cut. The new file is in place either way. + const int dir = ::open(target.parent_path().c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir >= 0) { + ::fsync(dir); + ::close(dir); + } + return true; +} + void queueConfigWork(std::function work) { struct Writer { std::mutex mutex; diff --git a/src/file_util.h b/src/file_util.h index eb43ab3..fef076d 100644 --- a/src/file_util.h +++ b/src/file_util.h @@ -50,6 +50,12 @@ std::string neighborIn(const std::vector& list, const std::string& std::future mediaNeighbor(const std::string& current, int step, bool wrap = false, PlayOrder order = {}); +// Replaces `path` with `contents` by way of a new `path`.new.., synced to disk before +// it is renamed over it, so a crash leaves the old file or the new one, never part of one. A +// symlink stays one: its target is replaced. `ownerOnly`: mode 0600, else std::ofstream's +// (0666 less the umask). False if it couldn't (its temporary is removed). +bool replaceFile(const std::filesystem::path& path, const std::string& contents, bool ownerOnly = false); + // Config reads and writes, in order. Disk work runs outside the queue lock; // shutdown waits for the last write, the frame loop never does. void queueConfigWork(std::function work); diff --git a/src/first_run.cpp b/src/first_run.cpp index ab34193..84437a9 100644 --- a/src/first_run.cpp +++ b/src/first_run.cpp @@ -16,9 +16,9 @@ fs::path markerPath() { return configDir() / "setup.conf"; } void writeMarker(const SetupChoices& choices) { std::error_code ec; fs::create_directories(configDir(), ec); - std::ofstream out(markerPath(), std::ios::trunc); - out << "language=" << choices.language << "\n"; - for (const std::string& place : choices.places) out << "place=" << place << "\n"; + std::string text = "language=" + choices.language + "\n"; + for (const std::string& place : choices.places) text += "place=" + place + "\n"; + replaceFile(markerPath(), text); } } // namespace diff --git a/src/menu_stash_lists.cpp b/src/menu_stash_lists.cpp index 43e6929..99c4426 100644 --- a/src/menu_stash_lists.cpp +++ b/src/menu_stash_lists.cpp @@ -253,11 +253,7 @@ static void writeStashPins(const std::vector& pins, ServerKind kind) { const fs::path path = pinsPath(kind); std::error_code ec; fs::create_directories(path.parent_path(), ec); - std::ofstream out(path); - if (!out) { - std::fprintf(stderr, "Could not save the pinned Stash lists\n"); - return; - } + std::ostringstream out; out << "# VideoFrameVR's pinned Stash lists: Stash's ids of tags, performers and studios\n"; for (const StashPin& p : pins) { const StashList& l = p.list; @@ -283,6 +279,7 @@ static void writeStashPins(const std::vector& pins, ServerKind kind) { << "\nsort=" << kStashSortNames[static_cast(l.sort)] << "\ndescending=" << (l.descending ? 1 : 0) << "\n"; } + if (!replaceFile(path, out.str())) std::fprintf(stderr, "Could not save the pinned Stash lists\n"); } void saveStashPins(const std::vector& pins, ServerKind kind) { diff --git a/src/offline.cpp b/src/offline.cpp index 5e96562..73275ce 100644 --- a/src/offline.cpp +++ b/src/offline.cpp @@ -188,19 +188,14 @@ void Offline::Shared::save() { {"oshash", d.oshash}, {"size", d.size}, {"mtime", d.mtime}, {"done", d.doneAt}, {"subtitles", d.subtitles}}); } - const fs::path dir = dataDir(), file = dir / "offline.json", temp = dir / "offline.json.new"; + const fs::path dir = dataDir(); std::error_code ec; fs::create_directories(dir, ec); - { - std::ofstream out(temp); - // Its strings are UTF-8: add() checks a source and its drive, and paths and subtitles are - // made of those and of names checked in copy() or parsed from JSON (Stash's, or this file - // read back). replace is the last guard, as an exception here would end the app. - const json all{{"paused", paused}, {"downloads", list}}; - out << all.dump(1, ' ', false, json::error_handler_t::replace) << '\n'; - if (!out) return; - } - fs::rename(temp, file, ec); + // Its strings are UTF-8: add() checks a source and its drive, and paths and subtitles are + // made of those and of names checked in copy() or parsed from JSON (Stash's, or this file + // read back). replace is the last guard, as an exception here would end the app. + const json all{{"paused", paused}, {"downloads", list}}; + replaceFile(dir / "offline.json", all.dump(1, ' ', false, json::error_handler_t::replace) + '\n'); } // Deletes the files in `deleting`; whether there were any. diff --git a/src/places.cpp b/src/places.cpp index 29e1f63..09f67ea 100644 --- a/src/places.cpp +++ b/src/places.cpp @@ -175,10 +175,6 @@ bool Places::poll() { return true; } -Places::~Places() { - if (saved_.valid()) saved_.wait(); -} - void Places::arrange() { auto at = [&](const std::string& path) { for (size_t i = 0; i < entries_.size(); ++i) @@ -300,18 +296,13 @@ void Places::save() { if (e.hidden) text += "hide\t" + e.path + '\n'; if (!e.name.empty()) text += "name\t" + e.name + '\t' + e.path + '\n'; } - // Serialize writes without waiting on disk in the render loop. auto done = std::make_shared>(); - const auto previous = saved_; saved_ = done->get_future().share(); - std::thread([text, previous, done] { - if (previous.valid()) previous.wait(); + queueConfigWork([text, done] { const fs::path file = configDir() / "pinned_folders.conf"; std::error_code ec; fs::create_directories(file.parent_path(), ec); - std::ofstream out(file); - out << text; - out.close(); + replaceFile(file, text); done->set_value(); - }).detach(); + }); } diff --git a/src/places.h b/src/places.h index b91b0e4..a87f35d 100644 --- a/src/places.h +++ b/src/places.h @@ -48,7 +48,6 @@ class Places { void setHidden(const std::string& path, bool hidden); void rename(const std::string& path, const std::string& name); void resetOrder(); - ~Places(); // As kept in the file, with the places not there now. struct Entry { diff --git a/src/presets.cpp b/src/presets.cpp index 7b4cd86..4fa907f 100644 --- a/src/presets.cpp +++ b/src/presets.cpp @@ -156,8 +156,9 @@ std::vector fileNames(const std::vector& presets) { } void writeOrder(const std::vector& files) { - std::ofstream out(orderPath(), std::ios::trunc); - for (const std::string& file : files) out << file << "\n"; + std::string text; + for (const std::string& file : files) text += file + "\n"; + replaceFile(orderPath(), text); } // Where a preset called `name` goes: the name made safe for a file name, @@ -178,12 +179,12 @@ fs::path presetPath(const std::string& name, const fs::path& own) { } } -void writePreset(const fs::path& path, const std::string& name, const std::string& lines) { +bool writePreset(const fs::path& path, const std::string& name, const std::string& lines) { std::error_code ec; fs::create_directories(path.parent_path(), ec); - std::ofstream out(path, std::ios::trunc); - out << "name=" << name << "\n" << lines; - if (!out) std::fprintf(stderr, "Could not save the preset\n"); + if (replaceFile(path, "name=" + name + "\n" + lines)) return true; + std::fprintf(stderr, "Could not save the preset\n"); + return false; } std::future> queued(std::function change) { @@ -303,7 +304,7 @@ std::future> saveUserPreset(const std::string& name, con for (const UserPreset& preset : before) if (samePresetName(preset.name, name)) own = presetFile(preset.file); const fs::path path = presetPath(name, own); - writePreset(path, name, lines); + if (!writePreset(path, name, lines)) return; std::vector files = fileNames(before); if (own.empty()) { files.push_back(path.filename().string()); @@ -326,7 +327,7 @@ std::future> renameUserPreset(const std::string& file, c in.close(); std::vector files = fileNames(readPresets()); const fs::path to = presetPath(name, from); - writePreset(to, name, kept); + if (!writePreset(to, name, kept)) return; std::error_code ec; if (to != from) fs::remove(from, ec); std::replace(files.begin(), files.end(), from.filename().string(), to.filename().string()); diff --git a/src/remote.cpp b/src/remote.cpp index f5bb810..fc6bfb2 100644 --- a/src/remote.cpp +++ b/src/remote.cpp @@ -13,9 +13,7 @@ #include #include #include -#include #include -#include namespace remote { namespace { @@ -113,18 +111,7 @@ struct Registry { const auto dir = path.parent_path(); std::error_code ec; std::filesystem::create_directories(dir, ec); - if (ec || chmod(dir.c_str(), 0700) != 0) return; - const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - if (fd < 0) return; - if (fchmod(fd, 0600) == 0) { - size_t offset = 0; - while (offset < contents.size()) { - const auto n = ::write(fd, contents.data() + offset, contents.size() - offset); - if (n <= 0) break; - offset += n; - } - } - ::close(fd); + if (!ec && chmod(dir.c_str(), 0700) == 0) replaceFile(path, contents, true); }); } }; diff --git a/src/settings.cpp b/src/settings.cpp index 97655bd..7715e87 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -20,7 +19,6 @@ #include #include #include -#include #include #include @@ -348,14 +346,6 @@ static void writeSettings(const Settings& s) { const fs::path path = settingsPath(); std::error_code ec; fs::create_directories(path.parent_path(), ec); - const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - FILE* file = nullptr; - if (fd >= 0 && fchmod(fd, 0600) == 0) file = fdopen(fd, "w"); - if (!file) { - if (fd >= 0) close(fd); - std::fprintf(stderr, "Could not save settings\n"); - return; - } std::ostringstream out; auto defaults = lineMap(defaultSettings()); { @@ -374,9 +364,7 @@ static void writeSettings(const Settings& s) { d == defaults.end() || d->second != value) out << key << "=" << value << "\n"; } - const std::string contents = out.str(); - std::fwrite(contents.data(), 1, contents.size(), file); - std::fclose(file); + if (!replaceFile(path, out.str(), true)) std::fprintf(stderr, "Could not save settings\n"); } static std::atomic held{false}; // read by Stash's sync worker too diff --git a/src/sftp.cpp b/src/sftp.cpp index 3b51b75..cb3c267 100644 --- a/src/sftp.cpp +++ b/src/sftp.cpp @@ -43,27 +43,6 @@ std::string pathOf(const std::string& locator) { std::string authorityOf(const std::string& root) { return root.substr(std::min(root.size(), kScheme.size())); } -bool writeAll(const fs::path& path, const std::string& contents) { - const fs::path temp = path.string() + ".new"; - const int fd = ::open(temp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - if (fd < 0) return false; - bool ok = fchmod(fd, 0600) == 0; - for (size_t at = 0; ok && at < contents.size();) { - const auto n = ::write(fd, contents.data() + at, contents.size() - at); - ok = n > 0; - if (ok) at += n; - } - ok = ::fsync(fd) == 0 && ok; - ::close(fd); - std::error_code ec; - if (ok) { - fs::rename(temp, path, ec); - ok = !ec; - } - if (!ok) fs::remove(temp, ec); - return ok; -} - // Frees a file's or folder's handle here only: once the connection is gone // it can't be closed on the server (sftp_close() would ask it). void discard(sftp_file file) { @@ -108,7 +87,7 @@ struct Keys { const fs::path dir = configDir(); std::error_code ec; fs::create_directories(dir, ec); - if (!ec && chmod(dir.c_str(), 0700) == 0) writeAll(dir / "sftp-hosts.json", contents); + if (!ec && chmod(dir.c_str(), 0700) == 0) replaceFile(dir / "sftp-hosts.json", contents, true); }); } // This device's key (a new copy each time: sessions use it from several @@ -135,7 +114,7 @@ struct Keys { const fs::path dir = configDir(); std::error_code ec; fs::create_directories(dir, ec); - if (ec || chmod(dir.c_str(), 0700) != 0 || !writeAll(dir / "sftp-key", contents)) { + if (ec || chmod(dir.c_str(), 0700) != 0 || !replaceFile(dir / "sftp-key", contents, true)) { ssh_key_free(key); return nullptr; } diff --git a/src/video_memory.cpp b/src/video_memory.cpp index e565e19..e14a9d3 100644 --- a/src/video_memory.cpp +++ b/src/video_memory.cpp @@ -122,8 +122,9 @@ void FolderMemory::save() const { const fs::path path = configFile("folders.conf"); std::error_code ec; fs::create_directories(path.parent_path(), ec); - std::ofstream out(path); + std::ostringstream out; for (const auto& [hash, view] : entries) out << hash << ' ' << view.sort << ' ' << (view.gallery ? 1 : 0) << '\n'; + replaceFile(path, out.str()); }); } From b71d3b620871df692d1f49e13923cbb2874ab5de Mon Sep 17 00:00:00 2001 From: seaweeduk <2912658+seaweeduk@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:06:57 +0000 Subject: [PATCH 2/2] Keep a config symlink whose target can't be found --- src/file_util.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/file_util.cpp b/src/file_util.cpp index 106e3e2..295f435 100644 --- a/src/file_util.cpp +++ b/src/file_util.cpp @@ -274,8 +274,10 @@ bool replaceFile(const fs::path& path, const std::string& contents, bool ownerOn std::error_code ec; fs::path target = path; if (fs::is_symlink(path, ec)) { + // A link whose target can't be found now (a drive not mounted) stays a link. const fs::path resolved = fs::canonical(path, ec); - if (!ec) target = resolved; + if (ec) return false; + target = resolved; } // A new file each call, never an existing one or a link: another instance may be saving too. const fs::path temp = target.string() + ".new." + std::to_string(getpid()) + "." + std::to_string(made++);