2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
29 #include "exitcodes.h"
34 /** Reference table, contains all current handlers
36 std::vector<EventHandler*> SocketEngine::ref;
38 /** Current number of descriptors in the engine
40 size_t SocketEngine::CurrentSetSize = 0;
42 /** List of handlers that want a trial read/write
44 std::set<int> SocketEngine::trials;
46 size_t SocketEngine::MaxSetSize = 0;
48 /** Socket engine statistics: count of various events, bandwidth usage
50 SocketEngine::Statistics SocketEngine::stats;
52 EventHandler::EventHandler()
58 void EventHandler::SwapInternals(EventHandler& other)
60 std::swap(fd, other.fd);
61 std::swap(event_mask, other.event_mask);
64 void EventHandler::SetFd(int FD)
69 void EventHandler::OnEventHandlerWrite()
73 void EventHandler::OnEventHandlerError(int errornum)
77 void SocketEngine::InitError()
79 std::cerr << con_red << "FATAL ERROR!" << con_reset << " Socket engine initialization failed. " << strerror(errno) << '.' << std::endl;
80 exit(EXIT_STATUS_SOCKETENGINE);
83 void SocketEngine::LookupMaxFds()
86 MaxSetSize = FD_SETSIZE;
89 if (!getrlimit(RLIMIT_NOFILE, &limits))
90 MaxSetSize = limits.rlim_cur;
93 limits.rlim_cur = limits.rlim_max == RLIM_INFINITY ? OPEN_MAX : limits.rlim_max;
95 limits.rlim_cur = limits.rlim_max;
97 if (!setrlimit(RLIMIT_NOFILE, &limits))
98 MaxSetSize = limits.rlim_cur;
102 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
104 int old_m = eh->event_mask;
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;
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());
121 eh->event_mask = new_m;
122 OnSetEvent(eh, old_m, new_m);
125 void SocketEngine::DispatchTrialWrites()
127 std::vector<int> working_list;
128 working_list.reserve(trials.size());
129 working_list.assign(trials.begin(), trials.end());
131 for(unsigned int i=0; i < working_list.size(); i++)
133 int fd = working_list[i];
134 EventHandler* eh = GetRef(fd);
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();
146 bool SocketEngine::AddFdRef(EventHandler* eh)
148 int fd = eh->GetFd();
152 while (static_cast<unsigned int>(fd) >= ref.size())
153 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
159 void SocketEngine::DelFdRef(EventHandler *eh)
161 int fd = eh->GetFd();
162 if (GetRef(fd) == eh)
169 bool SocketEngine::HasFd(int fd)
171 return GetRef(fd) != NULL;
174 EventHandler* SocketEngine::GetRef(int fd)
176 if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
181 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
183 return eh && eh->HasFd();
187 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
189 return accept(fd->GetFd(), addr, addrlen);
192 int SocketEngine::Close(EventHandler* eh)
195 int ret = Close(eh->GetFd());
200 int SocketEngine::Close(int fd)
203 return closesocket(fd);
209 int SocketEngine::Blocking(int fd)
212 unsigned long opt = 0;
213 return ioctlsocket(fd, FIONBIO, &opt);
215 int flags = fcntl(fd, F_GETFL, 0);
216 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
220 int SocketEngine::NonBlocking(int fd)
223 unsigned long opt = 1;
224 return ioctlsocket(fd, FIONBIO, &opt);
226 int flags = fcntl(fd, F_GETFL, 0);
227 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
231 void SocketEngine::SetReuse(int fd)
234 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
237 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
239 int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
240 stats.UpdateReadCounters(nbRecvd);
244 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
246 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
247 stats.UpdateWriteCounters(nbSent);
251 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
253 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
254 stats.UpdateReadCounters(nbRecvd);
258 int SocketEngine::SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address)
260 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, &address.sa, address.sa_size());
261 stats.UpdateWriteCounters(nbSent);
265 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
267 int sent = writev(fd->GetFd(), iovec, count);
268 stats.UpdateWriteCounters(sent);
273 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
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)));
282 for (int i = 0; i < count; i++)
284 wiovec[i].iov_len = iovec[i].iov_len;
285 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
287 return WriteV(fd, wiovec, count);
291 int SocketEngine::Connect(EventHandler* fd, const irc::sockets::sockaddrs& address)
293 int ret = connect(fd->GetFd(), &address.sa, address.sa_size());
295 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
301 int SocketEngine::Shutdown(EventHandler* fd, int how)
303 return shutdown(fd->GetFd(), how);
306 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
308 return bind(fd, &addr.sa, addr.sa_size());
311 int SocketEngine::Listen(int sockfd, int backlog)
313 return listen(sockfd, backlog);
316 int SocketEngine::Shutdown(int fd, int how)
318 return shutdown(fd, how);
321 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
332 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
339 else if (len_out < 0)
343 void SocketEngine::Statistics::CheckFlush() const
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)
350 indata = outdata = 0;
354 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
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;
364 std::string SocketEngine::LastError()
367 return strerror(errno);
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);
374 std::string::size_type p;
375 std::string ret = szErrorString;
376 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
383 std::string SocketEngine::GetError(int errnum)
386 return strerror(errnum);
388 WSASetLastError(errnum);