icinga2/base/socket.cpp

378 lines
8.1 KiB
C++
Raw Normal View History

/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012 Icinga Development Team (http://www.icinga.org/) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
2012-05-11 13:33:57 +02:00
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
2012-03-28 13:24:49 +02:00
#include "i2-base.h"
using namespace icinga;
/**
* Constructor for the Socket class.
*/
2012-03-28 13:24:49 +02:00
Socket::Socket(void)
{
m_FD = INVALID_SOCKET;
}
/**
* Destructor for the Socket class.
*/
2012-03-28 13:24:49 +02:00
Socket::~Socket(void)
{
2012-06-24 02:56:48 +02:00
{
mutex::scoped_lock lock(m_Mutex);
CloseInternal(true);
}
2012-03-28 13:24:49 +02:00
}
void Socket::Start(void)
{
2012-06-24 02:56:48 +02:00
assert(!m_ReadThread.joinable() && !m_WriteThread.joinable());
assert(GetFD() != INVALID_SOCKET);
2012-04-18 15:22:25 +02:00
2012-06-24 02:56:48 +02:00
m_ReadThread = thread(boost::bind(&Socket::ReadThreadProc, static_cast<Socket::Ptr>(GetSelf())));
m_ReadThread.detach();
2012-06-24 02:56:48 +02:00
m_WriteThread = thread(boost::bind(&Socket::WriteThreadProc, static_cast<Socket::Ptr>(GetSelf())));
m_WriteThread.detach();
2012-03-28 13:24:49 +02:00
}
/**
* Sets the file descriptor for this socket object.
*
* @param fd The file descriptor.
*/
2012-03-28 13:24:49 +02:00
void Socket::SetFD(SOCKET fd)
{
2012-06-22 11:47:06 +02:00
/* mark the socket as non-blocking */
2012-05-11 12:44:04 +02:00
if (fd != INVALID_SOCKET) {
#ifdef F_GETFL
int flags;
flags = fcntl(fd, F_GETFL, 0);
if (flags < 0)
throw PosixException("fcntl failed", errno);
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
throw PosixException("fcntl failed", errno);
#else /* F_GETFL */
2012-06-24 02:56:48 +02:00
unsigned long lTrue = 1;
ioctlsocket(fd, FIONBIO, &lTrue);
2012-05-11 12:44:04 +02:00
#endif /* F_GETFL */
}
2012-03-28 13:24:49 +02:00
m_FD = fd;
}
/**
* Retrieves the file descriptor for this socket object.
*
* @returns The file descriptor.
*/
2012-03-28 13:24:49 +02:00
SOCKET Socket::GetFD(void) const
{
return m_FD;
}
/**
* Closes the socket.
*/
2012-03-28 13:24:49 +02:00
void Socket::Close(void)
{
2012-06-24 02:56:48 +02:00
mutex::scoped_lock lock(m_Mutex);
2012-04-24 14:02:15 +02:00
CloseInternal(false);
2012-03-28 13:24:49 +02:00
}
/**
* Closes the socket.
*
* @param from_dtor Whether this method was called from the destructor.
*/
2012-04-24 14:02:15 +02:00
void Socket::CloseInternal(bool from_dtor)
2012-03-28 13:24:49 +02:00
{
if (m_FD == INVALID_SOCKET)
return;
closesocket(m_FD);
m_FD = INVALID_SOCKET;
2012-03-28 13:24:49 +02:00
/* nobody can possibly have a valid event subscription when the
destructor has been called */
if (!from_dtor) {
2012-06-24 02:56:48 +02:00
Event::Ptr ev = boost::make_shared<Event>();
ev->OnEventDelivered.connect(boost::bind(boost::ref(OnClosed), GetSelf()));
Event::Post(ev);
}
2012-03-28 13:24:49 +02:00
}
/**
2012-05-26 20:00:03 +02:00
* Retrieves the last error that occured for the socket.
*
* @returns An error code.
*/
2012-05-26 20:00:03 +02:00
int Socket::GetError(void) const
{
int opt;
socklen_t optlen = sizeof(opt);
int rc = getsockopt(GetFD(), SOL_SOCKET, SO_ERROR, (char *)&opt, &optlen);
2012-05-26 20:00:03 +02:00
if (rc >= 0)
return opt;
return 0;
}
/**
* Retrieves the last socket error.
*
* @returns An error code.
*/
int Socket::GetLastSocketError(void)
{
2012-04-22 16:45:31 +02:00
#ifdef _WIN32
2012-05-26 20:00:03 +02:00
return WSAGetLastError();
2012-04-22 16:45:31 +02:00
#else /* _WIN32 */
2012-05-26 20:00:03 +02:00
return errno;
2012-04-22 16:45:31 +02:00
#endif /* _WIN32 */
2012-05-26 20:00:03 +02:00
}
/**
* Handles a socket error by calling the OnError event or throwing an exception
* when there are no observers for the OnError event.
*
2012-05-26 21:30:04 +02:00
* @param ex An exception.
2012-05-26 20:00:03 +02:00
*/
2012-05-29 16:24:55 +02:00
void Socket::HandleSocketError(const std::exception& ex)
2012-05-26 20:00:03 +02:00
{
2012-06-15 19:32:41 +02:00
if (!OnError.empty()) {
2012-06-24 02:56:48 +02:00
Event::Ptr ev = boost::make_shared<Event>();
ev->OnEventDelivered.connect(boost::bind(boost::ref(OnError), GetSelf(), ex));
Event::Post(ev);
2012-06-24 02:56:48 +02:00
CloseInternal(false);
2012-06-15 19:32:41 +02:00
} else {
2012-05-26 21:30:04 +02:00
throw ex;
2012-06-15 19:32:41 +02:00
}
}
/**
* Processes errors that have occured for the socket.
*/
2012-06-24 02:56:48 +02:00
void Socket::HandleException(void)
2012-03-28 13:24:49 +02:00
{
2012-05-26 20:00:03 +02:00
HandleSocketError(SocketException(
"select() returned fd in except fdset", GetError()));
2012-03-28 13:24:49 +02:00
}
/**
* Checks whether data should be read for this socket object.
*
* @returns true if the socket should be registered for reading, false otherwise.
*/
2012-03-28 13:24:49 +02:00
bool Socket::WantsToRead(void) const
{
return false;
}
2012-06-24 02:56:48 +02:00
void Socket::HandleReadable(void)
{ }
/**
* Checks whether data should be written for this socket object.
*
* @returns true if the socket should be registered for writing, false otherwise.
*/
2012-03-28 13:24:49 +02:00
bool Socket::WantsToWrite(void) const
{
return false;
}
2012-06-24 02:56:48 +02:00
void Socket::HandleWritable(void)
{ }
/**
* Formats a sockaddr in a human-readable way.
*
* @returns A string describing the sockaddr.
*/
string Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len)
{
char host[NI_MAXHOST];
char service[NI_MAXSERV];
if (getnameinfo(address, len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
2012-05-26 21:30:04 +02:00
throw SocketException("getnameinfo() failed",
GetLastSocketError());
stringstream s;
s << "[" << host << "]:" << service;
return s.str();
}
/**
* Returns a string describing the local address of the socket.
*
* @returns A string describing the local address.
*/
string Socket::GetClientAddress(void)
{
2012-06-24 02:56:48 +02:00
mutex::scoped_lock lock(m_Mutex);
sockaddr_storage sin;
socklen_t len = sizeof(sin);
if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) {
2012-05-26 20:00:03 +02:00
HandleSocketError(SocketException(
"getsockname() failed", GetError()));
return string();
}
return GetAddressFromSockaddr((sockaddr *)&sin, len);
}
/**
* Returns a string describing the peer address of the socket.
*
* @returns A string describing the peer address.
*/
string Socket::GetPeerAddress(void)
{
2012-06-24 02:56:48 +02:00
mutex::scoped_lock lock(m_Mutex);
sockaddr_storage sin;
socklen_t len = sizeof(sin);
if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) {
2012-05-26 20:00:03 +02:00
HandleSocketError(SocketException(
"getpeername() failed", GetError()));
return string();
}
return GetAddressFromSockaddr((sockaddr *)&sin, len);
}
2012-05-26 20:00:03 +02:00
/**
* Constructor for the SocketException class.
*
* @param message The error message.
* @param errorCode The error code.
*/
SocketException::SocketException(const string& message, int errorCode)
{
#ifdef _WIN32
string details = Win32Exception::FormatErrorCode(errorCode);
#else /* _WIN32 */
string details = PosixException::FormatErrorCode(errorCode);
#endif /* _WIN32 */
string msg = message + ": " + details;
SetMessage(msg.c_str());
2012-05-29 16:24:55 +02:00
}
2012-06-24 02:56:48 +02:00
void Socket::ReadThreadProc(void)
{
mutex::scoped_lock lock(m_Mutex);
for (;;) {
fd_set readfds, exceptfds;
FD_ZERO(&readfds);
FD_ZERO(&exceptfds);
int fd = GetFD();
if (fd == INVALID_SOCKET)
return;
if (WantsToRead())
FD_SET(fd, &readfds);
FD_SET(fd, &exceptfds);
lock.unlock();
timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
int rc = select(fd + 1, &readfds, NULL, &exceptfds, &tv);
lock.lock();
if (rc < 0) {
HandleSocketError(SocketException("select() failed", GetError()));
return;
}
if (FD_ISSET(fd, &readfds))
HandleReadable();
if (FD_ISSET(fd, &exceptfds))
HandleException();
if (WantsToWrite())
; /* notify Write thread */
}
}
void Socket::WriteThreadProc(void)
{
mutex::scoped_lock lock(m_Mutex);
for (;;) {
fd_set writefds;
FD_ZERO(&writefds);
int fd = GetFD();
while (!WantsToWrite()) {
if (GetFD() == INVALID_SOCKET)
return;
lock.unlock();
Sleep(500);
lock.lock();
}
FD_SET(fd, &writefds);
lock.unlock();
int rc = select(fd + 1, NULL, &writefds, NULL, NULL);
lock.lock();
if (rc < 0) {
HandleSocketError(SocketException("select() failed", GetError()));
return;
}
if (FD_ISSET(fd, &writefds))
HandleWritable();
}
}
mutex& Socket::GetMutex(void) const
{
return m_Mutex;
}