OpenVPN 3 Core Library
Loading...
Searching...
No Matches
scoped_handle.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// scoped HANDLE for windows
13
14#ifndef OPENVPN_WIN_SCOPED_HANDLE_H
15#define OPENVPN_WIN_SCOPED_HANDLE_H
16
17#include <windows.h>
18
21
22namespace openvpn::Win {
24{
25 ScopedHANDLE(const ScopedHANDLE &) = delete;
27
28 public:
29 typedef HANDLE base_type;
30
32 : handle(Handle::undefined())
33 {
34 }
35
36 explicit ScopedHANDLE(HANDLE h)
37 : handle(h)
38 {
39 }
40
41 HANDLE release()
42 {
43 const HANDLE ret = handle;
44 handle = nullptr;
45 return ret;
46 }
47
48 bool defined() const
49 {
50 return Handle::defined(handle);
51 }
52
53 HANDLE operator()() const
54 {
55 return handle;
56 }
57
58 HANDLE *ref()
59 {
60 return &handle;
61 }
62
63 void reset(HANDLE h)
64 {
65 close();
66 handle = h;
67 }
68
69 void reset()
70 {
71 close();
72 }
73
74 // unusual semantics: replace handle without closing it first
75 void replace(HANDLE h)
76 {
77 handle = h;
78 }
79
80 bool close()
81 {
82 if (defined())
83 {
84 const BOOL ret = ::CloseHandle(handle);
85 // OPENVPN_LOG("**** SH CLOSE hand=" << handle << " ret=" << ret);
86 handle = nullptr;
87 return ret != 0;
88 }
89 else
90 return true;
91 }
92
94 {
95 close();
96 }
97
98 ScopedHANDLE(ScopedHANDLE &&other) noexcept
99 {
100 handle = other.handle;
101 other.handle = nullptr;
102 }
103
105 {
106 close();
107 handle = other.handle;
108 other.handle = nullptr;
109 return *this;
110 }
111
112 private:
113 HANDLE handle;
114};
115
116} // namespace openvpn::Win
117
118#endif
ScopedHANDLE & operator=(ScopedHANDLE &&other) noexcept
ScopedHANDLE(const ScopedHANDLE &)=delete
ScopedHANDLE & operator=(const ScopedHANDLE &)=delete
ScopedHANDLE(ScopedHANDLE &&other) noexcept
bool defined(HANDLE handle)
Definition handle.hpp:25
std::string ret