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/>.
27 /** Reference table, contains all current handlers
29 std::vector<EventHandler*> SocketEngine::ref;
31 /** Current number of descriptors in the engine
33 size_t SocketEngine::CurrentSetSize = 0;
35 /** List of handlers that want a trial read/write
37 std::set<int> SocketEngine::trials;
39 int SocketEngine::MAX_DESCRIPTORS;
41 /** Socket engine statistics: count of various events, bandwidth usage
43 SocketEngine::Statistics SocketEngine::stats;
45 EventHandler::EventHandler()
51 void EventHandler::SetFd(int FD)
56 void EventHandler::OnEventHandlerWrite()
60 void EventHandler::OnEventHandlerError(int errornum)
64 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
66 int old_m = eh->event_mask;
69 // if we are changing read/write type, remove the previously set bit
70 if (change & FD_WANT_READ_MASK)
71 new_m &= ~FD_WANT_READ_MASK;
72 if (change & FD_WANT_WRITE_MASK)
73 new_m &= ~FD_WANT_WRITE_MASK;
75 // if adding a trial read/write, insert it into the set
76 if (change & FD_TRIAL_NOTE_MASK && !(old_m & FD_TRIAL_NOTE_MASK))
77 trials.insert(eh->GetFd());
83 eh->event_mask = new_m;
84 OnSetEvent(eh, old_m, new_m);
87 void SocketEngine::DispatchTrialWrites()
89 std::vector<int> working_list;
90 working_list.reserve(trials.size());
91 working_list.assign(trials.begin(), trials.end());
93 for(unsigned int i=0; i < working_list.size(); i++)
95 int fd = working_list[i];
96 EventHandler* eh = GetRef(fd);
99 int mask = eh->event_mask;
100 eh->event_mask &= ~(FD_ADD_TRIAL_READ | FD_ADD_TRIAL_WRITE);
101 if ((mask & (FD_ADD_TRIAL_READ | FD_READ_WILL_BLOCK)) == FD_ADD_TRIAL_READ)
102 eh->OnEventHandlerRead();
103 if ((mask & (FD_ADD_TRIAL_WRITE | FD_WRITE_WILL_BLOCK)) == FD_ADD_TRIAL_WRITE)
104 eh->OnEventHandlerWrite();
108 bool SocketEngine::AddFdRef(EventHandler* eh)
110 int fd = eh->GetFd();
114 while (static_cast<unsigned int>(fd) >= ref.size())
115 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
121 void SocketEngine::DelFdRef(EventHandler *eh)
123 int fd = eh->GetFd();
124 if (GetRef(fd) == eh)
131 bool SocketEngine::HasFd(int fd)
133 return GetRef(fd) != NULL;
136 EventHandler* SocketEngine::GetRef(int fd)
138 if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
143 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
153 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
155 return accept(fd->GetFd(), addr, addrlen);
158 int SocketEngine::Close(EventHandler* eh)
161 int ret = Close(eh->GetFd());
166 int SocketEngine::Close(int fd)
169 return closesocket(fd);
175 int SocketEngine::Blocking(int fd)
178 unsigned long opt = 0;
179 return ioctlsocket(fd, FIONBIO, &opt);
181 int flags = fcntl(fd, F_GETFL, 0);
182 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
186 int SocketEngine::NonBlocking(int fd)
189 unsigned long opt = 1;
190 return ioctlsocket(fd, FIONBIO, &opt);
192 int flags = fcntl(fd, F_GETFL, 0);
193 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
197 void SocketEngine::SetReuse(int fd)
200 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
203 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
205 int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
206 stats.UpdateReadCounters(nbRecvd);
210 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
212 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
213 stats.UpdateWriteCounters(nbSent);
217 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
219 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
220 stats.UpdateReadCounters(nbRecvd);
224 int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen)
226 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, to, tolen);
227 stats.UpdateWriteCounters(nbSent);
231 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
233 int sent = writev(fd->GetFd(), iovec, count);
234 stats.UpdateWriteCounters(sent);
239 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
241 // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
242 // the fields in the correct order.
243 // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
244 // platform's native struct.
245 IOVector wiovec[128];
246 count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
248 for (int i = 0; i < count; i++)
250 wiovec[i].iov_len = iovec[i].iov_len;
251 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
253 return WriteV(fd, wiovec, count);
257 int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
259 int ret = connect(fd->GetFd(), serv_addr, addrlen);
261 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
267 int SocketEngine::Shutdown(EventHandler* fd, int how)
269 return shutdown(fd->GetFd(), how);
272 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
274 return bind(fd, &addr.sa, addr.sa_size());
277 int SocketEngine::Listen(int sockfd, int backlog)
279 return listen(sockfd, backlog);
282 int SocketEngine::Shutdown(int fd, int how)
284 return shutdown(fd, how);
287 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
298 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
305 else if (len_out < 0)
309 void SocketEngine::Statistics::CheckFlush() const
311 // Reset the in/out byte counters if it has been more than a second
312 time_t now = ServerInstance->Time();
313 if (lastempty != now)
316 indata = outdata = 0;
320 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
323 float in_kbit = indata * 8;
324 float out_kbit = outdata * 8;
325 kbitpersec_total = ((in_kbit + out_kbit) / 1024);
326 kbitpersec_in = in_kbit / 1024;
327 kbitpersec_out = out_kbit / 1024;
330 std::string SocketEngine::LastError()
333 return strerror(errno);
335 char szErrorString[500];
336 DWORD dwErrorCode = WSAGetLastError();
337 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
338 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
340 std::string::size_type p;
341 std::string ret = szErrorString;
342 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
349 std::string SocketEngine::GetError(int errnum)
352 return strerror(errnum);
354 WSASetLastError(errnum);