]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengines/socketengine_kqueue.cpp
07ea19d9dcce27f0990fc642ffeaeaec3f1abc8e
[user/henk/code/inspircd.git] / src / socketengines / socketengine_kqueue.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2009 Uli Schlachter <psychon@znc.in>
6  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *
8  * This file is part of InspIRCd.  InspIRCd is free software: you can
9  * redistribute it and/or modify it under the terms of the GNU General Public
10  * License as published by the Free Software Foundation, version 2.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
15  * details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21
22 #include "inspircd.h"
23 #include "exitcodes.h"
24 #include <sys/types.h>
25 #include <sys/event.h>
26 #include <sys/time.h>
27 #include "socketengine.h"
28 #include <iostream>
29 #include <sys/sysctl.h>
30
31 /** A specialisation of the SocketEngine class, designed to use BSD kqueue().
32  */
33 class KQueueEngine : public SocketEngine
34 {
35 private:
36         int EngineHandle;
37         /** These are used by kqueue() to hold socket events
38          */
39         std::vector<struct kevent> ke_list;
40         /** This is a specialised time value used by kqueue()
41          */
42         struct timespec ts;
43 public:
44         /** Create a new KQueueEngine
45          */
46         KQueueEngine();
47         /** Delete a KQueueEngine
48          */
49         virtual ~KQueueEngine();
50         bool AddFd(EventHandler* eh, int event_mask);
51         void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
52         virtual void DelFd(EventHandler* eh);
53         virtual int DispatchEvents();
54         virtual std::string GetName();
55         virtual void RecoverFromFork();
56 };
57
58 KQueueEngine::KQueueEngine() : ke_list(1)
59 {
60         MAX_DESCRIPTORS = 0;
61         int mib[2];
62         size_t len;
63
64         mib[0] = CTL_KERN;
65 #ifdef KERN_MAXFILESPERPROC
66         mib[1] = KERN_MAXFILESPERPROC;
67 #else
68         mib[1] = KERN_MAXFILES;
69 #endif
70         len = sizeof(MAX_DESCRIPTORS);
71         sysctl(mib, 2, &MAX_DESCRIPTORS, &len, NULL, 0);
72         if (MAX_DESCRIPTORS <= 0)
73         {
74                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Can't determine maximum number of open sockets!");
75                 std::cout << "ERROR: Can't determine maximum number of open sockets!" << std::endl;
76                 ServerInstance->QuickExit(EXIT_STATUS_SOCKETENGINE);
77         }
78
79         this->RecoverFromFork();
80 }
81
82 void KQueueEngine::RecoverFromFork()
83 {
84         /*
85          * The only bad thing about kqueue is that its fd cant survive a fork and is not inherited.
86          * BUM HATS.
87          *
88          */
89         EngineHandle = kqueue();
90         if (EngineHandle == -1)
91         {
92                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Could not initialize socket engine. Your kernel probably does not have the proper features.");
93                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: this is a fatal error, exiting now.");
94                 std::cout << "ERROR: Could not initialize socket engine. Your kernel probably does not have the proper features." << std::endl;
95                 std::cout << "ERROR: this is a fatal error, exiting now." << std::endl;
96                 ServerInstance->QuickExit(EXIT_STATUS_SOCKETENGINE);
97         }
98         CurrentSetSize = 0;
99 }
100
101 KQueueEngine::~KQueueEngine()
102 {
103         this->Close(EngineHandle);
104 }
105
106 bool KQueueEngine::AddFd(EventHandler* eh, int event_mask)
107 {
108         int fd = eh->GetFd();
109
110         if ((fd < 0) || (fd > GetMaxFds() - 1))
111                 return false;
112
113         if (!SocketEngine::AddFd(eh))
114                 return false;
115
116         // We always want to read from the socket...
117         struct kevent ke;
118         EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, NULL);
119
120         int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
121         if (i == -1)
122         {
123                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Failed to add fd: %d %s",
124                                           fd, strerror(errno));
125                 return false;
126         }
127
128         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "New file descriptor: %d", fd);
129
130         SocketEngine::SetEventMask(eh, event_mask);
131         OnSetEvent(eh, 0, event_mask);
132         CurrentSetSize++;
133         ResizeDouble(ke_list);
134
135         return true;
136 }
137
138 void KQueueEngine::DelFd(EventHandler* eh)
139 {
140         int fd = eh->GetFd();
141
142         if ((fd < 0) || (fd > GetMaxFds() - 1))
143         {
144                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "DelFd() on invalid fd: %d", fd);
145                 return;
146         }
147
148         struct kevent ke;
149
150         // First remove the write filter ignoring errors, since we can't be
151         // sure if there are actually any write filters registered.
152         EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
153         kevent(EngineHandle, &ke, 1, 0, 0, NULL);
154
155         // Then remove the read filter.
156         EV_SET(&ke, eh->GetFd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
157         int j = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
158
159         if (j < 0)
160         {
161                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Failed to remove fd: %d %s",
162                                           fd, strerror(errno));
163         }
164
165         SocketEngine::DelFd(eh);
166         CurrentSetSize--;
167
168         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Remove file descriptor: %d", fd);
169 }
170
171 void KQueueEngine::OnSetEvent(EventHandler* eh, int old_mask, int new_mask)
172 {
173         if ((new_mask & FD_WANT_POLL_WRITE) && !(old_mask & FD_WANT_POLL_WRITE))
174         {
175                 // new poll-style write
176                 struct kevent ke;
177                 EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_ADD, 0, 0, NULL);
178                 int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
179                 if (i < 0)
180                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Failed to mark for writing: %d %s",
181                                                   eh->GetFd(), strerror(errno));
182         }
183         else if ((old_mask & FD_WANT_POLL_WRITE) && !(new_mask & FD_WANT_POLL_WRITE))
184         {
185                 // removing poll-style write
186                 struct kevent ke;
187                 EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
188                 int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
189                 if (i < 0)
190                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Failed to mark for writing: %d %s",
191                                                   eh->GetFd(), strerror(errno));
192         }
193         if ((new_mask & (FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)) && !(old_mask & (FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)))
194         {
195                 // new one-shot write
196                 struct kevent ke;
197                 EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, NULL);
198                 int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
199                 if (i < 0)
200                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Failed to mark for writing: %d %s",
201                                                   eh->GetFd(), strerror(errno));
202         }
203 }
204
205 int KQueueEngine::DispatchEvents()
206 {
207         ts.tv_nsec = 0;
208         ts.tv_sec = 1;
209
210         int i = kevent(EngineHandle, NULL, 0, &ke_list[0], ke_list.size(), &ts);
211         ServerInstance->UpdateTime();
212
213         if (i < 0)
214                 return i;
215
216         TotalEvents += i;
217
218         for (int j = 0; j < i; j++)
219         {
220                 struct kevent& kev = ke_list[j];
221
222                 // Copy these in case the vector gets resized and kev invalidated
223                 const int fd = kev.ident;
224                 const short filter = kev.filter;
225
226                 EventHandler* eh = GetRef(fd);
227                 if (!eh)
228                         continue;
229
230                 if (kev.flags & EV_EOF)
231                 {
232                         ErrorEvents++;
233                         eh->HandleEvent(EVENT_ERROR, kev.fflags);
234                         continue;
235                 }
236                 if (filter == EVFILT_WRITE)
237                 {
238                         WriteEvents++;
239                         /* When mask is FD_WANT_FAST_WRITE or FD_WANT_SINGLE_WRITE,
240                          * we set a one-shot write, so we need to clear that bit
241                          * to detect when it set again.
242                          */
243                         const int bits_to_clr = FD_WANT_SINGLE_WRITE | FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
244                         SetEventMask(eh, eh->GetEventMask() & ~bits_to_clr);
245                         eh->HandleEvent(EVENT_WRITE);
246                 }
247                 else if (filter == EVFILT_READ)
248                 {
249                         ReadEvents++;
250                         SetEventMask(eh, eh->GetEventMask() & ~FD_READ_WILL_BLOCK);
251                         eh->HandleEvent(EVENT_READ);
252                 }
253         }
254
255         return i;
256 }
257
258 std::string KQueueEngine::GetName()
259 {
260         return "kqueue";
261 }
262
263 SocketEngine* CreateSocketEngine()
264 {
265         return new KQueueEngine;
266 }