OpenVPN 3 Core Library
Loading...
Searching...
No Matches
persistfile.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#ifndef OPENVPN_COMMON_PERSISTFILE_H
13#define OPENVPN_COMMON_PERSISTFILE_H
14
15#include <sys/types.h> // for open(), lseek(), ftruncate()
16#include <sys/stat.h> // for open()
17#include <fcntl.h> // for open()
18#include <unistd.h> // for write(), lseek(), ftruncate()
19#include <errno.h>
20
21#include <string>
22
29
30namespace openvpn {
32{
33 public:
34 PersistentFile(const std::string &fn_arg)
35 : fn(fn_arg)
36 {
37 const int f = ::open(fn.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
38 if (f < 0)
39 syserr("open");
40 fd.reset(f);
41 }
42
43 void write(const void *buf, size_t count)
44 {
45 const off_t off = ::lseek(fd(), 0, SEEK_SET);
46 if (off < 0)
47 syserr("seek");
48 if (off)
49 err("unexpected seek");
50 if (::ftruncate(fd(), 0) < 0)
51 syserr("truncate");
52 const ssize_t len = write_retry(fd(), buf, count);
53 if (len < 0)
54 syserr("write");
55 if (static_cast<size_t>(len) != count || len != ::lseek(fd(), 0, SEEK_CUR))
56 err("incomplete write");
57 if (::ftruncate(fd(), len) < 0)
58 syserr("truncate");
59 }
60
61 struct stat stat()
62 {
63 struct stat s;
64 if (::fstat(fd(), &s) < 0)
65 syserr("fstat");
66 return s;
67 }
68
69 void write(const Buffer &buf)
70 {
71 write(buf.c_data(), buf.size());
72 }
73
74 void write(const std::string &str)
75 {
76 write(str.c_str(), str.length());
77 }
78
79 private:
80 void syserr(const char *type)
81 {
82 const int eno = errno;
83 OPENVPN_THROW_EXCEPTION(fn << " : " << type << " error : " << strerror_str(eno));
84 }
85
86 void err(const char *type)
87 {
88 OPENVPN_THROW_EXCEPTION(fn << " : " << type << " error");
89 }
90
91 std::string fn;
93};
94} // namespace openvpn
95
96#endif
const T * c_data() const
Returns a const pointer to the start of the buffer.
Definition buffer.hpp:1194
size_t size() const
Returns the size of the buffer in T objects.
Definition buffer.hpp:1242
void syserr(const char *type)
void err(const char *type)
void write(const Buffer &buf)
void write(const std::string &str)
PersistentFile(const std::string &fn_arg)
void write(const void *buf, size_t count)
void reset(const int fd_arg)
Definition scoped_fd.hpp:68
#define OPENVPN_THROW_EXCEPTION(stuff)
ssize_t write_retry(int fd, const void *buf, size_t count)
Definition write.hpp:20
std::string strerror_str(const int errnum)
Definition strerror.hpp:21
os<< "Session Name: "<< tbc-> session_name<< '\n';os<< "Layer: "<< tbc-> layer str()<< '\n'
auto f(const Thing1 t)