12#ifndef OPENVPN_COMMON_TEMPFILE_H
13#define OPENVPN_COMMON_TEMPFILE_H
17#if defined(OPENVPN_PLATFORM_WIN)
18#error temporary file methods not supported on Windows
47 :
fn(new char[fn_template.length() + 1]),
50 constexpr char pattern[] =
"XXXXXX";
51 constexpr size_t patternLen =
sizeof(pattern) - 1;
52 std::memcpy(
fn.get(), fn_template.c_str(), fn_template.length() + 1);
53 const size_t pos = fn_template.rfind(pattern);
54 if (pos != std::string::npos)
56 if (fn_template.length() > pos + patternLen)
58 const auto suffixlen = fn_template.length() - pos - patternLen;
59 fd.
reset(::mkstemps(
fn.get(), numeric_cast<int>(suffixlen)));
65 const int eno = errno;
66 OPENVPN_THROW(tempfile_exception,
"error creating temporary file from template: " << fn_template <<
" : " <<
strerror_str(eno));
70 OPENVPN_THROW(tempfile_exception,
"badly formed temporary file template: " << fn_template);
81 const off_t off = ::lseek(
fd(), 0, SEEK_SET);
84 const int eno = errno;
94 if (::ftruncate(
fd(), 0) < 0)
96 const int eno = errno;
101 void write(
const std::string &content)
103 const ssize_t size =
write_retry(
fd(), content.c_str(), content.length());
106 const int eno = errno;
109 else if (
static_cast<std::string::size_type
>(size) != content.length())
133 const int eno = errno;
155 std::unique_ptr<char[]>
fn;
void reset(const int fd_arg)
void set_delete(const bool del_flag)
std::string filename() const
void write(const std::string &content)
OPENVPN_EXCEPTION(tempfile_exception)
std::unique_ptr< char[]> fn
TempFile(const std::string &fn_template, const bool fn_delete)
#define OPENVPN_THROW(exc, stuff)
OutT numeric_cast(InT inVal)
Tests attempted casts to ensure the input value does not exceed the capacity of the output type.
bool buf_read(const int fd, Buffer &buf, const std::string &title)
ssize_t write_retry(int fd, const void *buf, size_t count)
std::string strerror_str(const int errnum)
std::string to_string() const