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);
207 stats.Update(nbRecvd, 0);
211 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
213 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
215 stats.Update(0, nbSent);
219 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
221 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
223 stats.Update(nbRecvd, 0);
227 int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen)
229 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, to, tolen);
231 stats.Update(0, nbSent);
235 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
237 int sent = writev(fd->GetFd(), iovec, count);
239 stats.Update(0, sent);
244 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
246 // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
247 // the fields in the correct order.
248 // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
249 // platform's native struct.
250 IOVector wiovec[128];
251 count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
253 for (int i = 0; i < count; i++)
255 wiovec[i].iov_len = iovec[i].iov_len;
256 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
258 return WriteV(fd, wiovec, count);
262 int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
264 int ret = connect(fd->GetFd(), serv_addr, addrlen);
266 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
272 int SocketEngine::Shutdown(EventHandler* fd, int how)
274 return shutdown(fd->GetFd(), how);
277 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
279 return bind(fd, &addr.sa, addr.sa_size());
282 int SocketEngine::Listen(int sockfd, int backlog)
284 return listen(sockfd, backlog);
287 int SocketEngine::Shutdown(int fd, int how)
289 return shutdown(fd, how);
292 void SocketEngine::Statistics::Update(size_t len_in, size_t len_out)
299 void SocketEngine::Statistics::CheckFlush() const
301 // Reset the in/out byte counters if it has been more than a second
302 time_t now = ServerInstance->Time();
303 if (lastempty != now)
306 indata = outdata = 0;
310 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
313 float in_kbit = indata * 8;
314 float out_kbit = outdata * 8;
315 kbitpersec_total = ((in_kbit + out_kbit) / 1024);
316 kbitpersec_in = in_kbit / 1024;
317 kbitpersec_out = out_kbit / 1024;
320 std::string SocketEngine::LastError()
323 return strerror(errno);
325 char szErrorString[500];
326 DWORD dwErrorCode = WSAGetLastError();
327 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
328 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
330 std::string::size_type p;
331 std::string ret = szErrorString;
332 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
339 std::string SocketEngine::GetError(int errnum)
342 return strerror(errnum);
344 WSASetLastError(errnum);