]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengines/socketengine_kqueue.cpp
Replace printf(_c) with iostream
[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
30 /** A specialisation of the SocketEngine class, designed to use FreeBSD kqueue().
31  */
32 class KQueueEngine : public SocketEngine
33 {
34 private:
35         int EngineHandle;
36         /** These are used by kqueue() to hold socket events
37          */
38         struct kevent* ke_list;
39         /** This is a specialised time value used by kqueue()
40          */
41         struct timespec ts;
42 public:
43         /** Create a new KQueueEngine
44          */
45         KQueueEngine();
46         /** Delete a KQueueEngine
47          */
48         virtual ~KQueueEngine();
49         bool AddFd(EventHandler* eh, int event_mask);
50         void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
51         virtual void DelFd(EventHandler* eh);
52         virtual int DispatchEvents();
53         virtual std::string GetName();
54         virtual void RecoverFromFork();
55 };
56
57 #include <sys/sysctl.h>
58
59 KQueueEngine::KQueueEngine()
60 {
61         MAX_DESCRIPTORS = 0;
62         int mib[2];
63         size_t len;
64
65         mib[0] = CTL_KERN;
66         mib[1] = KERN_MAXFILESPERPROC;
67         len = sizeof(MAX_DESCRIPTORS);
68         sysctl(mib, 2, &MAX_DESCRIPTORS, &len, NULL, 0);
69         if (MAX_DESCRIPTORS <= 0)
70         {
71                 ServerInstance->Logs->Log("SOCKET", DEFAULT, "ERROR: Can't determine maximum number of open sockets!");
72                 std::cout << "ERROR: Can't determine maximum number of open sockets!" << std::endl;
73                 ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE);
74         }
75
76         this->RecoverFromFork();
77         ke_list = new struct kevent[GetMaxFds()];
78         ref = new EventHandler* [GetMaxFds()];
79         memset(ref, 0, GetMaxFds() * sizeof(EventHandler*));
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",DEFAULT, "ERROR: Could not initialize socket engine. Your kernel probably does not have the proper features.");
93                 ServerInstance->Logs->Log("SOCKET",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->Exit(EXIT_STATUS_SOCKETENGINE);
97         }
98         CurrentSetSize = 0;
99 }
100
101 KQueueEngine::~KQueueEngine()
102 {
103         this->Close(EngineHandle);
104         delete[] ref;
105         delete[] ke_list;
106 }
107
108 bool KQueueEngine::AddFd(EventHandler* eh, int event_mask)
109 {
110         int fd = eh->GetFd();
111
112         if ((fd < 0) || (fd > GetMaxFds() - 1))
113                 return false;
114
115         if (ref[fd])
116                 return false;
117
118         // We always want to read from the socket...
119         struct kevent ke;
120         EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, NULL);
121
122         int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
123         if (i == -1)
124         {
125                 ServerInstance->Logs->Log("SOCKET",DEFAULT,"Failed to add fd: %d %s",
126                                           fd, strerror(errno));
127                 return false;
128         }
129
130         ref[fd] = eh;
131         SocketEngine::SetEventMask(eh, event_mask);
132         OnSetEvent(eh, 0, event_mask);
133         CurrentSetSize++;
134
135         ServerInstance->Logs->Log("SOCKET",DEBUG,"New file descriptor: %d", fd);
136         return true;
137 }
138
139 void KQueueEngine::DelFd(EventHandler* eh)
140 {
141         int fd = eh->GetFd();
142
143         if ((fd < 0) || (fd > GetMaxFds() - 1))
144         {
145                 ServerInstance->Logs->Log("SOCKET",DEFAULT,"DelFd() on invalid fd: %d", fd);
146                 return;
147         }
148
149         struct kevent ke;
150
151         // First remove the write filter ignoring errors, since we can't be
152         // sure if there are actually any write filters registered.
153         EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
154         kevent(EngineHandle, &ke, 1, 0, 0, NULL);
155
156         // Then remove the read filter.
157         EV_SET(&ke, eh->GetFd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
158         int j = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
159
160         if (j < 0)
161         {
162                 ServerInstance->Logs->Log("SOCKET",DEFAULT,"Failed to remove fd: %d %s",
163                                           fd, strerror(errno));
164         }
165
166         CurrentSetSize--;
167         ref[fd] = NULL;
168
169         ServerInstance->Logs->Log("SOCKET",DEBUG,"Remove file descriptor: %d", fd);
170 }
171
172 void KQueueEngine::OnSetEvent(EventHandler* eh, int old_mask, int new_mask)
173 {
174         if ((new_mask & FD_WANT_POLL_WRITE) && !(old_mask & FD_WANT_POLL_WRITE))
175         {
176                 // new poll-style write
177                 struct kevent ke;
178                 EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_ADD, 0, 0, NULL);
179                 int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
180                 if (i < 0) {
181                         ServerInstance->Logs->Log("SOCKET",DEFAULT,"Failed to mark for writing: %d %s",
182                                                   eh->GetFd(), strerror(errno));
183                 }
184         }
185         else if ((old_mask & FD_WANT_POLL_WRITE) && !(new_mask & FD_WANT_POLL_WRITE))
186         {
187                 // removing poll-style write
188                 struct kevent ke;
189                 EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
190                 int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
191                 if (i < 0) {
192                         ServerInstance->Logs->Log("SOCKET",DEFAULT,"Failed to mark for writing: %d %s",
193                                                   eh->GetFd(), strerror(errno));
194                 }
195         }
196         if ((new_mask & (FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)) && !(old_mask & (FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)))
197         {
198                 // new one-shot write
199                 struct kevent ke;
200                 EV_SET(&ke, eh->GetFd(), EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, NULL);
201                 int i = kevent(EngineHandle, &ke, 1, 0, 0, NULL);
202                 if (i < 0) {
203                         ServerInstance->Logs->Log("SOCKET",DEFAULT,"Failed to mark for writing: %d %s",
204                                                   eh->GetFd(), strerror(errno));
205                 }
206         }
207 }
208
209 int KQueueEngine::DispatchEvents()
210 {
211         ts.tv_nsec = 0;
212         ts.tv_sec = 1;
213
214         int i = kevent(EngineHandle, NULL, 0, &ke_list[0], GetMaxFds(), &ts);
215         ServerInstance->UpdateTime();
216
217         TotalEvents += i;
218
219         for (int j = 0; j < i; j++)
220         {
221                 EventHandler* eh = ref[ke_list[j].ident];
222                 if (!eh)
223                         continue;
224                 if (ke_list[j].flags & EV_EOF)
225                 {
226                         ErrorEvents++;
227                         eh->HandleEvent(EVENT_ERROR, ke_list[j].fflags);
228                         continue;
229                 }
230                 if (ke_list[j].filter == EVFILT_WRITE)
231                 {
232                         WriteEvents++;
233                         /* When mask is FD_WANT_FAST_WRITE or FD_WANT_SINGLE_WRITE,
234                          * we set a one-shot write, so we need to clear that bit
235                          * to detect when it set again.
236                          */
237                         const int bits_to_clr = FD_WANT_SINGLE_WRITE | FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
238                         SetEventMask(eh, eh->GetEventMask() & ~bits_to_clr);
239                         eh->HandleEvent(EVENT_WRITE);
240
241                         if (eh != ref[ke_list[j].ident])
242                                 // whoops, deleted out from under us
243                                 continue;
244                 }
245                 if (ke_list[j].filter == EVFILT_READ)
246                 {
247                         ReadEvents++;
248                         SetEventMask(eh, eh->GetEventMask() & ~FD_READ_WILL_BLOCK);
249                         eh->HandleEvent(EVENT_READ);
250                 }
251         }
252
253         return i;
254 }
255
256 std::string KQueueEngine::GetName()
257 {
258         return "kqueue";
259 }
260
261 SocketEngine* CreateSocketEngine()
262 {
263         return new KQueueEngine;
264 }