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 * EVENT_WRITE for write events and EVENT_ERROR for
207 * @param errornum The error code which goes with an EVENT_ERROR.
209 virtual void HandleEvent(EventType et, int errornum = 0) = 0;
211 friend class SocketEngine;
214 /** Provides basic file-descriptor-based I/O support.
215 * The actual socketengine class presents the
216 * same interface on all operating systems, but
217 * its private members and internal behaviour
218 * should be treated as blackboxed, and vary
219 * from system to system and upon the config
220 * settings chosen by the server admin. The current
221 * version supports select, epoll and kqueue.
222 * The configure script will enable a socket engine
223 * based upon what OS is detected, and will derive
224 * a class from SocketEngine based upon what it finds.
225 * The derived classes file will also implement a
226 * classfactory, SocketEngineFactory, which will
227 * create a derived instance of SocketEngine using
228 * polymorphism so that the core and modules do not
229 * have to be aware of which SocketEngine derived
230 * class they are using.
232 class CoreExport SocketEngine
235 /** Current number of descriptors in the engine
238 /** Reference table, contains all current handlers
241 /** List of handlers that want a trial read/write
243 std::set<int> trials;
251 void UpdateStats(size_t len_in, size_t len_out);
253 virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
254 void SetEventMask(EventHandler* eh, int value);
257 unsigned long TotalEvents;
258 unsigned long ReadEvents;
259 unsigned long WriteEvents;
260 unsigned long ErrorEvents;
263 * The constructor transparently initializes
264 * the socket engine which the ircd is using.
265 * Please note that if there is a catastrophic
266 * failure (for example, you try and enable
267 * epoll on a 2.4 linux kernel) then this
268 * function may bail back to the shell.
273 * The destructor transparently tidies up
274 * any resources used by the socket engine.
276 virtual ~SocketEngine();
278 /** Add an EventHandler object to the engine. Use AddFd to add a file
279 * descriptor to the engine and have the socket engine monitor it. You
280 * must provide an object derived from EventHandler which implements
282 * @param eh An event handling object to add
283 * @param event_mask The initial event mask for the object
285 virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
287 /** If you call this function and pass it an
288 * event handler, that event handler will
289 * receive the next available write event,
290 * even if the socket is a readable socket only.
291 * Developers should avoid constantly keeping
292 * an eventhandler in the writeable state,
293 * as this will consume large amounts of
295 * @param eh The event handler to change
296 * @param event_mask The changes to make to the wait state
298 void ChangeEventMask(EventHandler* eh, int event_mask);
300 /** Returns the highest file descriptor you may store in the socket engine
301 * @return The maximum fd value
303 inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
305 /** Returns the number of file descriptors being queried
306 * @return The set size
308 inline int GetUsedFds() const { return CurrentSetSize; }
310 /** Delete an event handler from the engine.
311 * This function call deletes an EventHandler
312 * from the engine, returning true if it succeeded
313 * and false if it failed. This does not free the
314 * EventHandler pointer using delete, if this is
315 * required you must do this yourself.
316 * @param eh The event handler object to remove
318 virtual void DelFd(EventHandler* eh) = 0;
320 /** Returns true if a file descriptor exists in
321 * the socket engine's list.
322 * @param fd The event handler to look for
323 * @return True if this fd has an event handler
325 virtual bool HasFd(int fd);
327 /** Returns the EventHandler attached to a specific fd.
328 * If the fd isnt in the socketengine, returns NULL.
329 * @param fd The event handler to look for
330 * @return A pointer to the event handler, or NULL
332 virtual EventHandler* GetRef(int fd);
334 /** Waits for events and dispatches them to handlers. Please note that
335 * this doesn't wait long, only a couple of milliseconds. It returns the
336 * number of events which occurred during this call. This method will
337 * dispatch events to their handlers by calling their
338 * EventHandler::HandleEvent() methods with the necessary EventType
340 * @return The number of events which have occured.
342 virtual int DispatchEvents() = 0;
344 /** Dispatch trial reads and writes. This causes the actual socket I/O
345 * to happen when writes have been pre-buffered.
347 virtual void DispatchTrialWrites();
349 /** Returns the socket engines name. This returns the name of the
350 * engine for use in /VERSION responses.
351 * @return The socket engine name
353 virtual std::string GetName() = 0;
355 /** Returns true if the file descriptors in the given event handler are
356 * within sensible ranges which can be handled by the socket engine.
358 virtual bool BoundsCheckFd(EventHandler* eh);
360 /** Abstraction for BSD sockets accept(2).
361 * This function should emulate its namesake system call exactly.
362 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
363 * @param addr The client IP address and port
364 * @param addrlen The size of the sockaddr parameter.
365 * @return This method should return exactly the same values as the system call it emulates.
367 int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
369 /** Abstraction for BSD sockets close(2).
370 * This function should emulate its namesake system call exactly.
371 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
372 * @return This method should return exactly the same values as the system call it emulates.
374 int Close(EventHandler* fd);
376 /** Abstraction for BSD sockets close(2).
377 * This function should emulate its namesake system call exactly.
378 * This function should emulate its namesake system call exactly.
379 * @return This method should return exactly the same values as the system call it emulates.
383 /** Abstraction for BSD sockets send(2).
384 * This function should emulate its namesake system call exactly.
385 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
386 * @param buf The buffer in which the data that is sent is stored.
387 * @param len The size of the buffer.
388 * @param flags A flag value that controls the sending of the data.
389 * @return This method should return exactly the same values as the system call it emulates.
391 int Send(EventHandler* fd, const void *buf, size_t len, int flags);
393 /** Abstraction for BSD sockets recv(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 * @param buf The buffer in which the data that is read is stored.
397 * @param len The size of the buffer.
398 * @param flags A flag value that controls the reception of the data.
399 * @return This method should return exactly the same values as the system call it emulates.
401 int Recv(EventHandler* fd, void *buf, size_t len, int flags);
403 /** Abstraction for BSD sockets recvfrom(2).
404 * This function should emulate its namesake system call exactly.
405 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
406 * @param buf The buffer in which the data that is read is stored.
407 * @param len The size of the buffer.
408 * @param flags A flag value that controls the reception of the data.
409 * @param from The remote IP address and port.
410 * @param fromlen The size of the from parameter.
411 * @return This method should return exactly the same values as the system call it emulates.
413 int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
415 /** Abstraction for BSD sockets sendto(2).
416 * This function should emulate its namesake system call exactly.
417 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
418 * @param buf The buffer in which the data that is sent is stored.
419 * @param len The size of the buffer.
420 * @param flags A flag value that controls the sending of the data.
421 * @param to The remote IP address and port.
422 * @param tolen The size of the to parameter.
423 * @return This method should return exactly the same values as the system call it emulates.
425 int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
427 /** Abstraction for BSD sockets connect(2).
428 * This function should emulate its namesake system call exactly.
429 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
430 * @param serv_addr The server IP address and port.
431 * @param addrlen The size of the sockaddr parameter.
432 * @return This method should return exactly the same values as the system call it emulates.
434 int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
436 /** Make a file descriptor blocking.
437 * @param fd a file descriptor to set to blocking mode
438 * @return 0 on success, -1 on failure, errno is set appropriately.
440 int Blocking(int fd);
442 /** Make a file descriptor nonblocking.
443 * @param fd A file descriptor to set to nonblocking mode
444 * @return 0 on success, -1 on failure, errno is set appropriately.
446 int NonBlocking(int fd);
448 /** Abstraction for BSD sockets shutdown(2).
449 * This function should emulate its namesake system call exactly.
450 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
451 * @param how What part of the socket to shut down
452 * @return This method should return exactly the same values as the system call it emulates.
454 int Shutdown(EventHandler* fd, int how);
456 /** Abstraction for BSD sockets shutdown(2).
457 * This function should emulate its namesake system call exactly.
458 * @return This method should return exactly the same values as the system call it emulates.
460 int Shutdown(int fd, int how);
462 /** Abstraction for BSD sockets bind(2).
463 * This function should emulate its namesake system call exactly.
464 * @return This method should return exactly the same values as the system call it emulates.
466 int Bind(int fd, const irc::sockets::sockaddrs& addr);
468 /** Abstraction for BSD sockets listen(2).
469 * This function should emulate its namesake system call exactly.
470 * @return This method should return exactly the same values as the system call it emulates.
472 int Listen(int sockfd, int backlog);
474 /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
476 void SetReuse(int sockfd);
478 /** This function is called immediately after fork().
479 * Some socket engines (notably kqueue) cannot have their
480 * handles inherited by forked processes. This method
481 * allows for the socket engine to re-create its handle
482 * after the daemon forks as the socket engine is created
483 * long BEFORE the daemon forks.
484 * @return void, but it is acceptable for this function to bail back to
485 * the shell or operating system on fatal error.
487 virtual void RecoverFromFork();
489 /** Get data transfer statistics, kilobits per second in and out and total.
491 void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
494 SocketEngine* CreateSocketEngine();