0
0
mirror of https://github.com/OpenVPN/openvpn3.git synced 2024-09-20 20:13:05 +02:00
openvpn3/openvpn/common/scoped_fd.hpp
James Yonan 069de90ffd minor C++11 updates:
* rename BOOST_NOEXCEPT to noexcept

* verify that certain classes are noexcept move constructable
  including Option, Buffer, BufferAllocated, RunContext::Thread
2015-04-23 12:49:25 -06:00

133 lines
2.9 KiB
C++

// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2015 OpenVPN Technologies, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// A scoped file descriptor that is automatically closed by its destructor.
#ifndef OPENVPN_COMMON_SCOPED_FD_H
#define OPENVPN_COMMON_SCOPED_FD_H
#include <unistd.h> // for close()
#include <boost/noncopyable.hpp>
namespace openvpn {
class ScopedFD : boost::noncopyable
{
public:
typedef int base_type;
ScopedFD() : fd(undefined()) {}
explicit ScopedFD(const int fd_arg)
: fd(fd_arg) {}
static int undefined() { return -1; }
int release()
{
const int ret = fd;
fd = -1;
//OPENVPN_LOG("**** SFD RELEASE=" << ret);
return ret;
}
static bool defined_static(int fd)
{
return fd >= 0;
}
bool defined() const
{
return defined_static(fd);
}
int operator()() const
{
return fd;
}
void reset(const int fd_arg)
{
close();
fd = fd_arg;
//OPENVPN_LOG("**** SFD RESET=" << fd);
}
void reset()
{
close();
}
// unusual semantics: replace fd without closing it first
void replace(const int fd_arg)
{
//OPENVPN_LOG("**** SFD REPLACE " << fd << " -> " << fd_arg);
fd = fd_arg;
}
// return false if close error
bool close()
{
if (defined())
{
const int status = ::close(fd);
post_close(status);
//OPENVPN_LOG("**** SFD CLOSE fd=" << fd << " status=" << status);
fd = -1;
return status == 0;
}
else
return true;
}
virtual void post_close(const int close_status)
{
}
virtual ~ScopedFD()
{
//OPENVPN_LOG("**** SFD DESTRUCTOR");
close();
}
ScopedFD(ScopedFD&& other) noexcept
{
fd = other.fd;
other.fd = -1;
}
ScopedFD& operator=(ScopedFD&& other) noexcept
{
close();
fd = other.fd;
other.fd = -1;
return *this;
}
private:
int fd;
};
} // namespace openvpn
#endif // OPENVPN_COMMON_SCOPED_FD_H