]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengine.cpp
Get rid of InspIRCd::QuickExit.
[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         struct rlimit limits;
75         if (!getrlimit(RLIMIT_NOFILE, &limits))
76                 MaxSetSize = limits.rlim_cur;
77
78 #if defined __APPLE__
79         limits.rlim_cur = limits.rlim_max == RLIM_INFINITY ? OPEN_MAX : limits.rlim_max;
80 #else
81         limits.rlim_cur = limits.rlim_max;
82 #endif
83         if (!setrlimit(RLIMIT_NOFILE, &limits))
84                 MaxSetSize = limits.rlim_cur;
85 }
86
87 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
88 {
89         int old_m = eh->event_mask;
90         int new_m = old_m;
91
92         // if we are changing read/write type, remove the previously set bit
93         if (change & FD_WANT_READ_MASK)
94                 new_m &= ~FD_WANT_READ_MASK;
95         if (change & FD_WANT_WRITE_MASK)
96                 new_m &= ~FD_WANT_WRITE_MASK;
97
98         // if adding a trial read/write, insert it into the set
99         if (change & FD_TRIAL_NOTE_MASK && !(old_m & FD_TRIAL_NOTE_MASK))
100                 trials.insert(eh->GetFd());
101
102         new_m |= change;
103         if (new_m == old_m)
104                 return;
105
106         eh->event_mask = new_m;
107         OnSetEvent(eh, old_m, new_m);
108 }
109
110 void SocketEngine::DispatchTrialWrites()
111 {
112         std::vector<int> working_list;
113         working_list.reserve(trials.size());
114         working_list.assign(trials.begin(), trials.end());
115         trials.clear();
116         for(unsigned int i=0; i < working_list.size(); i++)
117         {
118                 int fd = working_list[i];
119                 EventHandler* eh = GetRef(fd);
120                 if (!eh)
121                         continue;
122                 int mask = eh->event_mask;
123                 eh->event_mask &= ~(FD_ADD_TRIAL_READ | FD_ADD_TRIAL_WRITE);
124                 if ((mask & (FD_ADD_TRIAL_READ | FD_READ_WILL_BLOCK)) == FD_ADD_TRIAL_READ)
125                         eh->OnEventHandlerRead();
126                 if ((mask & (FD_ADD_TRIAL_WRITE | FD_WRITE_WILL_BLOCK)) == FD_ADD_TRIAL_WRITE)
127                         eh->OnEventHandlerWrite();
128         }
129 }
130
131 bool SocketEngine::AddFdRef(EventHandler* eh)
132 {
133         int fd = eh->GetFd();
134         if (HasFd(fd))
135                 return false;
136
137         while (static_cast<unsigned int>(fd) >= ref.size())
138                 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
139         ref[fd] = eh;
140         CurrentSetSize++;
141         return true;
142 }
143
144 void SocketEngine::DelFdRef(EventHandler *eh)
145 {
146         int fd = eh->GetFd();
147         if (GetRef(fd) == eh)
148         {
149                 ref[fd] = NULL;
150                 CurrentSetSize--;
151         }
152 }
153
154 bool SocketEngine::HasFd(int fd)
155 {
156         return GetRef(fd) != NULL;
157 }
158
159 EventHandler* SocketEngine::GetRef(int fd)
160 {
161         if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
162                 return NULL;
163         return ref[fd];
164 }
165
166 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
167 {
168         if (!eh)
169                 return false;
170         if (eh->GetFd() < 0)
171                 return false;
172         return true;
173 }
174
175
176 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
177 {
178         return accept(fd->GetFd(), addr, addrlen);
179 }
180
181 int SocketEngine::Close(EventHandler* eh)
182 {
183         DelFd(eh);
184         int ret = Close(eh->GetFd());
185         eh->SetFd(-1);
186         return ret;
187 }
188
189 int SocketEngine::Close(int fd)
190 {
191 #ifdef _WIN32
192         return closesocket(fd);
193 #else
194         return close(fd);
195 #endif
196 }
197
198 int SocketEngine::Blocking(int fd)
199 {
200 #ifdef _WIN32
201         unsigned long opt = 0;
202         return ioctlsocket(fd, FIONBIO, &opt);
203 #else
204         int flags = fcntl(fd, F_GETFL, 0);
205         return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
206 #endif
207 }
208
209 int SocketEngine::NonBlocking(int fd)
210 {
211 #ifdef _WIN32
212         unsigned long opt = 1;
213         return ioctlsocket(fd, FIONBIO, &opt);
214 #else
215         int flags = fcntl(fd, F_GETFL, 0);
216         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
217 #endif
218 }
219
220 void SocketEngine::SetReuse(int fd)
221 {
222         int on = 1;
223         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
224 }
225
226 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
227 {
228         int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
229         stats.UpdateReadCounters(nbRecvd);
230         return nbRecvd;
231 }
232
233 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
234 {
235         int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
236         stats.UpdateWriteCounters(nbSent);
237         return nbSent;
238 }
239
240 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
241 {
242         int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
243         stats.UpdateReadCounters(nbRecvd);
244         return nbRecvd;
245 }
246
247 int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen)
248 {
249         int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, to, tolen);
250         stats.UpdateWriteCounters(nbSent);
251         return nbSent;
252 }
253
254 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
255 {
256         int sent = writev(fd->GetFd(), iovec, count);
257         stats.UpdateWriteCounters(sent);
258         return sent;
259 }
260
261 #ifdef _WIN32
262 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
263 {
264         // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
265         // the fields in the correct order.
266         // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
267         // platform's native struct.
268         IOVector wiovec[128];
269         count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
270
271         for (int i = 0; i < count; i++)
272         {
273                 wiovec[i].iov_len = iovec[i].iov_len;
274                 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
275         }
276         return WriteV(fd, wiovec, count);
277 }
278 #endif
279
280 int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
281 {
282         int ret = connect(fd->GetFd(), serv_addr, addrlen);
283 #ifdef _WIN32
284         if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
285                 errno = EINPROGRESS;
286 #endif
287         return ret;
288 }
289
290 int SocketEngine::Shutdown(EventHandler* fd, int how)
291 {
292         return shutdown(fd->GetFd(), how);
293 }
294
295 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
296 {
297         return bind(fd, &addr.sa, addr.sa_size());
298 }
299
300 int SocketEngine::Listen(int sockfd, int backlog)
301 {
302         return listen(sockfd, backlog);
303 }
304
305 int SocketEngine::Shutdown(int fd, int how)
306 {
307         return shutdown(fd, how);
308 }
309
310 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
311 {
312         CheckFlush();
313
314         ReadEvents++;
315         if (len_in > 0)
316                 indata += len_in;
317         else if (len_in < 0)
318                 ErrorEvents++;
319 }
320
321 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
322 {
323         CheckFlush();
324
325         WriteEvents++;
326         if (len_out > 0)
327                 outdata += len_out;
328         else if (len_out < 0)
329                 ErrorEvents++;
330 }
331
332 void SocketEngine::Statistics::CheckFlush() const
333 {
334         // Reset the in/out byte counters if it has been more than a second
335         time_t now = ServerInstance->Time();
336         if (lastempty != now)
337         {
338                 lastempty = now;
339                 indata = outdata = 0;
340         }
341 }
342
343 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
344 {
345         CheckFlush();
346         float in_kbit = indata * 8;
347         float out_kbit = outdata * 8;
348         kbitpersec_total = ((in_kbit + out_kbit) / 1024);
349         kbitpersec_in = in_kbit / 1024;
350         kbitpersec_out = out_kbit / 1024;
351 }
352
353 std::string SocketEngine::LastError()
354 {
355 #ifndef _WIN32
356         return strerror(errno);
357 #else
358         char szErrorString[500];
359         DWORD dwErrorCode = WSAGetLastError();
360         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
361                 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
362
363         std::string::size_type p;
364         std::string ret = szErrorString;
365         while ((p = ret.find_last_of("\r\n")) != std::string::npos)
366                 ret.erase(p, 1);
367
368         return ret;
369 #endif
370 }
371
372 std::string SocketEngine::GetError(int errnum)
373 {
374 #ifndef _WIN32
375         return strerror(errnum);
376 #else
377         WSASetLastError(errnum);
378         return LastError();
379 #endif
380 }