]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socketengines/socketengine_kqueue.cpp
Relax fd bounds checking
[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 namespace
34 {
35         int EngineHandle;
36         unsigned int ChangePos = 0;
37         /** These are used by kqueue() to hold socket events
38          */
39         std::vector<struct kevent> ke_list(16);
40
41         /** Pending changes
42          */
43         std::vector<struct kevent> changelist(8);
44 }
45
46 /** Initialize the kqueue engine
47  */
48 void SocketEngine::Init()
49 {
50         MAX_DESCRIPTORS = 0;
51         int mib[2];
52         size_t len;
53
54         mib[0] = CTL_KERN;
55 #ifdef KERN_MAXFILESPERPROC
56         mib[1] = KERN_MAXFILESPERPROC;
57 #else
58         mib[1] = KERN_MAXFILES;
59 #endif
60         len = sizeof(MAX_DESCRIPTORS);
61         sysctl(mib, 2, &MAX_DESCRIPTORS, &len, NULL, 0);
62         if (MAX_DESCRIPTORS <= 0)
63         {
64                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Can't determine maximum number of open sockets!");
65                 std::cout << "ERROR: Can't determine maximum number of open sockets!" << std::endl;
66                 ServerInstance->QuickExit(EXIT_STATUS_SOCKETENGINE);
67         }
68
69         RecoverFromFork();
70 }
71
72 void SocketEngine::RecoverFromFork()
73 {
74         /*
75          * The only bad thing about kqueue is that its fd cant survive a fork and is not inherited.
76          * BUM HATS.
77          *
78          */
79         EngineHandle = kqueue();
80         if (EngineHandle == -1)
81         {
82                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Could not initialize socket engine. Your kernel probably does not have the proper features.");
83                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: this is a fatal error, exiting now.");
84                 std::cout << "ERROR: Could not initialize socket engine. Your kernel probably does not have the proper features." << std::endl;
85                 std::cout << "ERROR: this is a fatal error, exiting now." << std::endl;
86                 ServerInstance->QuickExit(EXIT_STATUS_SOCKETENGINE);
87         }
88 }
89
90 /** Shutdown the kqueue engine
91  */
92 void SocketEngine::Deinit()
93 {
94         Close(EngineHandle);
95 }
96
97 static struct kevent* GetChangeKE()
98 {
99         if (ChangePos >= changelist.size())
100                 changelist.resize(changelist.size() * 2);
101         return &changelist[ChangePos++];
102 }
103
104 bool SocketEngine::AddFd(EventHandler* eh, int event_mask)
105 {
106         int fd = eh->GetFd();
107
108         if (fd < 0)
109                 return false;
110
111         if (!SocketEngine::AddFdRef(eh))
112                 return false;
113
114         // We always want to read from the socket...
115         struct kevent* ke = GetChangeKE();
116         EV_SET(ke, fd, EVFILT_READ, EV_ADD, 0, 0, static_cast<void*>(eh));
117
118         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "New file descriptor: %d", fd);
119
120         eh->SetEventMask(event_mask);
121         OnSetEvent(eh, 0, event_mask);
122         ResizeDouble(ke_list);
123
124         return true;
125 }
126
127 void SocketEngine::DelFd(EventHandler* eh)
128 {
129         int fd = eh->GetFd();
130
131         if (fd < 0)
132         {
133                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "DelFd() on invalid fd: %d", fd);
134                 return;
135         }
136
137         // First remove the write filter ignoring errors, since we can't be
138         // sure if there are actually any write filters registered.
139         struct kevent* ke = GetChangeKE();
140         EV_SET(ke, eh->GetFd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
141
142         // Then remove the read filter.
143         ke = GetChangeKE();
144         EV_SET(ke, eh->GetFd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
145
146         SocketEngine::DelFdRef(eh);
147
148         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Remove file descriptor: %d", fd);
149 }
150
151 void SocketEngine::OnSetEvent(EventHandler* eh, int old_mask, int new_mask)
152 {
153         if ((new_mask & FD_WANT_POLL_WRITE) && !(old_mask & FD_WANT_POLL_WRITE))
154         {
155                 // new poll-style write
156                 struct kevent* ke = GetChangeKE();
157                 EV_SET(ke, eh->GetFd(), EVFILT_WRITE, EV_ADD, 0, 0, static_cast<void*>(eh));
158         }
159         else if ((old_mask & FD_WANT_POLL_WRITE) && !(new_mask & FD_WANT_POLL_WRITE))
160         {
161                 // removing poll-style write
162                 struct kevent* ke = GetChangeKE();
163                 EV_SET(ke, eh->GetFd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
164         }
165         if ((new_mask & (FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)) && !(old_mask & (FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)))
166         {
167                 struct kevent* ke = GetChangeKE();
168                 EV_SET(ke, eh->GetFd(), EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, static_cast<void*>(eh));
169         }
170 }
171
172 int SocketEngine::DispatchEvents()
173 {
174         struct timespec ts;
175         ts.tv_nsec = 0;
176         ts.tv_sec = 1;
177
178         int i = kevent(EngineHandle, &changelist.front(), ChangePos, &ke_list.front(), ke_list.size(), &ts);
179         ChangePos = 0;
180         ServerInstance->UpdateTime();
181
182         if (i < 0)
183                 return i;
184
185         stats.TotalEvents += i;
186
187         for (int j = 0; j < i; j++)
188         {
189                 struct kevent& kev = ke_list[j];
190                 EventHandler* eh = static_cast<EventHandler*>(kev.udata);
191                 if (!eh)
192                         continue;
193
194                 // Copy these in case the vector gets resized and kev invalidated
195                 const int fd = eh->GetFd();
196                 const short filter = kev.filter;
197                 if (fd < 0)
198                         continue;
199
200                 if (kev.flags & EV_EOF)
201                 {
202                         stats.ErrorEvents++;
203                         eh->HandleEvent(EVENT_ERROR, kev.fflags);
204                         continue;
205                 }
206                 if (filter == EVFILT_WRITE)
207                 {
208                         stats.WriteEvents++;
209                         /* When mask is FD_WANT_FAST_WRITE or FD_WANT_SINGLE_WRITE,
210                          * we set a one-shot write, so we need to clear that bit
211                          * to detect when it set again.
212                          */
213                         const int bits_to_clr = FD_WANT_SINGLE_WRITE | FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
214                         eh->SetEventMask(eh->GetEventMask() & ~bits_to_clr);
215                         eh->HandleEvent(EVENT_WRITE);
216                 }
217                 else if (filter == EVFILT_READ)
218                 {
219                         stats.ReadEvents++;
220                         eh->SetEventMask(eh->GetEventMask() & ~FD_READ_WILL_BLOCK);
221                         eh->HandleEvent(EVENT_READ);
222                 }
223         }
224
225         return i;
226 }