]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengine.cpp
Merge insp20
[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 "inspircd.h"
25
26
27 /** Reference table, contains all current handlers
28  **/
29 std::vector<EventHandler*> SocketEngine::ref;
30
31 /** Current number of descriptors in the engine
32  */
33 size_t SocketEngine::CurrentSetSize = 0;
34
35 /** List of handlers that want a trial read/write
36  */
37 std::set<int> SocketEngine::trials;
38
39 int SocketEngine::MAX_DESCRIPTORS;
40
41 /** Socket engine statistics: count of various events, bandwidth usage
42  */
43 SocketEngine::Statistics SocketEngine::stats;
44
45 EventHandler::EventHandler()
46 {
47         fd = -1;
48         event_mask = 0;
49 }
50
51 void EventHandler::SetFd(int FD)
52 {
53         this->fd = FD;
54 }
55
56 void EventHandler::OnEventHandlerWrite()
57 {
58 }
59
60 void EventHandler::OnEventHandlerError(int errornum)
61 {
62 }
63
64 void SocketEngine::ChangeEventMask(EventHandler* eh, int change)
65 {
66         int old_m = eh->event_mask;
67         int new_m = old_m;
68
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;
74
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());
78
79         new_m |= change;
80         if (new_m == old_m)
81                 return;
82
83         eh->event_mask = new_m;
84         OnSetEvent(eh, old_m, new_m);
85 }
86
87 void SocketEngine::DispatchTrialWrites()
88 {
89         std::vector<int> working_list;
90         working_list.reserve(trials.size());
91         working_list.assign(trials.begin(), trials.end());
92         trials.clear();
93         for(unsigned int i=0; i < working_list.size(); i++)
94         {
95                 int fd = working_list[i];
96                 EventHandler* eh = GetRef(fd);
97                 if (!eh)
98                         continue;
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();
105         }
106 }
107
108 bool SocketEngine::AddFdRef(EventHandler* eh)
109 {
110         int fd = eh->GetFd();
111         if (HasFd(fd))
112                 return false;
113
114         while (static_cast<unsigned int>(fd) >= ref.size())
115                 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
116         ref[fd] = eh;
117         CurrentSetSize++;
118         return true;
119 }
120
121 void SocketEngine::DelFdRef(EventHandler *eh)
122 {
123         int fd = eh->GetFd();
124         if (GetRef(fd) == eh)
125         {
126                 ref[fd] = NULL;
127                 CurrentSetSize--;
128         }
129 }
130
131 bool SocketEngine::HasFd(int fd)
132 {
133         return GetRef(fd) != NULL;
134 }
135
136 EventHandler* SocketEngine::GetRef(int fd)
137 {
138         if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
139                 return NULL;
140         return ref[fd];
141 }
142
143 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
144 {
145         if (!eh)
146                 return false;
147         if (eh->GetFd() < 0)
148                 return false;
149         return true;
150 }
151
152
153 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
154 {
155         return accept(fd->GetFd(), addr, addrlen);
156 }
157
158 int SocketEngine::Close(EventHandler* eh)
159 {
160         DelFd(eh);
161         int ret = Close(eh->GetFd());
162         eh->SetFd(-1);
163         return ret;
164 }
165
166 int SocketEngine::Close(int fd)
167 {
168 #ifdef _WIN32
169         return closesocket(fd);
170 #else
171         return close(fd);
172 #endif
173 }
174
175 int SocketEngine::Blocking(int fd)
176 {
177 #ifdef _WIN32
178         unsigned long opt = 0;
179         return ioctlsocket(fd, FIONBIO, &opt);
180 #else
181         int flags = fcntl(fd, F_GETFL, 0);
182         return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
183 #endif
184 }
185
186 int SocketEngine::NonBlocking(int fd)
187 {
188 #ifdef _WIN32
189         unsigned long opt = 1;
190         return ioctlsocket(fd, FIONBIO, &opt);
191 #else
192         int flags = fcntl(fd, F_GETFL, 0);
193         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
194 #endif
195 }
196
197 void SocketEngine::SetReuse(int fd)
198 {
199         int on = 1;
200         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
201 }
202
203 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
204 {
205         int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
206         if (nbRecvd > 0)
207                 stats.Update(nbRecvd, 0);
208         return nbRecvd;
209 }
210
211 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
212 {
213         int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
214         if (nbSent > 0)
215                 stats.Update(0, nbSent);
216         return nbSent;
217 }
218
219 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
220 {
221         int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
222         if (nbRecvd > 0)
223                 stats.Update(nbRecvd, 0);
224         return nbRecvd;
225 }
226
227 int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen)
228 {
229         int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, to, tolen);
230         if (nbSent > 0)
231                 stats.Update(0, nbSent);
232         return nbSent;
233 }
234
235 int SocketEngine::WriteV(EventHandler* fd, const IOVector* iovec, int count)
236 {
237         int sent = writev(fd->GetFd(), iovec, count);
238         if (sent > 0)
239                 stats.Update(0, sent);
240         return sent;
241 }
242
243 #ifdef _WIN32
244 int SocketEngine::WriteV(EventHandler* fd, const iovec* iovec, int count)
245 {
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)));
252
253         for (int i = 0; i < count; i++)
254         {
255                 wiovec[i].iov_len = iovec[i].iov_len;
256                 wiovec[i].iov_base = reinterpret_cast<char*>(iovec[i].iov_base);
257         }
258         return WriteV(fd, wiovec, count);
259 }
260 #endif
261
262 int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
263 {
264         int ret = connect(fd->GetFd(), serv_addr, addrlen);
265 #ifdef _WIN32
266         if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
267                 errno = EINPROGRESS;
268 #endif
269         return ret;
270 }
271
272 int SocketEngine::Shutdown(EventHandler* fd, int how)
273 {
274         return shutdown(fd->GetFd(), how);
275 }
276
277 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
278 {
279         return bind(fd, &addr.sa, addr.sa_size());
280 }
281
282 int SocketEngine::Listen(int sockfd, int backlog)
283 {
284         return listen(sockfd, backlog);
285 }
286
287 int SocketEngine::Shutdown(int fd, int how)
288 {
289         return shutdown(fd, how);
290 }
291
292 void SocketEngine::Statistics::Update(size_t len_in, size_t len_out)
293 {
294         CheckFlush();
295         indata += len_in;
296         outdata += len_out;
297 }
298
299 void SocketEngine::Statistics::CheckFlush() const
300 {
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)
304         {
305                 lastempty = now;
306                 indata = outdata = 0;
307         }
308 }
309
310 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
311 {
312         CheckFlush();
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;
318 }
319
320 std::string SocketEngine::LastError()
321 {
322 #ifndef _WIN32
323         return strerror(errno);
324 #else
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);
329
330         std::string::size_type p;
331         std::string ret = szErrorString;
332         while ((p = ret.find_last_of("\r\n")) != std::string::npos)
333                 ret.erase(p, 1);
334
335         return ret;
336 #endif
337 }
338
339 std::string SocketEngine::GetError(int errnum)
340 {
341 #ifndef _WIN32
342         return strerror(errnum);
343 #else
344         WSASetLastError(errnum);
345         return LastError();
346 #endif
347 }