From d4427931a2f03b8fd9f80895ace12fb95e0b759c Mon Sep 17 00:00:00 2001 From: stickz Date: Fri, 6 Sep 2024 11:05:35 -0400 Subject: [PATCH] Fix session file data corruption From https://github.com/jesec/rtorrent/commit/f9a875b633eb083ec82f89ebeae8678ca424e8b2 This commit ensures session files land on the disk in the event of a system crash or power outage. It prevents data corruption of rTorrent session files, which causes torrent client breakage. Optimizations from the initial implementation include 1) Skipping unnecessary file metadata updates during the sync process. 2) Skipping variable initialization since open will assign -1 on failure. --- src/core/download_store.cc | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/core/download_store.cc b/src/core/download_store.cc index 536dba10..3345cddc 100644 --- a/src/core/download_store.cc +++ b/src/core/download_store.cc @@ -40,6 +40,7 @@ #include #include +#include #include #include #include @@ -121,6 +122,15 @@ DownloadStore::write_bencode(const std::string& filename, const torrent::Object& goto download_store_save_error; output.close(); + + // Ensure that the new file is actually written to the disk + int fd = ::open(filename.c_str(), O_WRONLY); + if (fd < 0) + goto download_store_save_error; + + fdatasync(fd); + ::close(fd); + return true; download_store_save_error: