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 SocketEngine::ChangeEventMask(EventHandler* eh, int change)
58 int old_m = eh->event_mask;
61 // if we are changing read/write type, remove the previously set bit
62 if (change & FD_WANT_READ_MASK)
63 new_m &= ~FD_WANT_READ_MASK;
64 if (change & FD_WANT_WRITE_MASK)
65 new_m &= ~FD_WANT_WRITE_MASK;
67 // if adding a trial read/write, insert it into the set
68 if (change & FD_TRIAL_NOTE_MASK && !(old_m & FD_TRIAL_NOTE_MASK))
69 trials.insert(eh->GetFd());
75 eh->event_mask = new_m;
76 OnSetEvent(eh, old_m, new_m);
79 void SocketEngine::DispatchTrialWrites()
81 std::vector<int> working_list;
82 working_list.reserve(trials.size());
83 working_list.assign(trials.begin(), trials.end());
85 for(unsigned int i=0; i < working_list.size(); i++)
87 int fd = working_list[i];
88 EventHandler* eh = GetRef(fd);
91 int mask = eh->event_mask;
92 eh->event_mask &= ~(FD_ADD_TRIAL_READ | FD_ADD_TRIAL_WRITE);
93 if ((mask & (FD_ADD_TRIAL_READ | FD_READ_WILL_BLOCK)) == FD_ADD_TRIAL_READ)
94 eh->HandleEvent(EVENT_READ, 0);
95 if ((mask & (FD_ADD_TRIAL_WRITE | FD_WRITE_WILL_BLOCK)) == FD_ADD_TRIAL_WRITE)
96 eh->HandleEvent(EVENT_WRITE, 0);
100 bool SocketEngine::AddFdRef(EventHandler* eh)
102 int fd = eh->GetFd();
106 while (static_cast<unsigned int>(fd) >= ref.size())
107 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
113 void SocketEngine::DelFdRef(EventHandler *eh)
115 int fd = eh->GetFd();
116 if (GetRef(fd) == eh)
123 bool SocketEngine::HasFd(int fd)
125 return GetRef(fd) != NULL;
128 EventHandler* SocketEngine::GetRef(int fd)
130 if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
135 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
145 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
147 return accept(fd->GetFd(), addr, addrlen);
150 int SocketEngine::Close(EventHandler* eh)
153 int ret = Close(eh->GetFd());
158 int SocketEngine::Close(int fd)
161 return closesocket(fd);
167 int SocketEngine::Blocking(int fd)
170 unsigned long opt = 0;
171 return ioctlsocket(fd, FIONBIO, &opt);
173 int flags = fcntl(fd, F_GETFL, 0);
174 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
178 int SocketEngine::NonBlocking(int fd)
181 unsigned long opt = 1;
182 return ioctlsocket(fd, FIONBIO, &opt);
184 int flags = fcntl(fd, F_GETFL, 0);
185 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
189 void SocketEngine::SetReuse(int fd)
192 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
195 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
197 int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
199 stats.Update(nbRecvd, 0);
203 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
205 int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
207 stats.Update(0, nbSent);
211 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
213 int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
215 stats.Update(nbRecvd, 0);
219 int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen)
221 int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, to, tolen);
223 stats.Update(0, nbSent);
227 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
229 int sent = writev(fd->GetFd(), iovec, count);
231 stats.Update(0, sent);
236 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
238 // On Windows the fields in iovec are not in the order required by the Winsock API; IOVector has
239 // the fields in the correct order.
240 // Create temporary IOVectors from the iovecs and pass them to the WriteV() method that accepts the
241 // platform's native struct.
242 IOVector wiovec[128];
243 count = std::min(count, static_cast<int>(sizeof(wiovec) / sizeof(IOVector)));
245 for (int i = 0; i < count; i++)
247 wiovec[i].iov_len = iovec[i].iov_len;
248 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
250 return WriteV(fd, wiovec, count);
254 int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
256 int ret = connect(fd->GetFd(), serv_addr, addrlen);
258 if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
264 int SocketEngine::Shutdown(EventHandler* fd, int how)
266 return shutdown(fd->GetFd(), how);
269 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
271 return bind(fd, &addr.sa, addr.sa_size());
274 int SocketEngine::Listen(int sockfd, int backlog)
276 return listen(sockfd, backlog);
279 int SocketEngine::Shutdown(int fd, int how)
281 return shutdown(fd, how);
284 void SocketEngine::Statistics::Update(size_t len_in, size_t len_out)
291 void SocketEngine::Statistics::CheckFlush() const
293 // Reset the in/out byte counters if it has been more than a second
294 time_t now = ServerInstance->Time();
295 if (lastempty != now)
298 indata = outdata = 0;
302 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
305 float in_kbit = indata * 8;
306 float out_kbit = outdata * 8;
307 kbitpersec_total = ((in_kbit + out_kbit) / 1024);
308 kbitpersec_in = in_kbit / 1024;
309 kbitpersec_out = out_kbit / 1024;
312 std::string SocketEngine::LastError()
315 return strerror(errno);
317 char szErrorString[500];
318 DWORD dwErrorCode = WSAGetLastError();
319 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
320 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
322 std::string::size_type p;
323 std::string ret = szErrorString;
324 while ((p = ret.find_last_of("\r\n")) != std::string::npos)
331 std::string SocketEngine::GetError(int errnum)
334 return strerror(errnum);
336 WSASetLastError(errnum);