2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2005-2007 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #ifndef SOCKETENGINE_H
24 #define SOCKETENGINE_H
29 #include "inspircd_config.h"
33 /** Types of event an EventHandler may receive.
34 * EVENT_READ is a readable file descriptor,
35 * and EVENT_WRITE is a writeable file descriptor.
36 * EVENT_ERROR can always occur, and indicates
37 * a write error or read error on the socket,
38 * e.g. EOF condition or broken pipe.
51 * Event mask for SocketEngine events
55 /** Do not test this socket for readability
57 FD_WANT_NO_READ = 0x1,
58 /** Give a read event at all times when reads will not block.
60 FD_WANT_POLL_READ = 0x2,
61 /** Give a read event when there is new data to read.
63 * An event MUST be sent if there is new data to be read, and the most
64 * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
65 * at any time there is data to be read on the socket.
67 FD_WANT_FAST_READ = 0x4,
68 /** Give an optional read event when reads begin to unblock
70 * This state is useful if you want to leave data in the OS receive
71 * queue but not get continuous event notifications about it, because
72 * it may not require a system call to transition from FD_WANT_FAST_READ
74 FD_WANT_EDGE_READ = 0x8,
76 /** Mask for all read events */
77 FD_WANT_READ_MASK = 0x0F,
79 /** Do not test this socket for writeability
81 FD_WANT_NO_WRITE = 0x10,
82 /** Give a write event at all times when writes will not block.
84 * You probably shouldn't use this state; if it's likely that the write
85 * will not block, try it first, then use FD_WANT_FAST_WRITE if it
86 * fails. If it's likely to block (or you are using polling-style reads)
87 * then use FD_WANT_SINGLE_WRITE.
89 FD_WANT_POLL_WRITE = 0x20,
90 /** Give a write event when writes don't block any more
92 * An event MUST be sent if writes will not block, and the most recent
93 * write/send() on this FD returned EAGAIN, or connect() returned
94 * EINPROGRESS. An event MAY be sent at any time that writes will not
97 * Before calling HandleEvent, a socket engine MAY change the state of
98 * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
99 * one-shot notification was registered). If further writes are needed,
100 * it is the responsibility of the event handler to change the state to
101 * one that will generate the required notifications
103 FD_WANT_FAST_WRITE = 0x40,
104 /** Give an optional write event on edge-triggered write unblock.
106 * This state is useful to avoid system calls when moving to/from
107 * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
109 FD_WANT_EDGE_WRITE = 0x80,
110 /** Request a one-shot poll-style write notification. The socket will
111 * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
113 FD_WANT_SINGLE_WRITE = 0x100,
115 /** Mask for all write events */
116 FD_WANT_WRITE_MASK = 0x1F0,
118 /** Add a trial read. During the next DispatchEvents invocation, this
119 * will call HandleEvent with EVENT_READ unless reads are known to be
122 FD_ADD_TRIAL_READ = 0x1000,
123 /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
124 * Reset by SE before running EVENT_READ
126 FD_READ_WILL_BLOCK = 0x2000,
128 /** Add a trial write. During the next DispatchEvents invocation, this
129 * will call HandleEvent with EVENT_WRITE unless writes are known to be
132 * This could be used to group several writes together into a single
133 * send() syscall, or to ensure that writes are blocking when attempting
134 * to use FD_WANT_FAST_WRITE.
136 FD_ADD_TRIAL_WRITE = 0x4000,
137 /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
138 * Reset by SE before running EVENT_WRITE
140 FD_WRITE_WILL_BLOCK = 0x8000,
142 /** Mask for trial read/trial write */
143 FD_TRIAL_NOTE_MASK = 0x5000
146 /** This class is a basic I/O handler class.
147 * Any object which wishes to receive basic I/O events
148 * from the socketengine must derive from this class and
149 * implement the HandleEvent() method. The derived class
150 * must then be added to SocketEngine using the method
151 * SocketEngine::AddFd(), after which point the derived
152 * class will receive events to its HandleEvent() method.
153 * The derived class should also implement one of Readable()
154 * and Writeable(). In the current implementation, only
155 * Readable() is used. If this returns true, the socketengine
156 * inserts a readable socket. If it is false, the socketengine
157 * inserts a writeable socket. The derived class should never
158 * change the value this function returns without first
159 * deleting the socket from the socket engine. The only
160 * requirement beyond this for an event handler is that it
161 * must have a file descriptor. What this file descriptor
162 * is actually attached to is completely up to you.
164 class CoreExport EventHandler : public classbase
167 /** Private state maintained by socket engine */
171 * All events which can be handled must have a file descriptor. This
172 * allows you to add events for sockets, fifo's, pipes, and various
173 * other forms of IPC. Do not change this while the object is
174 * registered with the SocketEngine
178 /** Get the current file descriptor
179 * @return The file descriptor of this handler
181 inline int GetFd() const { return fd; }
183 inline int GetEventMask() const { return event_mask; }
185 /** Set a new file desciptor
186 * @param FD The new file descriptor. Do not call this method without
187 * first deleting the object from the SocketEngine if you have
188 * added it to a SocketEngine instance.
198 virtual ~EventHandler() {}
200 /** Process an I/O event.
201 * You MUST implement this function in your derived
202 * class, and it will be called whenever read or write
203 * events are received.
204 * @param et either one of EVENT_READ for read events,
205 * and EVENT_WRITE for write events.
207 virtual void HandleEvent(EventType et, int errornum = 0) = 0;
209 friend class SocketEngine;
212 /** Provides basic file-descriptor-based I/O support.
213 * The actual socketengine class presents the
214 * same interface on all operating systems, but
215 * its private members and internal behaviour
216 * should be treated as blackboxed, and vary
217 * from system to system and upon the config
218 * settings chosen by the server admin. The current
219 * version supports select, epoll and kqueue.
220 * The configure script will enable a socket engine
221 * based upon what OS is detected, and will derive
222 * a class from SocketEngine based upon what it finds.
223 * The derived classes file will also implement a
224 * classfactory, SocketEngineFactory, which will
225 * create a derived instance of SocketEngine using
226 * polymorphism so that the core and modules do not
227 * have to be aware of which SocketEngine derived
228 * class they are using.
230 class CoreExport SocketEngine
233 /** Current number of descriptors in the engine
236 /** Reference table, contains all current handlers
239 /** List of handlers that want a trial read/write
241 std::set<int> trials;
249 void UpdateStats(size_t len_in, size_t len_out);
251 virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
252 void SetEventMask(EventHandler* eh, int value);
255 unsigned long TotalEvents;
256 unsigned long ReadEvents;
257 unsigned long WriteEvents;
258 unsigned long ErrorEvents;
261 * The constructor transparently initializes
262 * the socket engine which the ircd is using.
263 * Please note that if there is a catastrophic
264 * failure (for example, you try and enable
265 * epoll on a 2.4 linux kernel) then this
266 * function may bail back to the shell.
271 * The destructor transparently tidies up
272 * any resources used by the socket engine.
274 virtual ~SocketEngine();
276 /** Add an EventHandler object to the engine. Use AddFd to add a file
277 * descriptor to the engine and have the socket engine monitor it. You
278 * must provide an object derived from EventHandler which implements
280 * @param eh An event handling object to add
281 * @param event_mask The initial event mask for the object
283 virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
285 /** If you call this function and pass it an
286 * event handler, that event handler will
287 * receive the next available write event,
288 * even if the socket is a readable socket only.
289 * Developers should avoid constantly keeping
290 * an eventhandler in the writeable state,
291 * as this will consume large amounts of
293 * @param eh The event handler to change
294 * @param event_mask The changes to make to the wait state
296 void ChangeEventMask(EventHandler* eh, int event_mask);
298 /** Returns the highest file descriptor you may store in the socket engine
299 * @return The maximum fd value
301 inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
303 /** Returns the number of file descriptors being queried
304 * @return The set size
306 inline int GetUsedFds() const { return CurrentSetSize; }
308 /** Delete an event handler from the engine.
309 * This function call deletes an EventHandler
310 * from the engine, returning true if it succeeded
311 * and false if it failed. This does not free the
312 * EventHandler pointer using delete, if this is
313 * required you must do this yourself.
314 * @param eh The event handler object to remove
316 virtual void DelFd(EventHandler* eh) = 0;
318 /** Returns true if a file descriptor exists in
319 * the socket engine's list.
320 * @param fd The event handler to look for
321 * @return True if this fd has an event handler
323 virtual bool HasFd(int fd);
325 /** Returns the EventHandler attached to a specific fd.
326 * If the fd isnt in the socketengine, returns NULL.
327 * @param fd The event handler to look for
328 * @return A pointer to the event handler, or NULL
330 virtual EventHandler* GetRef(int fd);
332 /** Waits for events and dispatches them to handlers. Please note that
333 * this doesn't wait long, only a couple of milliseconds. It returns the
334 * number of events which occurred during this call. This method will
335 * dispatch events to their handlers by calling their
336 * EventHandler::HandleEvent() methods with the necessary EventType
338 * @return The number of events which have occured.
340 virtual int DispatchEvents() = 0;
342 /** Dispatch trial reads and writes. This causes the actual socket I/O
343 * to happen when writes have been pre-buffered.
345 virtual void DispatchTrialWrites();
347 /** Returns the socket engines name. This returns the name of the
348 * engine for use in /VERSION responses.
349 * @return The socket engine name
351 virtual std::string GetName() = 0;
353 /** Returns true if the file descriptors in the given event handler are
354 * within sensible ranges which can be handled by the socket engine.
356 virtual bool BoundsCheckFd(EventHandler* eh);
358 /** Abstraction for BSD sockets accept(2).
359 * This function should emulate its namesake system call exactly.
360 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
361 * @return This method should return exactly the same values as the system call it emulates.
363 int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
365 /** Abstraction for BSD sockets close(2).
366 * This function should emulate its namesake system call exactly.
367 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
368 * @return This method should return exactly the same values as the system call it emulates.
370 int Close(EventHandler* fd);
372 /** Abstraction for BSD sockets close(2).
373 * This function should emulate its namesake system call exactly.
374 * This function should emulate its namesake system call exactly.
375 * @return This method should return exactly the same values as the system call it emulates.
379 /** Abstraction for BSD sockets send(2).
380 * This function should emulate its namesake system call exactly.
381 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
382 * @return This method should return exactly the same values as the system call it emulates.
384 int Send(EventHandler* fd, const void *buf, size_t len, int flags);
386 /** Abstraction for BSD sockets recv(2).
387 * This function should emulate its namesake system call exactly.
388 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
389 * @return This method should return exactly the same values as the system call it emulates.
391 int Recv(EventHandler* fd, void *buf, size_t len, int flags);
393 /** Abstraction for BSD sockets recvfrom(2).
394 * This function should emulate its namesake system call exactly.
395 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
396 * @return This method should return exactly the same values as the system call it emulates.
398 int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
400 /** Abstraction for BSD sockets sendto(2).
401 * This function should emulate its namesake system call exactly.
402 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
403 * @return This method should return exactly the same values as the system call it emulates.
405 int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
407 /** Abstraction for BSD sockets connect(2).
408 * This function should emulate its namesake system call exactly.
409 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
410 * @return This method should return exactly the same values as the system call it emulates.
412 int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
414 /** Make a file descriptor blocking.
415 * @param fd a file descriptor to set to blocking mode
416 * @return 0 on success, -1 on failure, errno is set appropriately.
418 int Blocking(int fd);
420 /** Make a file descriptor nonblocking.
421 * @param fd A file descriptor to set to nonblocking mode
422 * @return 0 on success, -1 on failure, errno is set appropriately.
424 int NonBlocking(int fd);
426 /** Abstraction for BSD sockets shutdown(2).
427 * This function should emulate its namesake system call exactly.
428 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
429 * @return This method should return exactly the same values as the system call it emulates.
431 int Shutdown(EventHandler* fd, int how);
433 /** Abstraction for BSD sockets shutdown(2).
434 * This function should emulate its namesake system call exactly.
435 * @return This method should return exactly the same values as the system call it emulates.
437 int Shutdown(int fd, int how);
439 /** Abstraction for BSD sockets bind(2).
440 * This function should emulate its namesake system call exactly.
441 * @return This method should return exactly the same values as the system call it emulates.
443 int Bind(int fd, const irc::sockets::sockaddrs& addr);
445 /** Abstraction for BSD sockets listen(2).
446 * This function should emulate its namesake system call exactly.
447 * @return This method should return exactly the same values as the system call it emulates.
449 int Listen(int sockfd, int backlog);
451 /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
453 void SetReuse(int sockfd);
455 /** This function is called immediately after fork().
456 * Some socket engines (notably kqueue) cannot have their
457 * handles inherited by forked processes. This method
458 * allows for the socket engine to re-create its handle
459 * after the daemon forks as the socket engine is created
460 * long BEFORE the daemon forks.
461 * @return void, but it is acceptable for this function to bail back to
462 * the shell or operating system on fatal error.
464 virtual void RecoverFromFork();
466 /** Get data transfer statistics, kilobits per second in and out and total.
468 void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
471 SocketEngine* CreateSocketEngine();