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.connect(bind(&Socket::ExceptionEventHandler, this, _1));
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 // XXX, TODO: add SetErrorHandling() function
175 /* if (OnError.HasObservers()) {*/
176 SocketErrorEventArgs sea(ex);
186 * Processes errors that have occured for the socket.
188 * @param - Event arguments for the socket error.
191 int Socket::ExceptionEventHandler(const EventArgs&)
193 HandleSocketError(SocketException(
194 "select() returned fd in except fdset", GetError()));
200 * Checks whether data should be read for this socket object.
202 * @returns true if the socket should be registered for reading, false otherwise.
204 bool Socket::WantsToRead(void) const
210 * Checks whether data should be written for this socket object.
212 * @returns true if the socket should be registered for writing, false otherwise.
214 bool Socket::WantsToWrite(void) const
220 * Formats a sockaddr in a human-readable way.
222 * @returns A string describing the sockaddr.
224 string Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len)
226 char host[NI_MAXHOST];
227 char service[NI_MAXSERV];
229 if (getnameinfo(address, len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
230 throw SocketException("getnameinfo() failed",
231 GetLastSocketError());
234 s << "[" << host << "]:" << service;
239 * Returns a string describing the local address of the socket.
241 * @returns A string describing the local address.
243 string Socket::GetClientAddress(void)
245 sockaddr_storage sin;
246 socklen_t len = sizeof(sin);
248 if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) {
249 HandleSocketError(SocketException(
250 "getsockname() failed", GetError()));
255 return GetAddressFromSockaddr((sockaddr *)&sin, len);
259 * Returns a string describing the peer address of the socket.
261 * @returns A string describing the peer address.
263 string Socket::GetPeerAddress(void)
265 sockaddr_storage sin;
266 socklen_t len = sizeof(sin);
268 if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) {
269 HandleSocketError(SocketException(
270 "getpeername() failed", GetError()));
275 return GetAddressFromSockaddr((sockaddr *)&sin, len);
279 * Constructor for the SocketException class.
281 * @param message The error message.
282 * @param errorCode The error code.
284 SocketException::SocketException(const string& message, int errorCode)
287 string details = Win32Exception::FormatErrorCode(errorCode);
289 string details = PosixException::FormatErrorCode(errorCode);
292 string msg = message + ": " + details;
293 SetMessage(msg.c_str());