1 /******************************************************************************
3 * Copyright (C) 2012 Icinga Development Team (http://www.icinga.org/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
22 using namespace icinga;
25 * A collection of weak pointers to Socket objects which have been
26 * registered with the socket sub-system.
28 Socket::CollectionType Socket::Sockets;
31 * Constructor for the Socket class.
35 m_FD = INVALID_SOCKET;
39 * Destructor for the Socket class.
47 * Registers the socket and starts handling events for it.
49 void Socket::Start(void)
51 assert(m_FD != INVALID_SOCKET);
53 OnException += bind_weak(&Socket::ExceptionEventHandler, shared_from_this());
55 Sockets.push_back(static_pointer_cast<Socket>(shared_from_this()));
59 * Unregisters the sockets and stops handling events for it.
61 void Socket::Stop(void)
63 Sockets.remove_if(WeakPtrEqual<Socket>(this));
67 * Sets the file descriptor for this socket object.
69 * @param fd The file descriptor.
71 void Socket::SetFD(SOCKET fd)
73 unsigned long lTrue = 1;
75 if (fd != INVALID_SOCKET) {
78 flags = fcntl(fd, F_GETFL, 0);
80 throw PosixException("fcntl failed", errno);
82 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
83 throw PosixException("fcntl failed", errno);
85 ioctlsocket(fd, FIONBIO, &lTrue);
93 * Retrieves the file descriptor for this socket object.
95 * @returns The file descriptor.
97 SOCKET Socket::GetFD(void) const
105 void Socket::Close(void)
107 CloseInternal(false);
113 * @param from_dtor Whether this method was called from the destructor.
115 void Socket::CloseInternal(bool from_dtor)
117 if (m_FD == INVALID_SOCKET)
121 m_FD = INVALID_SOCKET;
123 /* nobody can possibly have a valid event subscription when the
124 destructor has been called */
129 ea.Source = shared_from_this();
135 * Retrieves the last error that occured for the socket.
137 * @returns An error code.
139 int Socket::GetError(void) const
142 socklen_t optlen = sizeof(opt);
144 int rc = getsockopt(GetFD(), SOL_SOCKET, SO_ERROR, (char *)&opt, &optlen);
153 * Retrieves the last socket error.
155 * @returns An error code.
157 int Socket::GetLastSocketError(void)
160 return WSAGetLastError();
167 * Handles a socket error by calling the OnError event or throwing an exception
168 * when there are no observers for the OnError event.
170 * @param ex An exception.
172 void Socket::HandleSocketError(const std::exception& ex)
174 if (OnError.HasObservers()) {
175 SocketErrorEventArgs sea(ex);
185 * Processes errors that have occured for the socket.
187 * @param - Event arguments for the socket error.
190 int Socket::ExceptionEventHandler(const EventArgs&)
192 HandleSocketError(SocketException(
193 "select() returned fd in except fdset", GetError()));
199 * Checks whether data should be read for this socket object.
201 * @returns true if the socket should be registered for reading, false otherwise.
203 bool Socket::WantsToRead(void) const
209 * Checks whether data should be written for this socket object.
211 * @returns true if the socket should be registered for writing, false otherwise.
213 bool Socket::WantsToWrite(void) const
219 * Formats a sockaddr in a human-readable way.
221 * @returns A string describing the sockaddr.
223 string Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len)
225 char host[NI_MAXHOST];
226 char service[NI_MAXSERV];
228 if (getnameinfo(address, len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
229 throw SocketException("getnameinfo() failed",
230 GetLastSocketError());
233 s << "[" << host << "]:" << service;
238 * Returns a string describing the local address of the socket.
240 * @returns A string describing the local address.
242 string Socket::GetClientAddress(void)
244 sockaddr_storage sin;
245 socklen_t len = sizeof(sin);
247 if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) {
248 HandleSocketError(SocketException(
249 "getsockname() failed", GetError()));
254 return GetAddressFromSockaddr((sockaddr *)&sin, len);
258 * Returns a string describing the peer address of the socket.
260 * @returns A string describing the peer address.
262 string Socket::GetPeerAddress(void)
264 sockaddr_storage sin;
265 socklen_t len = sizeof(sin);
267 if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) {
268 HandleSocketError(SocketException(
269 "getpeername() failed", GetError()));
274 return GetAddressFromSockaddr((sockaddr *)&sin, len);
278 * Constructor for the SocketException class.
280 * @param message The error message.
281 * @param errorCode The error code.
283 SocketException::SocketException(const string& message, int errorCode)
286 string details = Win32Exception::FormatErrorCode(errorCode);
288 string details = PosixException::FormatErrorCode(errorCode);
291 string msg = message + ": " + details;
292 SetMessage(msg.c_str());