]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengine.cpp
86608f0a31d90c4461020916ae0541deb844c99d
[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 SocketEngine::ChangeEventMask(EventHandler* eh, int change)
57 {
58         int old_m = eh->event_mask;
59         int new_m = old_m;
60
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;
66
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());
70
71         new_m |= change;
72         if (new_m == old_m)
73                 return;
74
75         eh->event_mask = new_m;
76         OnSetEvent(eh, old_m, new_m);
77 }
78
79 void SocketEngine::DispatchTrialWrites()
80 {
81         std::vector<int> working_list;
82         working_list.reserve(trials.size());
83         working_list.assign(trials.begin(), trials.end());
84         trials.clear();
85         for(unsigned int i=0; i < working_list.size(); i++)
86         {
87                 int fd = working_list[i];
88                 EventHandler* eh = GetRef(fd);
89                 if (!eh)
90                         continue;
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);
97         }
98 }
99
100 bool SocketEngine::AddFdRef(EventHandler* eh)
101 {
102         int fd = eh->GetFd();
103         if (HasFd(fd))
104                 return false;
105
106         while (static_cast<unsigned int>(fd) >= ref.size())
107                 ref.resize(ref.empty() ? 1 : (ref.size() * 2));
108         ref[fd] = eh;
109         CurrentSetSize++;
110         return true;
111 }
112
113 void SocketEngine::DelFdRef(EventHandler *eh)
114 {
115         int fd = eh->GetFd();
116         if (GetRef(fd) == eh)
117         {
118                 ref[fd] = NULL;
119                 CurrentSetSize--;
120         }
121 }
122
123 bool SocketEngine::HasFd(int fd)
124 {
125         return GetRef(fd) != NULL;
126 }
127
128 EventHandler* SocketEngine::GetRef(int fd)
129 {
130         if (fd < 0 || static_cast<unsigned int>(fd) >= ref.size())
131                 return NULL;
132         return ref[fd];
133 }
134
135 bool SocketEngine::BoundsCheckFd(EventHandler* eh)
136 {
137         if (!eh)
138                 return false;
139         if ((eh->GetFd() < 0) || (eh->GetFd() > GetMaxFds()))
140                 return false;
141         return true;
142 }
143
144
145 int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
146 {
147         return accept(fd->GetFd(), addr, addrlen);
148 }
149
150 int SocketEngine::Close(EventHandler* eh)
151 {
152         DelFd(eh);
153         int ret = Close(eh->GetFd());
154         eh->SetFd(-1);
155         return ret;
156 }
157
158 int SocketEngine::Close(int fd)
159 {
160 #ifdef _WIN32
161         return closesocket(fd);
162 #else
163         return close(fd);
164 #endif
165 }
166
167 int SocketEngine::Blocking(int fd)
168 {
169 #ifdef _WIN32
170         unsigned long opt = 0;
171         return ioctlsocket(fd, FIONBIO, &opt);
172 #else
173         int flags = fcntl(fd, F_GETFL, 0);
174         return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
175 #endif
176 }
177
178 int SocketEngine::NonBlocking(int fd)
179 {
180 #ifdef _WIN32
181         unsigned long opt = 1;
182         return ioctlsocket(fd, FIONBIO, &opt);
183 #else
184         int flags = fcntl(fd, F_GETFL, 0);
185         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
186 #endif
187 }
188
189 void SocketEngine::SetReuse(int fd)
190 {
191         int on = 1;
192         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
193 }
194
195 int SocketEngine::RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen)
196 {
197         int nbRecvd = recvfrom(fd->GetFd(), (char*)buf, len, flags, from, fromlen);
198         if (nbRecvd > 0)
199                 stats.Update(nbRecvd, 0);
200         return nbRecvd;
201 }
202
203 int SocketEngine::Send(EventHandler* fd, const void *buf, size_t len, int flags)
204 {
205         int nbSent = send(fd->GetFd(), (const char*)buf, len, flags);
206         if (nbSent > 0)
207                 stats.Update(0, nbSent);
208         return nbSent;
209 }
210
211 int SocketEngine::Recv(EventHandler* fd, void *buf, size_t len, int flags)
212 {
213         int nbRecvd = recv(fd->GetFd(), (char*)buf, len, flags);
214         if (nbRecvd > 0)
215                 stats.Update(nbRecvd, 0);
216         return nbRecvd;
217 }
218
219 int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen)
220 {
221         int nbSent = sendto(fd->GetFd(), (const char*)buf, len, flags, to, tolen);
222         if (nbSent > 0)
223                 stats.Update(0, nbSent);
224         return nbSent;
225 }
226
227 int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
228 {
229         int ret = connect(fd->GetFd(), serv_addr, addrlen);
230 #ifdef _WIN32
231         if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
232                 errno = EINPROGRESS;
233 #endif
234         return ret;
235 }
236
237 int SocketEngine::Shutdown(EventHandler* fd, int how)
238 {
239         return shutdown(fd->GetFd(), how);
240 }
241
242 int SocketEngine::Bind(int fd, const irc::sockets::sockaddrs& addr)
243 {
244         return bind(fd, &addr.sa, addr.sa_size());
245 }
246
247 int SocketEngine::Listen(int sockfd, int backlog)
248 {
249         return listen(sockfd, backlog);
250 }
251
252 int SocketEngine::Shutdown(int fd, int how)
253 {
254         return shutdown(fd, how);
255 }
256
257 void SocketEngine::Statistics::Update(size_t len_in, size_t len_out)
258 {
259         CheckFlush();
260         indata += len_in;
261         outdata += len_out;
262 }
263
264 void SocketEngine::Statistics::CheckFlush() const
265 {
266         // Reset the in/out byte counters if it has been more than a second
267         time_t now = ServerInstance->Time();
268         if (lastempty != now)
269         {
270                 lastempty = now;
271                 indata = outdata = 0;
272         }
273 }
274
275 void SocketEngine::Statistics::GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const
276 {
277         CheckFlush();
278         float in_kbit = indata * 8;
279         float out_kbit = outdata * 8;
280         kbitpersec_total = ((in_kbit + out_kbit) / 1024);
281         kbitpersec_in = in_kbit / 1024;
282         kbitpersec_out = out_kbit / 1024;
283 }
284
285 std::string SocketEngine::LastError()
286 {
287 #ifndef _WIN32
288         return strerror(errno);
289 #else
290         char szErrorString[500];
291         DWORD dwErrorCode = WSAGetLastError();
292         if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szErrorString, _countof(szErrorString), NULL) == 0)
293                 sprintf_s(szErrorString, _countof(szErrorString), "Error code: %u", dwErrorCode);
294         return szErrorString;
295 #endif
296 }
297
298 std::string SocketEngine::GetError(int errnum)
299 {
300 #ifndef _WIN32
301         return strerror(errnum);
302 #else
303         WSASetLastError(errnum);
304         return LastError();
305 #endif
306 }