]> granicus.if.org Git - icinga2/blob - base/socket.cpp
Replaced custom event code with Boost.Signals.
[icinga2] / base / socket.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012 Icinga Development Team (http://www.icinga.org/)        *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
20 #include "i2-base.h"
21
22 using namespace icinga;
23
24 /**
25  * A collection of weak pointers to Socket objects which have been
26  * registered with the socket sub-system.
27  */
28 Socket::CollectionType Socket::Sockets;
29
30 /**
31  * Constructor for the Socket class.
32  */
33 Socket::Socket(void)
34 {
35         m_FD = INVALID_SOCKET;
36 }
37
38 /**
39  * Destructor for the Socket class.
40  */
41 Socket::~Socket(void)
42 {
43         CloseInternal(true);
44 }
45
46 /**
47  * Registers the socket and starts handling events for it.
48  */
49 void Socket::Start(void)
50 {
51         assert(m_FD != INVALID_SOCKET);
52
53         OnException.connect(bind(&Socket::ExceptionEventHandler, this, _1));
54
55         Sockets.push_back(static_pointer_cast<Socket>(shared_from_this()));
56 }
57
58 /**
59  * Unregisters the sockets and stops handling events for it.
60  */
61 void Socket::Stop(void)
62 {
63         Sockets.remove_if(WeakPtrEqual<Socket>(this));
64 }
65
66 /**
67  * Sets the file descriptor for this socket object.
68  *
69  * @param fd The file descriptor.
70  */
71 void Socket::SetFD(SOCKET fd)
72 {
73         unsigned long lTrue = 1;
74
75         if (fd != INVALID_SOCKET) {
76 #ifdef F_GETFL
77                 int flags;
78                 flags = fcntl(fd, F_GETFL, 0);
79                 if (flags < 0)
80                         throw PosixException("fcntl failed", errno);
81
82                 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
83                         throw PosixException("fcntl failed", errno);
84 #else /* F_GETFL */
85                 ioctlsocket(fd, FIONBIO, &lTrue);
86 #endif /* F_GETFL */
87         }
88
89         m_FD = fd;
90 }
91
92 /**
93  * Retrieves the file descriptor for this socket object.
94  *
95  * @returns The file descriptor.
96  */
97 SOCKET Socket::GetFD(void) const
98 {
99         return m_FD;
100 }
101
102 /**
103  * Closes the socket.
104  */
105 void Socket::Close(void)
106 {
107         CloseInternal(false);
108 }
109
110 /**
111  * Closes the socket.
112  *
113  * @param from_dtor Whether this method was called from the destructor.
114  */
115 void Socket::CloseInternal(bool from_dtor)
116 {
117         if (m_FD == INVALID_SOCKET)
118                 return;
119
120         closesocket(m_FD);
121         m_FD = INVALID_SOCKET;
122
123         /* nobody can possibly have a valid event subscription when the
124                 destructor has been called */
125         if (!from_dtor) {
126                 Stop();
127
128                 EventArgs ea;
129                 ea.Source = shared_from_this();
130                 OnClosed(ea);
131         }
132 }
133
134 /**
135  * Retrieves the last error that occured for the socket.
136  *
137  * @returns An error code.
138  */
139 int Socket::GetError(void) const
140 {
141         int opt;
142         socklen_t optlen = sizeof(opt);
143
144         int rc = getsockopt(GetFD(), SOL_SOCKET, SO_ERROR, (char *)&opt, &optlen);
145
146         if (rc >= 0)
147                 return opt;
148
149         return 0;
150 }
151
152 /**
153  * Retrieves the last socket error.
154  *
155  * @returns An error code.
156  */
157 int Socket::GetLastSocketError(void)
158 {
159 #ifdef _WIN32
160         return WSAGetLastError();
161 #else /* _WIN32 */
162         return errno;
163 #endif /* _WIN32 */
164 }
165
166 /**
167  * Handles a socket error by calling the OnError event or throwing an exception
168  * when there are no observers for the OnError event.
169  *
170  * @param ex An exception.
171  */
172 void Socket::HandleSocketError(const std::exception& ex)
173 {
174         // XXX, TODO: add SetErrorHandling() function
175 /*      if (OnError.HasObservers()) {*/
176                 SocketErrorEventArgs sea(ex);
177                 OnError(sea);
178
179                 Close();
180 /*      } else {
181                 throw ex;
182         }*/
183 }
184
185 /**
186  * Processes errors that have occured for the socket.
187  *
188  * @param - Event arguments for the socket error.
189  * @returns 0
190  */
191 int Socket::ExceptionEventHandler(const EventArgs&)
192 {
193         HandleSocketError(SocketException(
194             "select() returned fd in except fdset", GetError()));
195
196         return 0;
197 }
198
199 /**
200  * Checks whether data should be read for this socket object.
201  *
202  * @returns true if the socket should be registered for reading, false otherwise.
203  */
204 bool Socket::WantsToRead(void) const
205 {
206         return false;
207 }
208
209 /**
210  * Checks whether data should be written for this socket object.
211  *
212  * @returns true if the socket should be registered for writing, false otherwise.
213  */
214 bool Socket::WantsToWrite(void) const
215 {
216         return false;
217 }
218
219 /**
220  * Formats a sockaddr in a human-readable way.
221  *
222  * @returns A string describing the sockaddr.
223  */
224 string Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len)
225 {
226         char host[NI_MAXHOST];
227         char service[NI_MAXSERV];
228
229         if (getnameinfo(address, len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
230                 throw SocketException("getnameinfo() failed",
231                     GetLastSocketError());
232
233         stringstream s;
234         s << "[" << host << "]:" << service;
235         return s.str();
236 }
237
238 /**
239  * Returns a string describing the local address of the socket.
240  *
241  * @returns A string describing the local address.
242  */
243 string Socket::GetClientAddress(void)
244 {
245         sockaddr_storage sin;
246         socklen_t len = sizeof(sin);
247
248         if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) {
249                 HandleSocketError(SocketException(
250                     "getsockname() failed", GetError()));
251
252                 return string();
253         }
254
255         return GetAddressFromSockaddr((sockaddr *)&sin, len);
256 }
257
258 /**
259  * Returns a string describing the peer address of the socket.
260  *
261  * @returns A string describing the peer address.
262  */
263 string Socket::GetPeerAddress(void)
264 {
265         sockaddr_storage sin;
266         socklen_t len = sizeof(sin);
267
268         if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) {
269                 HandleSocketError(SocketException(
270                     "getpeername() failed", GetError()));
271
272                 return string();
273         }
274
275         return GetAddressFromSockaddr((sockaddr *)&sin, len);
276 }
277
278 /**
279  * Constructor for the SocketException class.
280  *
281  * @param message The error message.
282  * @param errorCode The error code.
283  */
284 SocketException::SocketException(const string& message, int errorCode)  
285 {
286 #ifdef _WIN32
287         string details = Win32Exception::FormatErrorCode(errorCode);
288 #else /* _WIN32 */
289         string details = PosixException::FormatErrorCode(errorCode);
290 #endif /* _WIN32 */
291
292         string msg = message + ": " + details;
293         SetMessage(msg.c_str());
294 }