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::SetFd(int FD)
58 void EventHandler::OnEventHandlerWrite()
62 void EventHandler::OnEventHandlerError(int errornum)
66 void SocketEngine::InitError()
68 std::cerr << con_red << "FATAL ERROR!" << con_reset << " Socket engine initialization failed. " << strerror(errno) << '.' << std::endl;
69 exit(EXIT_STATUS_SOCKETENGINE);
72 void SocketEngine::LookupMaxFds()
75 if (!getrlimit(RLIMIT_NOFILE, &limits))
76 MaxSetSize = limits.rlim_cur;
79 limits.rlim_cur = limits.rlim_max == RLIM_INFINITY ? OPEN_MAX : limits.rlim_max;
81 limits.rlim_cur = limits.rlim_max;
83 if (!setrlimit(RLIMIT_NOFILE, &limits))
84 MaxSetSize = limits.rlim_cur;
87 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
89 int old_m = eh->event_mask;
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;
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());
106 eh->event_mask = new_m;
107 OnSetEvent(eh, old_m, new_m);
110 void SocketEngine::DispatchTrialWrites()
112 std::vector<int> working_list;
113 working_list.reserve(trials.size());
114 working_list.assign(trials.begin(), trials.end());
116 for(unsigned int i=0; i < working_list.size(); i++)
118 int fd = working_list[i];
119 EventHandler* eh = GetRef(fd);
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();
131 bool SocketEngine::AddFdRef(EventHandler* eh)
133 int fd = eh->GetFd();
137 while (static_cast<unsigned int>(fd) >= ref.size())
138 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
144 void SocketEngine::DelFdRef(EventHandler *eh)
146 int fd = eh->GetFd();
147 if (GetRef(fd) == eh)
154 bool SocketEngine::HasFd(int fd)
156 return GetRef(fd) != NULL;
159 EventHandler* SocketEngine::GetRef(int fd)
161 if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
166 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
176 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
178 return accept(fd->GetFd(), addr, addrlen);
181 int SocketEngine::Close(EventHandler* eh)
184 int ret = Close(eh->GetFd());
189 int SocketEngine::Close(int fd)
192 return closesocket(fd);
198 int SocketEngine::Blocking(int fd)
201 unsigned long opt = 0;
202 return ioctlsocket(fd, FIONBIO, &opt);
204 int flags = fcntl(fd, F_GETFL, 0);
205 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
209 int SocketEngine::NonBlocking(int fd)
212 unsigned long opt = 1;
213 return ioctlsocket(fd, FIONBIO, &opt);
215 int flags = fcntl(fd, F_GETFL, 0);
216 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
220 void SocketEngine::SetReuse(int fd)
223 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
226 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
228 int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
229 stats.UpdateReadCounters(nbRecvd);
233 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
235 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
236 stats.UpdateWriteCounters(nbSent);
240 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
242 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
243 stats.UpdateReadCounters(nbRecvd);
247 int SocketEngine::SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address)
249 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, &address.sa, address.sa_size());
250 stats.UpdateWriteCounters(nbSent);
254 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
256 int sent = writev(fd->GetFd(), iovec, count);
257 stats.UpdateWriteCounters(sent);
262 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
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)));
271 for (int i = 0; i < count; i++)
273 wiovec[i].iov_len = iovec[i].iov_len;
274 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
276 return WriteV(fd, wiovec, count);
280 int SocketEngine::Connect(EventHandler* fd, const irc::sockets::sockaddrs& address)
282 int ret = connect(fd->GetFd(), &address.sa, address.sa_size());
284 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
290 int SocketEngine::Shutdown(EventHandler* fd, int how)
292 return shutdown(fd->GetFd(), how);
295 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
297 return bind(fd, &addr.sa, addr.sa_size());
300 int SocketEngine::Listen(int sockfd, int backlog)
302 return listen(sockfd, backlog);
305 int SocketEngine::Shutdown(int fd, int how)
307 return shutdown(fd, how);
310 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
321 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
328 else if (len_out < 0)
332 void SocketEngine::Statistics::CheckFlush() const
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)
339 indata = outdata = 0;
343 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
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;
353 std::string SocketEngine::LastError()
356 return strerror(errno);
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);
363 std::string::size_type p;
364 std::string ret = szErrorString;
365 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
372 std::string SocketEngine::GetError(int errnum)
375 return strerror(errnum);
377 WSASetLastError(errnum);