]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengine.cpp
Fix building on Windows (mostly).
[user/henk/code/inspircd.git] / src / socketengine.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2005-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2007 Burlex <???@???>
8  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #include "exitcodes.h"
25 #include "inspircd.h"
26
27 #include <iostream>
28
29 /** Reference table, contains all current handlers
30  **/
31 std::vector<EventHandler*> SocketEngine::ref;
32
33 /** Current number of descriptors in the engine
34  */
35 size_t SocketEngine::CurrentSetSize = 0;
36
37 /** List of handlers that want a trial read/write
38  */
39 std::set<int> SocketEngine::trials;
40
41 size_t SocketEngine::MaxSetSize = 0;
42
43 /** Socket engine statistics: count of various events, bandwidth usage
44  */
45 SocketEngine::Statistics SocketEngine::stats;
46
47 EventHandler::EventHandler()
48 {
49         fd = -1;
50         event_mask = 0;
51 }
52
53 void EventHandler::SetFd(int FD)
54 {
55         this->fd = FD;
56 }
57
58 void EventHandler::OnEventHandlerWrite()
59 {
60 }
61
62 void EventHandler::OnEventHandlerError(int errornum)
63 {
64 }
65
66 void SocketEngine::InitError()
67 {
68         std::cerr << con_red << "FATAL ERROR!" << con_reset << " Socket engine initialization failed. " << strerror(errno) << '.' << std::endl;
69         exit(EXIT_STATUS_SOCKETENGINE);
70 }
71
72 void SocketEngine::LookupMaxFds()
73 {
74 #if defined _WIN32
75         MaxSetSize = FD_SETSIZE;
76 #else
77         struct rlimit limits;
78         if (!getrlimit(RLIMIT_NOFILE, &limits))
79                 MaxSetSize = limits.rlim_cur;
80
81 #if defined __APPLE__
82         limits.rlim_cur = limits.rlim_max == RLIM_INFINITY ? OPEN_MAX : limits.rlim_max;
83 #else
84         limits.rlim_cur = limits.rlim_max;
85 #endif
86         if (!setrlimit(RLIMIT_NOFILE, &limits))
87                 MaxSetSize = limits.rlim_cur;
88 #endif
89 }
90
91 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
92 {
93         int old_m = eh->event_mask;
94         int new_m = old_m;
95
96         // if we are changing read/write type, remove the previously set bit
97         if (change & FD_WANT_READ_MASK)
98                 new_m &= ~FD_WANT_READ_MASK;
99         if (change & FD_WANT_WRITE_MASK)
100                 new_m &= ~FD_WANT_WRITE_MASK;
101
102         // if adding a trial read/write, insert it into the set
103         if (change & FD_TRIAL_NOTE_MASK && !(old_m & FD_TRIAL_NOTE_MASK))
104                 trials.insert(eh->GetFd());
105
106         new_m |= change;
107         if (new_m == old_m)
108                 return;
109
110         eh->event_mask = new_m;
111         OnSetEvent(eh, old_m, new_m);
112 }
113
114 void SocketEngine::DispatchTrialWrites()
115 {
116         std::vector<int> working_list;
117         working_list.reserve(trials.size());
118         working_list.assign(trials.begin(), trials.end());
119         trials.clear();
120         for(unsigned int i=0; i < working_list.size(); i++)
121         {
122                 int fd = working_list[i];
123                 EventHandler* eh = GetRef(fd);
124                 if (!eh)
125                         continue;
126                 int mask = eh->event_mask;
127                 eh->event_mask &= ~(FD_ADD_TRIAL_READ | FD_ADD_TRIAL_WRITE);
128                 if ((mask & (FD_ADD_TRIAL_READ | FD_READ_WILL_BLOCK)) == FD_ADD_TRIAL_READ)
129                         eh->OnEventHandlerRead();
130                 if ((mask & (FD_ADD_TRIAL_WRITE | FD_WRITE_WILL_BLOCK)) == FD_ADD_TRIAL_WRITE)
131                         eh->OnEventHandlerWrite();
132         }
133 }
134
135 bool SocketEngine::AddFdRef(EventHandler* eh)
136 {
137         int fd = eh->GetFd();
138         if (HasFd(fd))
139                 return false;
140
141         while (static_cast<unsigned int>(fd) >= ref.size())
142                 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
143         ref[fd] = eh;
144         CurrentSetSize++;
145         return true;
146 }
147
148 void SocketEngine::DelFdRef(EventHandler *eh)
149 {
150         int fd = eh->GetFd();
151         if (GetRef(fd) == eh)
152         {
153                 ref[fd] = NULL;
154                 CurrentSetSize--;
155         }
156 }
157
158 bool SocketEngine::HasFd(int fd)
159 {
160         return GetRef(fd) != NULL;
161 }
162
163 EventHandler* SocketEngine::GetRef(int fd)
164 {
165         if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
166                 return NULL;
167         return ref[fd];
168 }
169
170 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
171 {
172         if (!eh)
173                 return false;
174         if (eh->GetFd() < 0)
175                 return false;
176         return true;
177 }
178
179
180 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
181 {
182         return accept(fd->GetFd(), addr, addrlen);
183 }
184
185 int SocketEngine::Close(EventHandler* eh)
186 {
187         DelFd(eh);
188         int ret = Close(eh->GetFd());
189         eh->SetFd(-1);
190         return ret;
191 }
192
193 int SocketEngine::Close(int fd)
194 {
195 #ifdef _WIN32
196         return closesocket(fd);
197 #else
198         return close(fd);
199 #endif
200 }
201
202 int SocketEngine::Blocking(int fd)
203 {
204 #ifdef _WIN32
205         unsigned long opt = 0;
206         return ioctlsocket(fd, FIONBIO, &opt);
207 #else
208         int flags = fcntl(fd, F_GETFL, 0);
209         return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
210 #endif
211 }
212
213 int SocketEngine::NonBlocking(int fd)
214 {
215 #ifdef _WIN32
216         unsigned long opt = 1;
217         return ioctlsocket(fd, FIONBIO, &opt);
218 #else
219         int flags = fcntl(fd, F_GETFL, 0);
220         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
221 #endif
222 }
223
224 void SocketEngine::SetReuse(int fd)
225 {
226         int on = 1;
227         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
228 }
229
230 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
231 {
232         int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
233         stats.UpdateReadCounters(nbRecvd);
234         return nbRecvd;
235 }
236
237 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
238 {
239         int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
240         stats.UpdateWriteCounters(nbSent);
241         return nbSent;
242 }
243
244 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
245 {
246         int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
247         stats.UpdateReadCounters(nbRecvd);
248         return nbRecvd;
249 }
250
251 int SocketEngine::SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address)
252 {
253         int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, &address.sa, address.sa_size());
254         stats.UpdateWriteCounters(nbSent);
255         return nbSent;
256 }
257
258 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
259 {
260         int sent = writev(fd->GetFd(), iovec, count);
261         stats.UpdateWriteCounters(sent);
262         return sent;
263 }
264
265 #ifdef _WIN32
266 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
267 {
268         // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
269         // the fields in the correct order.
270         // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
271         // platform's native struct.
272         IOVector wiovec[128];
273         count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
274
275         for (int i = 0; i < count; i++)
276         {
277                 wiovec[i].iov_len = iovec[i].iov_len;
278                 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
279         }
280         return WriteV(fd, wiovec, count);
281 }
282 #endif
283
284 int SocketEngine::Connect(EventHandler* fd, const irc::sockets::sockaddrs& address)
285 {
286         int ret = connect(fd->GetFd(), &address.sa, address.sa_size());
287 #ifdef _WIN32
288         if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
289                 errno = EINPROGRESS;
290 #endif
291         return ret;
292 }
293
294 int SocketEngine::Shutdown(EventHandler* fd, int how)
295 {
296         return shutdown(fd->GetFd(), how);
297 }
298
299 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
300 {
301         return bind(fd, &addr.sa, addr.sa_size());
302 }
303
304 int SocketEngine::Listen(int sockfd, int backlog)
305 {
306         return listen(sockfd, backlog);
307 }
308
309 int SocketEngine::Shutdown(int fd, int how)
310 {
311         return shutdown(fd, how);
312 }
313
314 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
315 {
316         CheckFlush();
317
318         ReadEvents++;
319         if (len_in > 0)
320                 indata += len_in;
321         else if (len_in < 0)
322                 ErrorEvents++;
323 }
324
325 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
326 {
327         CheckFlush();
328
329         WriteEvents++;
330         if (len_out > 0)
331                 outdata += len_out;
332         else if (len_out < 0)
333                 ErrorEvents++;
334 }
335
336 void SocketEngine::Statistics::CheckFlush() const
337 {
338         // Reset the in/out byte counters if it has been more than a second
339         time_t now = ServerInstance->Time();
340         if (lastempty != now)
341         {
342                 lastempty = now;
343                 indata = outdata = 0;
344         }
345 }
346
347 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
348 {
349         CheckFlush();
350         float in_kbit = indata * 8;
351         float out_kbit = outdata * 8;
352         kbitpersec_total = ((in_kbit + out_kbit) / 1024);
353         kbitpersec_in = in_kbit / 1024;
354         kbitpersec_out = out_kbit / 1024;
355 }
356
357 std::string SocketEngine::LastError()
358 {
359 #ifndef _WIN32
360         return strerror(errno);
361 #else
362         char szErrorString[500];
363         DWORD dwErrorCode = WSAGetLastError();
364         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
365                 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
366
367         std::string::size_type p;
368         std::string ret = szErrorString;
369         while ((p = ret.find_last_of("\r\n")) != std::string::npos)
370                 ret.erase(p, 1);
371
372         return ret;
373 #endif
374 }
375
376 std::string SocketEngine::GetError(int errnum)
377 {
378 #ifndef _WIN32
379         return strerror(errnum);
380 #else
381         WSASetLastError(errnum);
382         return LastError();
383 #endif
384 }