OpenVPN 3 Core Library
Loading...
Searching...
No Matches
scoped_asio_stream.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// A scoped Asio stream that is automatically closed by its destructor.
13
14#ifndef OPENVPN_ASIO_SCOPED_ASIO_STREAM_H
15#define OPENVPN_ASIO_SCOPED_ASIO_STREAM_H
16
18
19namespace openvpn {
20
21template <typename STREAM>
23{
26
27 public:
28 typedef STREAM *base_type;
29
31 : obj_(undefined())
32 {
33 }
34
35 explicit ScopedAsioStream(STREAM *obj)
36 : obj_(obj)
37 {
38 }
39
40 static STREAM *undefined()
41 {
42 return nullptr;
43 }
44
45 STREAM *release()
46 {
47 STREAM *ret = obj_;
48 obj_ = nullptr;
49 // OPENVPN_LOG("**** SAS RELEASE=" << ret);
50 return ret;
51 }
52
53 static bool defined_static(STREAM *obj)
54 {
55 return obj != nullptr;
56 }
57
58 bool defined() const
59 {
60 return defined_static(obj_);
61 }
62
63 STREAM *operator()() const
64 {
65 return obj_;
66 }
67
68 void reset(STREAM *obj)
69 {
70 close();
71 obj_ = obj;
72 // OPENVPN_LOG("**** SAS RESET=" << obj_);
73 }
74
75 // unusual semantics: replace obj without closing it first
76 void replace(STREAM *obj)
77 {
78 // OPENVPN_LOG("**** SAS REPLACE " << obj_ << " -> " << obj);
79 obj_ = obj;
80 }
81
82 // return false if close error
83 bool close()
84 {
85 if (defined())
86 {
87 // OPENVPN_LOG("**** SAS CLOSE obj=" << obj_);
88 delete obj_;
89 obj_ = nullptr;
90 }
91 return true;
92 }
93
95 {
96 // OPENVPN_LOG("**** SAS DESTRUCTOR");
97 close();
98 }
99
100 private:
101 STREAM *obj_;
102};
103
104} // namespace openvpn
105
106#endif
ScopedAsioStream(const ScopedAsioStream &)=delete
static bool defined_static(STREAM *obj)
ScopedAsioStream & operator=(const ScopedAsioStream &)=delete
std::string ret