]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengine.cpp
Fix some remaining uses of ato[il].
[user/henk/code/inspircd.git] / src / socketengine.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
9  *
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.
13  *
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
17  * details.
18  *
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/>.
21  */
22
23
24 #include "exitcodes.h"
25 #include "inspircd.h"
26
27 #include <iostream>
28
29 /** Reference table, contains all current handlers
30  **/
31 std::vector<EventHandler*> SocketEngine::ref;
32
33 /** Current number of descriptors in the engine
34  */
35 size_t SocketEngine::CurrentSetSize = 0;
36
37 /** List of handlers that want a trial read/write
38  */
39 std::set<int> SocketEngine::trials;
40
41 size_t SocketEngine::MaxSetSize = 0;
42
43 /** Socket engine statistics: count of various events, bandwidth usage
44  */
45 SocketEngine::Statistics SocketEngine::stats;
46
47 EventHandler::EventHandler()
48 {
49         fd = -1;
50         event_mask = 0;
51 }
52
53 void EventHandler::SwapInternals(EventHandler& other)
54 {
55         std::swap(fd, other.fd);
56         std::swap(event_mask, other.event_mask);
57 }
58
59 void EventHandler::SetFd(int FD)
60 {
61         this->fd = FD;
62 }
63
64 void EventHandler::OnEventHandlerWrite()
65 {
66 }
67
68 void EventHandler::OnEventHandlerError(int errornum)
69 {
70 }
71
72 void SocketEngine::InitError()
73 {
74         std::cerr << con_red << "FATAL ERROR!" << con_reset << " Socket engine initialization failed. " << strerror(errno) << '.' << std::endl;
75         exit(EXIT_STATUS_SOCKETENGINE);
76 }
77
78 void SocketEngine::LookupMaxFds()
79 {
80 #if defined _WIN32
81         MaxSetSize = FD_SETSIZE;
82 #else
83         struct rlimit limits;
84         if (!getrlimit(RLIMIT_NOFILE, &limits))
85                 MaxSetSize = limits.rlim_cur;
86
87 #if defined __APPLE__
88         limits.rlim_cur = limits.rlim_max == RLIM_INFINITY ? OPEN_MAX : limits.rlim_max;
89 #else
90         limits.rlim_cur = limits.rlim_max;
91 #endif
92         if (!setrlimit(RLIMIT_NOFILE, &limits))
93                 MaxSetSize = limits.rlim_cur;
94 #endif
95 }
96
97 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
98 {
99         int old_m = eh->event_mask;
100         int new_m = old_m;
101
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;
107
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());
111
112         new_m |= change;
113         if (new_m == old_m)
114                 return;
115
116         eh->event_mask = new_m;
117         OnSetEvent(eh, old_m, new_m);
118 }
119
120 void SocketEngine::DispatchTrialWrites()
121 {
122         std::vector<int> working_list;
123         working_list.reserve(trials.size());
124         working_list.assign(trials.begin(), trials.end());
125         trials.clear();
126         for(unsigned int i=0; i < working_list.size(); i++)
127         {
128                 int fd = working_list[i];
129                 EventHandler* eh = GetRef(fd);
130                 if (!eh)
131                         continue;
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();
138         }
139 }
140
141 bool SocketEngine::AddFdRef(EventHandler* eh)
142 {
143         int fd = eh->GetFd();
144         if (HasFd(fd))
145                 return false;
146
147         while (static_cast<unsigned int>(fd) >= ref.size())
148                 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
149         ref[fd] = eh;
150         CurrentSetSize++;
151         return true;
152 }
153
154 void SocketEngine::DelFdRef(EventHandler *eh)
155 {
156         int fd = eh->GetFd();
157         if (GetRef(fd) == eh)
158         {
159                 ref[fd] = NULL;
160                 CurrentSetSize--;
161         }
162 }
163
164 bool SocketEngine::HasFd(int fd)
165 {
166         return GetRef(fd) != NULL;
167 }
168
169 EventHandler* SocketEngine::GetRef(int fd)
170 {
171         if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
172                 return NULL;
173         return ref[fd];
174 }
175
176 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
177 {
178         if (!eh)
179                 return false;
180         if (eh->GetFd() < 0)
181                 return false;
182         return true;
183 }
184
185
186 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
187 {
188         return accept(fd->GetFd(), addr, addrlen);
189 }
190
191 int SocketEngine::Close(EventHandler* eh)
192 {
193         DelFd(eh);
194         int ret = Close(eh->GetFd());
195         eh->SetFd(-1);
196         return ret;
197 }
198
199 int SocketEngine::Close(int fd)
200 {
201 #ifdef _WIN32
202         return closesocket(fd);
203 #else
204         return close(fd);
205 #endif
206 }
207
208 int SocketEngine::Blocking(int fd)
209 {
210 #ifdef _WIN32
211         unsigned long opt = 0;
212         return ioctlsocket(fd, FIONBIO, &opt);
213 #else
214         int flags = fcntl(fd, F_GETFL, 0);
215         return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
216 #endif
217 }
218
219 int SocketEngine::NonBlocking(int fd)
220 {
221 #ifdef _WIN32
222         unsigned long opt = 1;
223         return ioctlsocket(fd, FIONBIO, &opt);
224 #else
225         int flags = fcntl(fd, F_GETFL, 0);
226         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
227 #endif
228 }
229
230 void SocketEngine::SetReuse(int fd)
231 {
232         int on = 1;
233         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
234 }
235
236 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
237 {
238         int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
239         stats.UpdateReadCounters(nbRecvd);
240         return nbRecvd;
241 }
242
243 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
244 {
245         int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
246         stats.UpdateWriteCounters(nbSent);
247         return nbSent;
248 }
249
250 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
251 {
252         int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
253         stats.UpdateReadCounters(nbRecvd);
254         return nbRecvd;
255 }
256
257 int SocketEngine::SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address)
258 {
259         int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, &address.sa, address.sa_size());
260         stats.UpdateWriteCounters(nbSent);
261         return nbSent;
262 }
263
264 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
265 {
266         int sent = writev(fd->GetFd(), iovec, count);
267         stats.UpdateWriteCounters(sent);
268         return sent;
269 }
270
271 #ifdef _WIN32
272 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
273 {
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)));
280
281         for (int i = 0; i < count; i++)
282         {
283                 wiovec[i].iov_len = iovec[i].iov_len;
284                 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
285         }
286         return WriteV(fd, wiovec, count);
287 }
288 #endif
289
290 int SocketEngine::Connect(EventHandler* fd, const irc::sockets::sockaddrs& address)
291 {
292         int ret = connect(fd->GetFd(), &address.sa, address.sa_size());
293 #ifdef _WIN32
294         if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
295                 errno = EINPROGRESS;
296 #endif
297         return ret;
298 }
299
300 int SocketEngine::Shutdown(EventHandler* fd, int how)
301 {
302         return shutdown(fd->GetFd(), how);
303 }
304
305 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
306 {
307         return bind(fd, &addr.sa, addr.sa_size());
308 }
309
310 int SocketEngine::Listen(int sockfd, int backlog)
311 {
312         return listen(sockfd, backlog);
313 }
314
315 int SocketEngine::Shutdown(int fd, int how)
316 {
317         return shutdown(fd, how);
318 }
319
320 void SocketEngine::Statistics::UpdateReadCounters(int len_in)
321 {
322         CheckFlush();
323
324         ReadEvents++;
325         if (len_in > 0)
326                 indata += len_in;
327         else if (len_in < 0)
328                 ErrorEvents++;
329 }
330
331 void SocketEngine::Statistics::UpdateWriteCounters(int len_out)
332 {
333         CheckFlush();
334
335         WriteEvents++;
336         if (len_out > 0)
337                 outdata += len_out;
338         else if (len_out < 0)
339                 ErrorEvents++;
340 }
341
342 void SocketEngine::Statistics::CheckFlush() const
343 {
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)
347         {
348                 lastempty = now;
349                 indata = outdata = 0;
350         }
351 }
352
353 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
354 {
355         CheckFlush();
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;
361 }
362
363 std::string SocketEngine::LastError()
364 {
365 #ifndef _WIN32
366         return strerror(errno);
367 #else
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);
372
373         std::string::size_type p;
374         std::string ret = szErrorString;
375         while ((p = ret.find_last_of("\r\n")) != std::string::npos)
376                 ret.erase(p, 1);
377
378         return ret;
379 #endif
380 }
381
382 std::string SocketEngine::GetError(int errnum)
383 {
384 #ifndef _WIN32
385         return strerror(errnum);
386 #else
387         WSASetLastError(errnum);
388         return LastError();
389 #endif
390 }