OpenVPN 3 Core Library
Loading...
Searching...
No Matches
writeprivate.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#pragma once
13
14#include <string>
15
17
18#if !defined(OPENVPN_PLATFORM_WIN)
19#include <sys/types.h> // for open(), ftruncate()
20#include <sys/stat.h> // for open()
21#include <fcntl.h> // for open()
22#include <unistd.h> // for write(), ftruncate()
23#include <errno.h>
24#endif
25
29
30#if !defined(OPENVPN_PLATFORM_WIN)
34#endif
35
36namespace openvpn {
37
38#if defined(OPENVPN_PLATFORM_WIN)
39
40inline void write_private(const std::string &path, const void *buf, size_t count)
41{
42 OPENVPN_THROW_EXCEPTION("write_private('" << path << "') : not implemented on Windows yet");
43}
44
45#else
46
47inline void write_private(const std::string &path, const void *buf, ssize_t count)
48{
49 ScopedFD fd(::open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
50 if (!fd.defined())
51 {
52 const int eno = errno;
53 OPENVPN_THROW_EXCEPTION(path << " : open error : " << strerror_str(eno));
54 }
55 if (::ftruncate(fd(), 0) < 0)
56 {
57 const int eno = errno;
58 OPENVPN_THROW_EXCEPTION(path << " : truncate error : " << strerror_str(eno));
59 }
60 const ssize_t len = write_retry(fd(), buf, count);
61 if (len == -1)
62 {
63 const int eno = errno;
64 OPENVPN_THROW_EXCEPTION(path << " : write error : " << strerror_str(eno));
65 }
66 else if (len != count)
67 OPENVPN_THROW_EXCEPTION(path << " : unexpected write size");
68 if (!fd.close())
69 {
70 const int eno = errno;
71 OPENVPN_THROW_EXCEPTION(path << " : close error : " << strerror_str(eno));
72 }
73}
74
75#endif
76
77inline void write_private(const std::string &path, const Buffer &buf)
78{
79 write_private(path, buf.c_data(), buf.size());
80}
81
82inline void write_private(const std::string &path, const std::string &str)
83{
84 write_private(path, str.c_str(), str.length());
85}
86
87} // namespace openvpn
const T * c_data() const
Returns a const pointer to the start of the buffer.
Definition buffer.hpp:1177
size_t size() const
Returns the size of the buffer in T objects.
Definition buffer.hpp:1225
bool defined() const
Definition scoped_fd.hpp:58
#define OPENVPN_THROW_EXCEPTION(stuff)
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
ssize_t write_retry(int fd, const void *buf, size_t count)
Definition write.hpp:20
void write_private(const std::string &path, const void *buf, ssize_t count)
std::string strerror_str(const int errnum)
Definition strerror.hpp:21