Fray Engine
Loading...
Searching...
No Matches
application_state_location.hpp
Go to the documentation of this file.
1#ifndef FRAY_APPLICATION_STATE_LOCATION_HPP
2#define FRAY_APPLICATION_STATE_LOCATION_HPP
3
4#include <atomic>
5#include <cerrno>
6#include <cstring>
7#include <filesystem>
8#include <fstream>
9#include <string>
10
11#include "errors.hpp"
12#include "log_manager.hpp"
13
14#ifdef _WIN32
15#ifndef NOMINMAX
16#define NOMINMAX
17#endif
18#ifndef WIN32_LEAN_AND_MEAN
19#define WIN32_LEAN_AND_MEAN
20#endif
21#include <windows.h>
22#else
23#include <fcntl.h>
24#include <unistd.h>
25#endif
26
27namespace fray
28{
29 namespace state
30 {
32 inline constexpr const char* applicationLocationFile = "Fray.application-database";
33
41 const std::filesystem::path& directory,
42 std::filesystem::path& result)
43 {
44 const auto location = directory / applicationLocationFile;
45 std::error_code error;
46 const auto status = std::filesystem::symlink_status(location, error);
47 if (error == std::errc::no_such_file_or_directory ||
48 (!error && status.type() == std::filesystem::file_type::not_found))
49 {
50 result.clear();
51 return errors::NONE;
52 }
53 if (error || !std::filesystem::is_regular_file(status))
54 {
55 log::engineError("Cannot read application database location: invalid file.");
56 return errors::FAILED_OPEN_STORE;
57 }
58 const auto size = std::filesystem::file_size(location, error);
59 if (error || size == 0 || size > 32768)
60 {
61 log::engineError("Cannot read application database location: invalid file size.");
62 return errors::FAILED_OPEN_STORE;
63 }
64 std::ifstream input(location, std::ios::binary);
65 if (!input)
66 {
67 log::engineError("Cannot open application database location.");
68 return errors::FAILED_OPEN_STORE;
69 }
70 std::string value(static_cast<std::size_t>(size), '\0');
71 input.read(value.data(), static_cast<std::streamsize>(value.size()));
72 if (input.gcount() != static_cast<std::streamsize>(value.size()) || input.peek() != std::char_traits<char>::eof() ||
73 input.bad() || value.find('\0') != std::string::npos ||
74 !std::filesystem::path(value).is_absolute())
75 {
76 log::engineError("Cannot read application database location: invalid path.");
77 return errors::FAILED_OPEN_STORE;
78 }
79 result = std::filesystem::path(value);
80 return errors::NONE;
81 }
82
92 const std::filesystem::path& directory,
93 const std::string& filename,
94 const std::string& value,
95 bool replaceExisting = true)
96 {
97 if (filename.empty() || std::filesystem::path(filename).filename() != filename ||
98 filename == "." || filename == ".." || value.size() > 1024 * 1024 ||
99 value.find('\0') != std::string::npos)
100 {
101 log::engineError("Cannot save application file: invalid name or contents.");
102 return errors::FAILED_SAVE_STATE;
103 }
104 static std::atomic<unsigned long> sequence{0};
105#ifdef _WIN32
106 const auto process = GetCurrentProcessId();
107#else
108 const auto process = getpid();
109#endif
110 std::filesystem::path temporary;
111#ifdef _WIN32
112 HANDLE file = INVALID_HANDLE_VALUE;
113 for (unsigned attempt = 0; attempt < 64; ++attempt)
114 {
115 temporary = directory / (std::string(".fray-file.") + std::to_string(process) + "." +
116 std::to_string(sequence.fetch_add(1)) + ".tmp");
117 file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
118 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
119 if (file != INVALID_HANDLE_VALUE || GetLastError() != ERROR_FILE_EXISTS)
120 break;
121 }
122 if (file == INVALID_HANDLE_VALUE)
123 {
124 log::engineError("Cannot create temporary application file.");
125 return errors::FAILED_SAVE_STATE;
126 }
127 DWORD written = 0;
128 const bool wrote = WriteFile(file, value.data(), static_cast<DWORD>(value.size()), &written, nullptr) &&
129 written == value.size() && FlushFileBuffers(file);
130 const bool closed = CloseHandle(file);
131 bool replaced = false;
132 if (wrote && closed)
133 {
134 replaced = MoveFileExW(temporary.c_str(), (directory / filename).c_str(),
135 (replaceExisting ? MOVEFILE_REPLACE_EXISTING : 0) | MOVEFILE_WRITE_THROUGH);
136 if (!replaced && !replaceExisting &&
137 (GetLastError() == ERROR_FILE_EXISTS || GetLastError() == ERROR_ALREADY_EXISTS))
138 replaced = true;
139 }
140#else
141 int file = -1;
142 for (unsigned attempt = 0; attempt < 64; ++attempt)
143 {
144 temporary = directory / (std::string(".fray-file.") + std::to_string(process) + "." +
145 std::to_string(sequence.fetch_add(1)) + ".tmp");
146 file = ::open(temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
147 if (file >= 0 || errno != EEXIST)
148 break;
149 }
150 if (file < 0)
151 {
152 log::engineError("Cannot create temporary application file: %s", std::strerror(errno));
153 return errors::FAILED_SAVE_STATE;
154 }
155 std::size_t offset = 0;
156 while (offset < value.size())
157 {
158 const ssize_t count = ::write(file, value.data() + offset, value.size() - offset);
159 if (count < 0 && errno == EINTR)
160 continue;
161 if (count <= 0)
162 break;
163 offset += static_cast<std::size_t>(count);
164 }
165 const bool wrote = offset == value.size() && fsync(file) == 0;
166 const bool closed = ::close(file) == 0;
167 bool replaced = false;
168 if (wrote && closed)
169 {
170 if (replaceExisting)
171 replaced = ::rename(temporary.c_str(), (directory / filename).c_str()) == 0;
172 else
173 replaced = ::link(temporary.c_str(), (directory / filename).c_str()) == 0 || errno == EEXIST;
174 }
175#endif
176 if (!replaceExisting)
177 {
178 std::error_code cleanup;
179 std::filesystem::remove(temporary, cleanup);
180 if (cleanup)
181 {
182 log::engineError("Cannot remove temporary application file: %s", cleanup.message().c_str());
183 return errors::FAILED_SAVE_STATE;
184 }
185 }
186 if (!replaced)
187 {
188 log::engineError("Cannot save application file.");
189 std::error_code cleanup;
190 std::filesystem::remove(temporary, cleanup);
191 if (cleanup)
192 log::engineError("Cannot remove temporary application file: %s", cleanup.message().c_str());
193 return errors::FAILED_SAVE_STATE;
194 }
195 return errors::NONE;
196 }
197
205 const std::filesystem::path& directory,
206 const std::filesystem::path& database)
207 {
208 const std::string value = database.string();
209 if (!database.is_absolute() || value.empty() || value.size() > 32768 ||
210 value.find('\0') != std::string::npos)
211 {
212 log::engineError("Cannot save application database location: invalid path.");
213 return errors::FAILED_SAVE_STATE;
214 }
215 return writeApplicationFile(directory, applicationLocationFile, value);
216 }
217 }
218}
219
220#endif
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
Definition errors.hpp:13
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_err readApplicationLocation(const std::filesystem::path &directory, std::filesystem::path &result)
Reads the selected application database path, if one has been recorded.
F_err writeApplicationLocation(const std::filesystem::path &directory, const std::filesystem::path &database)
Atomically records the selected application database path.
F_err writeApplicationFile(const std::filesystem::path &directory, const std::string &filename, const std::string &value, bool replaceExisting=true)
Atomically replaces a named application-owned file.
constexpr const char * applicationLocationFile
Name of the Engine-adjacent file identifying the selected application database.