1 /*
2 * InspIRCd -- Internet Relay Chat Daemon
3 *
4 * Copyright (C) 2017-2020 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
EventHandler()52 EventHandler::EventHandler()
53 {
54 fd = -1;
55 event_mask = 0;
56 }
57
SwapInternals(EventHandler & other)58 void EventHandler::SwapInternals(EventHandler& other)
59 {
60 std::swap(fd, other.fd);
61 std::swap(event_mask, other.event_mask);
62 }
63
SetFd(int FD)64 void EventHandler::SetFd(int FD)
65 {
66 this->fd = FD;
67 }
68
OnEventHandlerWrite()69 void EventHandler::OnEventHandlerWrite()
70 {
71 }
72
OnEventHandlerError(int errornum)73 void EventHandler::OnEventHandlerError(int errornum)
74 {
75 }
76
InitError()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
LookupMaxFds()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
ChangeEventMask(EventHandler * eh,int change)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
DispatchTrialWrites()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
AddFdRef(EventHandler * eh)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
DelFdRef(EventHandler * eh)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
HasFd(int fd)169 bool SocketEngine::HasFd(int fd)
170 {
171 return GetRef(fd) != NULL;
172 }
173
GetRef(int fd)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
BoundsCheckFd(EventHandler * eh)181 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
182 {
183 return eh && eh->HasFd();
184 }
185
186
Accept(EventHandler * fd,sockaddr * addr,socklen_t * addrlen)187 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
188 {
189 return accept(fd->GetFd(), addr, addrlen);
190 }
191
Close(EventHandler * eh)192 int SocketEngine::Close(EventHandler* eh)
193 {
194 DelFd(eh);
195 int ret = Close(eh->GetFd());
196 eh->SetFd(-1);
197 return ret;
198 }
199
Close(int fd)200 int SocketEngine::Close(int fd)
201 {
202 #ifdef _WIN32
203 return closesocket(fd);
204 #else
205 return close(fd);
206 #endif
207 }
208
Blocking(int fd)209 int SocketEngine::Blocking(int fd)
210 {
211 #ifdef _WIN32
212 unsigned long opt = 0;
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
NonBlocking(int fd)220 int SocketEngine::NonBlocking(int fd)
221 {
222 #ifdef _WIN32
223 unsigned long opt = 1;
224 return ioctlsocket(fd, FIONBIO, &opt);
225 #else
226 int flags = fcntl(fd, F_GETFL, 0);
227 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
228 #endif
229 }
230
SetReuse(int fd)231 void SocketEngine::SetReuse(int fd)
232 {
233 int on = 1;
234 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
235 }
236
RecvFrom(EventHandler * fd,void * buf,size_t len,int flags,sockaddr * from,socklen_t * fromlen)237 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
238 {
239 int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
240 stats.UpdateReadCounters(nbRecvd);
241 return nbRecvd;
242 }
243
Send(EventHandler * fd,const void * buf,size_t len,int flags)244 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
245 {
246 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
247 stats.UpdateWriteCounters(nbSent);
248 return nbSent;
249 }
250
Recv(EventHandler * fd,void * buf,size_t len,int flags)251 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
252 {
253 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
254 stats.UpdateReadCounters(nbRecvd);
255 return nbRecvd;
256 }
257
SendTo(EventHandler * fd,const void * buf,size_t len,int flags,const irc::sockets::sockaddrs & address)258 int SocketEngine::SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address)
259 {
260 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, &address.sa, address.sa_size());
261 stats.UpdateWriteCounters(nbSent);
262 return nbSent;
263 }
264
WriteV(EventHandler * fd,const IOVector * iovec,int count)265 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
266 {
267 int sent = writev(fd->GetFd(), iovec, count);
268 stats.UpdateWriteCounters(sent);
269 return sent;
270 }
271
272 #ifdef _WIN32
WriteV(EventHandler * fd,const iovec * iovec,int count)273 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
274 {
275 // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
276 // the fields in the correct order.
277 // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
278 // platform's native struct.
279 IOVector wiovec[128];
280 count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
281
282 for (int i = 0; i < count; i++)
283 {
284 wiovec[i].iov_len = iovec[i].iov_len;
285 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
286 }
287 return WriteV(fd, wiovec, count);
288 }
289 #endif
290
Connect(EventHandler * fd,const irc::sockets::sockaddrs & address)291 int SocketEngine::Connect(EventHandler* fd, const irc::sockets::sockaddrs& address)
292 {
293 int ret = connect(fd->GetFd(), &address.sa, address.sa_size());
294 #ifdef _WIN32
295 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
296 errno = EINPROGRESS;
297 #endif
298 return ret;
299 }
300
Shutdown(EventHandler * fd,int how)301 int SocketEngine::Shutdown(EventHandler* fd, int how)
302 {
303 return shutdown(fd->GetFd(), how);
304 }
305
Bind(int fd,const irc::sockets::sockaddrs & addr)306 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
307 {
308 return bind(fd, &addr.sa, addr.sa_size());
309 }
310
Listen(int sockfd,int backlog)311 int SocketEngine::Listen(int sockfd, int backlog)
312 {
313 return listen(sockfd, backlog);
314 }
315
Shutdown(int fd,int how)316 int SocketEngine::Shutdown(int fd, int how)
317 {
318 return shutdown(fd, how);
319 }
320
UpdateReadCounters(int len_in)321 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
322 {
323 CheckFlush();
324
325 ReadEvents++;
326 if (len_in > 0)
327 indata += len_in;
328 else if (len_in < 0)
329 ErrorEvents++;
330 }
331
UpdateWriteCounters(int len_out)332 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
333 {
334 CheckFlush();
335
336 WriteEvents++;
337 if (len_out > 0)
338 outdata += len_out;
339 else if (len_out < 0)
340 ErrorEvents++;
341 }
342
CheckFlush() const343 void SocketEngine::Statistics::CheckFlush() const
344 {
345 // Reset the in/out byte counters if it has been more than a second
346 time_t now = ServerInstance->Time();
347 if (lastempty != now)
348 {
349 lastempty = now;
350 indata = outdata = 0;
351 }
352 }
353
GetBandwidth(float & kbitpersec_in,float & kbitpersec_out,float & kbitpersec_total) const354 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
355 {
356 CheckFlush();
357 float in_kbit = indata * 8;
358 float out_kbit = outdata * 8;
359 kbitpersec_total = ((in_kbit + out_kbit) / 1024);
360 kbitpersec_in = in_kbit / 1024;
361 kbitpersec_out = out_kbit / 1024;
362 }
363
LastError()364 std::string SocketEngine::LastError()
365 {
366 #ifndef _WIN32
367 return strerror(errno);
368 #else
369 char szErrorString[500];
370 DWORD dwErrorCode = WSAGetLastError();
371 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
372 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
373
374 std::string::size_type p;
375 std::string ret = szErrorString;
376 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
377 ret.erase(p, 1);
378
379 return ret;
380 #endif
381 }
382
GetError(int errnum)383 std::string SocketEngine::GetError(int errnum)
384 {
385 #ifndef _WIN32
386 return strerror(errnum);
387 #else
388 WSASetLastError(errnum);
389 return LastError();
390 #endif
391 }
392