OpenVPN 3 Core Library
Loading...
Searching...
No Matches
fileatomic.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// Atomic file-handling methods.
13
14#pragma once
15
17
18#if defined(OPENVPN_PLATFORM_WIN)
19#error atomic file methods not supported on Windows
20#endif
21
22#include <stdio.h> // for rename()
23#include <unistd.h> // for unlink()
24#include <errno.h>
25#include <cstring>
26
31
32namespace openvpn {
33// Atomically write binary buffer to file (relies on
34// the atomicity of rename())
35inline void write_binary_atomic(const std::string &fn,
36 const std::string &tmpdir,
37 const mode_t mode,
38 const std::uint64_t mtime_ns, // set explicit modification-time in nanoseconds since epoch, or 0 to defer to system
39 const ConstBuffer &buf,
40 StrongRandomAPI &rng)
41{
42 // generate temporary filename
43 const std::string tfn = tmp_filename(fn, tmpdir, rng);
44
45 // write to temporary file
46 write_binary_unix(tfn, mode, mtime_ns, buf);
47
48 // then move into position
49 if (::rename(tfn.c_str(), fn.c_str()) == -1)
50 {
51 const int eno = errno;
52 ::unlink(tfn.c_str()); // move failed, so delete the temporary file
53 OPENVPN_THROW(file_unix_error, "error moving '" << tfn << "' -> '" << fn << "' : " << strerror_str(eno));
54 }
55}
56
57inline void write_binary_atomic(const std::string &fn,
58 const std::string &tmpdir,
59 const mode_t mode,
60 const std::uint64_t mtime_ns,
61 const Buffer &buf,
62 StrongRandomAPI &rng)
63{
64 write_binary_atomic(fn, tmpdir, mode, mtime_ns, const_buffer_ref(buf), rng);
65}
66} // namespace openvpn
Abstract base class for cryptographically strong random number generators.
Definition randapi.hpp:228
#define OPENVPN_THROW(exc, stuff)
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
std::string tmp_filename(const std::string &fn, const std::string &tmpdir, StrongRandomAPI &rng)
void write_binary_unix(const std::string &fn, const mode_t mode, const std::uint64_t mtime_ns, const void *buf, const ssize_t size)
Definition fileunix.hpp:44
ConstBufferType< T > & const_buffer_ref(BufferType< T > &src)
Definition buffer.hpp:1873
void write_binary_atomic(const std::string &fn, const std::string &tmpdir, const mode_t mode, const std::uint64_t mtime_ns, const ConstBuffer &buf, StrongRandomAPI &rng)
std::string strerror_str(const int errnum)
Definition strerror.hpp:21