2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
24 #include "exitcodes.h"
29 /** Reference table, contains all current handlers
31 std::vector<EventHandler*> SocketEngine::ref;
33 /** Current number of descriptors in the engine
35 size_t SocketEngine::CurrentSetSize = 0;
37 /** List of handlers that want a trial read/write
39 std::set<int> SocketEngine::trials;
41 size_t SocketEngine::MaxSetSize = 0;
43 /** Socket engine statistics: count of various events, bandwidth usage
45 SocketEngine::Statistics SocketEngine::stats;
47 EventHandler::EventHandler()
53 void EventHandler::SwapInternals(EventHandler& other)
55 std::swap(fd, other.fd);
56 std::swap(event_mask, other.event_mask);
59 void EventHandler::SetFd(int FD)
64 void EventHandler::OnEventHandlerWrite()
68 void EventHandler::OnEventHandlerError(int errornum)
72 void SocketEngine::InitError()
74 std::cerr << con_red << "FATAL ERROR!" << con_reset << " Socket engine initialization failed. " << strerror(errno) << '.' << std::endl;
75 exit(EXIT_STATUS_SOCKETENGINE);
78 void SocketEngine::LookupMaxFds()
81 MaxSetSize = FD_SETSIZE;
84 if (!getrlimit(RLIMIT_NOFILE, &limits))
85 MaxSetSize = limits.rlim_cur;
88 limits.rlim_cur = limits.rlim_max == RLIM_INFINITY ? OPEN_MAX : limits.rlim_max;
90 limits.rlim_cur = limits.rlim_max;
92 if (!setrlimit(RLIMIT_NOFILE, &limits))
93 MaxSetSize = limits.rlim_cur;
97 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
99 int old_m = eh->event_mask;
102 // if we are changing read/write type, remove the previously set bit
103 if (change & FD_WANT_READ_MASK)
104 new_m &= ~FD_WANT_READ_MASK;
105 if (change & FD_WANT_WRITE_MASK)
106 new_m &= ~FD_WANT_WRITE_MASK;
108 // if adding a trial read/write, insert it into the set
109 if (change & FD_TRIAL_NOTE_MASK && !(old_m & FD_TRIAL_NOTE_MASK))
110 trials.insert(eh->GetFd());
116 eh->event_mask = new_m;
117 OnSetEvent(eh, old_m, new_m);
120 void SocketEngine::DispatchTrialWrites()
122 std::vector<int> working_list;
123 working_list.reserve(trials.size());
124 working_list.assign(trials.begin(), trials.end());
126 for(unsigned int i=0; i < working_list.size(); i++)
128 int fd = working_list[i];
129 EventHandler* eh = GetRef(fd);
132 int mask = eh->event_mask;
133 eh->event_mask &= ~(FD_ADD_TRIAL_READ | FD_ADD_TRIAL_WRITE);
134 if ((mask & (FD_ADD_TRIAL_READ | FD_READ_WILL_BLOCK)) == FD_ADD_TRIAL_READ)
135 eh->OnEventHandlerRead();
136 if ((mask & (FD_ADD_TRIAL_WRITE | FD_WRITE_WILL_BLOCK)) == FD_ADD_TRIAL_WRITE)
137 eh->OnEventHandlerWrite();
141 bool SocketEngine::AddFdRef(EventHandler* eh)
143 int fd = eh->GetFd();
147 while (static_cast<unsigned int>(fd) >= ref.size())
148 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
154 void SocketEngine::DelFdRef(EventHandler *eh)
156 int fd = eh->GetFd();
157 if (GetRef(fd) == eh)
164 bool SocketEngine::HasFd(int fd)
166 return GetRef(fd) != NULL;
169 EventHandler* SocketEngine::GetRef(int fd)
171 if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
176 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
186 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
188 return accept(fd->GetFd(), addr, addrlen);
191 int SocketEngine::Close(EventHandler* eh)
194 int ret = Close(eh->GetFd());
199 int SocketEngine::Close(int fd)
202 return closesocket(fd);
208 int SocketEngine::Blocking(int fd)
211 unsigned long opt = 0;
212 return ioctlsocket(fd, FIONBIO, &opt);
214 int flags = fcntl(fd, F_GETFL, 0);
215 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
219 int SocketEngine::NonBlocking(int fd)
222 unsigned long opt = 1;
223 return ioctlsocket(fd, FIONBIO, &opt);
225 int flags = fcntl(fd, F_GETFL, 0);
226 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
230 void SocketEngine::SetReuse(int fd)
233 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
236 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
238 int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
239 stats.UpdateReadCounters(nbRecvd);
243 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
245 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
246 stats.UpdateWriteCounters(nbSent);
250 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
252 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
253 stats.UpdateReadCounters(nbRecvd);
257 int SocketEngine::SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address)
259 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, &address.sa, address.sa_size());
260 stats.UpdateWriteCounters(nbSent);
264 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
266 int sent = writev(fd->GetFd(), iovec, count);
267 stats.UpdateWriteCounters(sent);
272 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
274 // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
275 // the fields in the correct order.
276 // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
277 // platform's native struct.
278 IOVector wiovec[128];
279 count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
281 for (int i = 0; i < count; i++)
283 wiovec[i].iov_len = iovec[i].iov_len;
284 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
286 return WriteV(fd, wiovec, count);
290 int SocketEngine::Connect(EventHandler* fd, const irc::sockets::sockaddrs& address)
292 int ret = connect(fd->GetFd(), &address.sa, address.sa_size());
294 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
300 int SocketEngine::Shutdown(EventHandler* fd, int how)
302 return shutdown(fd->GetFd(), how);
305 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
307 return bind(fd, &addr.sa, addr.sa_size());
310 int SocketEngine::Listen(int sockfd, int backlog)
312 return listen(sockfd, backlog);
315 int SocketEngine::Shutdown(int fd, int how)
317 return shutdown(fd, how);
320 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
331 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
338 else if (len_out < 0)
342 void SocketEngine::Statistics::CheckFlush() const
344 // Reset the in/out byte counters if it has been more than a second
345 time_t now = ServerInstance->Time();
346 if (lastempty != now)
349 indata = outdata = 0;
353 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
356 float in_kbit = indata * 8;
357 float out_kbit = outdata * 8;
358 kbitpersec_total = ((in_kbit + out_kbit) / 1024);
359 kbitpersec_in = in_kbit / 1024;
360 kbitpersec_out = out_kbit / 1024;
363 std::string SocketEngine::LastError()
366 return strerror(errno);
368 char szErrorString[500];
369 DWORD dwErrorCode = WSAGetLastError();
370 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
371 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
373 std::string::size_type p;
374 std::string ret = szErrorString;
375 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
382 std::string SocketEngine::GetError(int errnum)
385 return strerror(errnum);
387 WSASetLastError(errnum);