Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/file_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
#include "stash_text.h"
#include "remote.h"

#include <fcntl.h>
#include <glib.h>
#include <langinfo.h>
#include <locale.h>
#include <sys/stat.h>
#include <unistd.h>

#include <algorithm>
#include <atomic>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
Expand Down Expand Up @@ -264,6 +269,49 @@ std::future<std::string> 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<unsigned> made{0};
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) 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++);
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<void()> work) {
struct Writer {
std::mutex mutex;
Expand Down
6 changes: 6 additions & 0 deletions src/file_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ std::string neighborIn(const std::vector<std::string>& list, const std::string&
std::future<std::string> mediaNeighbor(const std::string& current, int step, bool wrap = false,
PlayOrder order = {});

// Replaces `path` with `contents` by way of a new `path`.new.<pid>.<n>, 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<void()> work);
Expand Down
6 changes: 3 additions & 3 deletions src/first_run.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 2 additions & 5 deletions src/menu_stash_lists.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,7 @@ static void writeStashPins(const std::vector<StashPin>& 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;
Expand All @@ -283,6 +279,7 @@ static void writeStashPins(const std::vector<StashPin>& pins, ServerKind kind) {
<< "\nsort=" << kStashSortNames[static_cast<int>(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<StashPin>& pins, ServerKind kind) {
Expand Down
17 changes: 6 additions & 11 deletions src/offline.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 3 additions & 12 deletions src/places.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<std::promise<void>>();
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();
});
}
1 change: 0 additions & 1 deletion src/places.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
17 changes: 9 additions & 8 deletions src/presets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,9 @@ std::vector<std::string> fileNames(const std::vector<UserPreset>& presets) {
}

void writeOrder(const std::vector<std::string>& 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,
Expand All @@ -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<std::vector<UserPreset>> queued(std::function<void()> change) {
Expand Down Expand Up @@ -303,7 +304,7 @@ std::future<std::vector<UserPreset>> 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<std::string> files = fileNames(before);
if (own.empty()) {
files.push_back(path.filename().string());
Expand All @@ -326,7 +327,7 @@ std::future<std::vector<UserPreset>> renameUserPreset(const std::string& file, c
in.close();
std::vector<std::string> 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());
Expand Down
15 changes: 1 addition & 14 deletions src/remote.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
#include <fstream>
#include <map>
#include <optional>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

namespace remote {
namespace {
Expand Down Expand Up @@ -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);
});
}
};
Expand Down
14 changes: 1 addition & 13 deletions src/settings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <filesystem>
#include <fstream>
#include <iterator>
Expand All @@ -20,7 +19,6 @@
#include <string>
#include <sys/stat.h>
#include <system_error>
#include <unistd.h>
#include <utility>
#include <vector>

Expand Down Expand Up @@ -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());
{
Expand All @@ -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<bool> held{false}; // read by Stash's sync worker too
Expand Down
25 changes: 2 additions & 23 deletions src/sftp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand All @@ -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;
}
Expand Down
3 changes: 2 additions & 1 deletion src/video_memory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
});
}