game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
atomic_write.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// atomic_write.cpp
4// ==============================================================================
5// Implementation of core::atomicWriteFile.
6// ==============================================================================
7
8#include "util/atomic_write.h"
9#include "logger.h"
10
11#include <atomic>
12#include <cerrno>
13#include <cstring>
14#include <filesystem>
15#include <fstream>
16#include <sstream>
17#include <string>
18#include <thread>
19
20#ifndef _WIN32
21#include <fcntl.h>
22#include <sys/stat.h>
23#include <unistd.h>
24#endif
25
26namespace core
27{
28
29namespace
30{
31
32// Process-wide monotonically-increasing counter to disambiguate concurrent
33// writers in the same process. Combined with PID + thread id, the temp
34// suffix becomes unique across (process, thread, call) — meeting the
35// header's "concurrent writers in the same process" claim.
36std::atomic<uint64_t> g_atomicWriteCounter{0};
37
38std::string buildTempSuffix()
39{
40#ifndef _WIN32
41 const auto pid = static_cast<long>(::getpid());
42#else
43 const long pid = 0;
44#endif
45 std::ostringstream tid;
46 tid << std::this_thread::get_id();
47 const auto seq = g_atomicWriteCounter.fetch_add(1, std::memory_order_relaxed);
48 std::ostringstream out;
49 out << ".tmp." << pid << "." << tid.str() << "." << seq;
50 return out.str();
51}
52
53} // namespace
54
55namespace
56{
57
58#ifndef _WIN32
59// Best-effort fsync on the parent directory. Per fsync(2):
60// "Calling fsync() does not necessarily ensure that the entry in the
61// directory containing the file has also reached disk. For that an
62// explicit fsync() on a file descriptor for the directory is also
63// needed."
64// We open with O_RDONLY because directory fsync only needs read access on
65// Linux; the open(2) call must NOT include O_PATH (fsync rejects it).
66//
67// Failures here are logged at warn level rather than propagating: the
68// file's own fsync already moved 95% of the durability burden, and many
69// filesystems (older FAT, some FUSE impls) genuinely refuse directory
70// fsync. We never want to fail a write that otherwise succeeded — but a
71// silent discard would make "I lost my settings after a power cut" bugs
72// undebuggable.
73bool fsyncParentDir(const std::filesystem::path& target)
74{
75 auto parent = target.parent_path();
76 if (parent.empty())
77 parent = std::filesystem::path(".");
78 int dfd = ::open(parent.c_str(), O_RDONLY | O_CLOEXEC);
79 if (dfd < 0)
80 {
81 // LCOV_EXCL_START — opening a directory the caller's parent path
82 // resolved to is essentially never going to fail under unit-test
83 // conditions; triggering it requires fault injection.
84 Logger::warn("[atomicWriteFile] open(parent_dir {}) failed: {}", parent.string(),
85 std::strerror(errno));
86 return false;
87 // LCOV_EXCL_STOP
88 }
89 int rc = ::fsync(dfd);
90 int saved = errno;
91 ::close(dfd);
92 if (rc != 0)
93 {
94 // LCOV_EXCL_START — fsync(dirfd) failures are real (older FAT,
95 // some FUSE) but unit tests can't reliably trigger them. Best-
96 // effort log + return false; caller has already succeeded on
97 // the file's own fsync so we don't surface the parent-fsync
98 // failure to the user.
99 Logger::warn("[atomicWriteFile] fsync(parent_dir {}) failed: {}", parent.string(),
100 std::strerror(saved));
101 return false;
102 // LCOV_EXCL_STOP
103 }
104 return true;
105}
106
107// Helper that removes a stranded temp file and logs (rather than discards)
108// any cleanup failure. Returns the original errno-style message in `errOut`
109// if non-null; the cleanup-error log is independent so the caller still
110// learns about the original failure.
111void cleanupTempFile(const std::filesystem::path& tmp)
112{
113 std::error_code rmEc;
114 std::filesystem::remove(tmp, rmEc);
115 if (rmEc)
116 {
117 // LCOV_EXCL_START — cleanup of a temp file we just created is
118 // essentially never going to fail (we own the file); fault
119 // injection is the only reliable trigger and isn't worth the
120 // test infrastructure for a defensive log line.
121 Logger::warn("[atomicWriteFile] cleanup of stranded temp {} failed: {}", tmp.string(),
122 rmEc.message());
123 // LCOV_EXCL_STOP
124 }
125}
126#endif // !_WIN32
127
128} // namespace
129
130bool atomicWriteFile(const std::filesystem::path& targetPath, std::string_view contents,
131 std::string* errOut)
132{
133 if (targetPath.empty())
134 {
135 if (errOut)
136 *errOut = "atomicWriteFile: empty target path";
137 return false;
138 }
139
140 // Unique-per-call temp suffix: `.tmp.<pid>.<tid>.<counter>`. PID alone
141 // isn't enough because two threads in the same process share it; thread
142 // id alone isn't enough because thread-id reuse across joined threads
143 // could collide; the atomic counter ties everything to the specific
144 // call instance. This implements the header's "concurrent writers in
145 // the same process" claim correctly.
146 auto tmp = targetPath;
147 tmp += buildTempSuffix();
148
149#ifndef _WIN32
150 // POSIX path: open exclusively, write, fsync, rename, fsync(dir).
151 //
152 // SECURITY (CWE-59 symlink-follow / CWE-377 insecure temp file / CWE-367
153 // TOCTOU): the temp name is predictable (`.tmp.<pid>.<tid>.<counter>`), so
154 // open it with O_EXCL (fail if it already exists) and O_NOFOLLOW (never
155 // open through a symlink). Together these ensure we only ever write to a
156 // brand-new regular file we just created, so a pre-planted symlink at the
157 // temp path cannot redirect the write to an attacker-chosen target. On the
158 // rare EEXIST (a leftover temp from a crashed run) regenerate the suffix
159 // and retry a bounded number of times.
160 int fd = -1;
161 for (int attempt = 0; attempt < 8; ++attempt)
162 {
163 if (attempt > 0)
164 {
165 tmp = targetPath;
166 tmp += buildTempSuffix();
167 }
168 fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
169 S_IRUSR | S_IWUSR /* 0600 */);
170 if (fd >= 0 || errno != EEXIST)
171 break;
172 }
173 if (fd < 0)
174 {
175 if (errOut)
176 {
177 *errOut = "open(" + tmp.string() + ") failed: ";
178 *errOut += std::strerror(errno);
179 }
180 return false;
181 }
182
183 // write(2) loop — partial writes are possible on signals or large
184 // payloads (>= SSIZE_MAX), per write(2). Loop until done or hard error.
185 const char* data = contents.data();
186 size_t remaining = contents.size();
187 while (remaining > 0)
188 {
189 ssize_t n = ::write(fd, data, remaining);
190 if (n < 0)
191 {
192 // LCOV_EXCL_START — write(2) failure on a tempfile we just
193 // created requires fault injection (ENOSPC, EIO). The unit
194 // suite can't trigger these reliably; the error path is
195 // exercised manually during ENOSPC investigations.
196 if (errno == EINTR)
197 continue; // retry on signal
198 int saved = errno;
199 ::close(fd);
200 std::error_code rmEc;
201 std::filesystem::remove(tmp, rmEc);
202 if (errOut)
203 {
204 *errOut = "write(" + tmp.string() + ") failed: ";
205 *errOut += std::strerror(saved);
206 }
207 return false;
208 // LCOV_EXCL_STOP
209 }
210 data += n;
211 remaining -= static_cast<size_t>(n);
212 }
213
214 if (::fsync(fd) != 0)
215 {
216 // LCOV_EXCL_START — fsync(fd) on a freshly-written file is the
217 // most-reliable POSIX call we make; failure modes are
218 // hardware-fault-injection territory.
219 int saved = errno;
220 ::close(fd);
221 cleanupTempFile(tmp);
222 if (errOut)
223 {
224 *errOut = "fsync(" + tmp.string() + ") failed: ";
225 *errOut += std::strerror(saved);
226 }
227 return false;
228 // LCOV_EXCL_STOP
229 }
230 if (::close(fd) != 0)
231 {
232 // LCOV_EXCL_START — close(fd) failure after a successful fsync is
233 // even rarer than fsync failure (NFS late-flush); not unit-
234 // testable.
235 int saved = errno;
236 cleanupTempFile(tmp);
237 if (errOut)
238 {
239 *errOut = "close(" + tmp.string() + ") failed: ";
240 *errOut += std::strerror(saved);
241 }
242 return false;
243 // LCOV_EXCL_STOP
244 }
245
246 // Atomic rename: same-filesystem rename(2) is guaranteed atomic by
247 // POSIX. fs::rename forwards to renameat2/rename per glibc.
248 std::error_code renameEc;
249 std::filesystem::rename(tmp, targetPath, renameEc);
250 if (renameEc)
251 {
252 // LCOV_EXCL_START — rename(2) on same filesystem with both paths
253 // owned by us doesn't fail under normal conditions.
254 cleanupTempFile(tmp);
255 if (errOut)
256 {
257 *errOut = "rename(" + tmp.string() + " -> " + targetPath.string() +
258 ") failed: " + renameEc.message();
259 }
260 return false;
261 // LCOV_EXCL_STOP
262 }
263
264 // Best-effort parent fsync — not fatal if it fails (helper logs at warn).
265 fsyncParentDir(targetPath);
266 return true;
267#else
268 // Windows fallback: write + ofstream-flush + explicit-close + rename.
269 // Not durable against power loss (no MoveFileExW with WRITE_THROUGH yet),
270 // but every observable error path is now logged.
271 //
272 // Explicit close-and-check rather than relying on the dtor: a flush
273 // failure in ~ofstream would otherwise be silently lost — the project
274 // already had the same fix applied to stepWriteFile (P2.2).
275 {
276 std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
277 if (!out)
278 {
279 if (errOut)
280 *errOut = "open(" + tmp.string() + ") failed";
281 return false;
282 }
283 out.write(contents.data(), static_cast<std::streamsize>(contents.size()));
284 if (!out.good())
285 {
286 // RAII close still happens via dtor when scope ends, but we
287 // need the file gone before we report the error to the caller.
288 out.close();
289 std::error_code rmEc;
290 std::filesystem::remove(tmp, rmEc);
291 if (errOut)
292 *errOut = "write to " + tmp.string() + " failed";
293 return false;
294 }
295 out.close();
296 if (!out.good())
297 {
298 std::error_code rmEc;
299 std::filesystem::remove(tmp, rmEc);
300 if (errOut)
301 *errOut = "close(" + tmp.string() + ") failed (flush error)";
302 return false;
303 }
304 }
305 std::error_code renameEc;
306 std::filesystem::rename(tmp, targetPath, renameEc);
307 if (renameEc)
308 {
309 // No POSIX-only cleanupTempFile() helper here — same intent inline.
310 std::error_code rmEc;
311 std::filesystem::remove(tmp, rmEc);
312 if (errOut)
313 *errOut = "rename failed: " + renameEc.message();
314 return false;
315 }
316 return true;
317#endif
318}
319
320} // namespace core
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
void cleanupTempFile(const std::filesystem::path &tmp)
bool fsyncParentDir(const std::filesystem::path &target)
bool atomicWriteFile(const std::filesystem::path &targetPath, std::string_view contents, std::string *errOut=nullptr)
Atomically and durably write contents to targetPath.