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