1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #ifndef __SOCKETENGINE__
15 #define __SOCKETENGINE__
20 #include "inspircd_config.h"
23 /** Types of event an EventHandler may receive.
24 * EVENT_READ is a readable file descriptor,
25 * and EVENT_WRITE is a writeable file descriptor.
26 * EVENT_ERROR can always occur, and indicates
27 * a write error or read error on the socket,
28 * e.g. EOF condition or broken pipe.
41 * Event mask for SocketEngine events
45 /** Do not test this socket for readability
47 FD_WANT_NO_READ = 0x1,
48 /** Give a read event at all times when reads will not block.
50 FD_WANT_POLL_READ = 0x2,
51 /** Give a read event when there is new data to read.
53 * An event MUST be sent if there is new data to be read, and the most
54 * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
55 * at any time there is data to be read on the socket.
57 FD_WANT_FAST_READ = 0x4,
58 /** Give an optional read event when reads begin to unblock
60 * This state is useful if you want to leave data in the OS receive
61 * queue but not get continuous event notifications about it, because
62 * it may not require a system call to transition from FD_WANT_FAST_READ
64 FD_WANT_EDGE_READ = 0x8,
66 /** Mask for all read events */
67 FD_WANT_READ_MASK = 0x0F,
69 /** Do not test this socket for writeability
71 FD_WANT_NO_WRITE = 0x10,
72 /** Give a write event at all times when writes will not block.
74 * You probably shouldn't use this state; if it's likely that the write
75 * will not block, try it first, then use FD_WANT_FAST_WRITE if it
76 * fails. If it's likely to block (or you are using polling-style reads)
77 * then use FD_WANT_SINGLE_WRITE.
79 FD_WANT_POLL_WRITE = 0x20,
80 /** Give a write event when writes don't block any more
82 * An event MUST be sent if writes will not block, and the most recent
83 * write/send() on this FD returned EAGAIN, or connect() returned
84 * EINPROGRESS. An event MAY be sent at any time that writes will not
87 * Before calling HandleEvent, a socket engine MAY change the state of
88 * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
89 * one-shot notification was registered). If further writes are needed,
90 * it is the responsibility of the event handler to change the state to
91 * one that will generate the required notifications
93 FD_WANT_FAST_WRITE = 0x40,
94 /** Give an optional write event on edge-triggered write unblock.
96 * This state is useful to avoid system calls when moving to/from
97 * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
99 FD_WANT_EDGE_WRITE = 0x80,
100 /** Request a one-shot poll-style write notification. The socket will
101 * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
103 FD_WANT_SINGLE_WRITE = 0x100,
105 /** Mask for all write events */
106 FD_WANT_WRITE_MASK = 0x1F0,
108 /** Add a trial read. During the next DispatchEvents invocation, this
109 * will call HandleEvent with EVENT_READ unless reads are known to be
112 FD_ADD_TRIAL_READ = 0x1000,
113 /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
114 * Reset by SE before running EVENT_READ
116 FD_READ_WILL_BLOCK = 0x2000,
118 /** Add a trial write. During the next DispatchEvents invocation, this
119 * will call HandleEvent with EVENT_WRITE unless writes are known to be
122 * This could be used to group several writes together into a single
123 * send() syscall, or to ensure that writes are blocking when attempting
124 * to use FD_WANT_FAST_WRITE.
126 FD_ADD_TRIAL_WRITE = 0x4000,
127 /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
128 * Reset by SE before running EVENT_WRITE
130 FD_WRITE_WILL_BLOCK = 0x8000,
132 /** Mask for trial read/trial write */
133 FD_TRIAL_NOTE_MASK = 0x5000
139 /** This class is a basic I/O handler class.
140 * Any object which wishes to receive basic I/O events
141 * from the socketengine must derive from this class and
142 * implement the HandleEvent() method. The derived class
143 * must then be added to SocketEngine using the method
144 * SocketEngine::AddFd(), after which point the derived
145 * class will receive events to its HandleEvent() method.
146 * The derived class should also implement one of Readable()
147 * and Writeable(). In the current implementation, only
148 * Readable() is used. If this returns true, the socketengine
149 * inserts a readable socket. If it is false, the socketengine
150 * inserts a writeable socket. The derived class should never
151 * change the value this function returns without first
152 * deleting the socket from the socket engine. The only
153 * requirement beyond this for an event handler is that it
154 * must have a file descriptor. What this file descriptor
155 * is actually attached to is completely up to you.
157 class CoreExport EventHandler : public Extensible
160 /** Private state maintained by socket engine */
164 * All events which can be handled must have a file descriptor. This
165 * allows you to add events for sockets, fifo's, pipes, and various
166 * other forms of IPC. Do not change this while the object is
167 * registered with the SocketEngine
171 /** Get the current file descriptor
172 * @return The file descriptor of this handler
174 inline int GetFd() const { return fd; }
176 inline int GetEventMask() const { return event_mask; }
178 /** Set a new file desciptor
179 * @param FD The new file descriptor. Do not call this method without
180 * first deleting the object from the SocketEngine if you have
181 * added it to a SocketEngine instance.
191 virtual ~EventHandler() {}
193 /** Process an I/O event.
194 * You MUST implement this function in your derived
195 * class, and it will be called whenever read or write
196 * events are received.
197 * @param et either one of EVENT_READ for read events,
198 * and EVENT_WRITE for write events.
200 virtual void HandleEvent(EventType et, int errornum = 0) = 0;
202 friend class SocketEngine;
205 /** Provides basic file-descriptor-based I/O support.
206 * The actual socketengine class presents the
207 * same interface on all operating systems, but
208 * its private members and internal behaviour
209 * should be treated as blackboxed, and vary
210 * from system to system and upon the config
211 * settings chosen by the server admin. The current
212 * version supports select, epoll and kqueue.
213 * The configure script will enable a socket engine
214 * based upon what OS is detected, and will derive
215 * a class from SocketEngine based upon what it finds.
216 * The derived classes file will also implement a
217 * classfactory, SocketEngineFactory, which will
218 * create a derived instance of SocketEngine using
219 * polymorphism so that the core and modules do not
220 * have to be aware of which SocketEngine derived
221 * class they are using.
223 class CoreExport SocketEngine
226 /** Current number of descriptors in the engine
229 /** Reference table, contains all current handlers
232 /** List of handlers that want a trial read/write
234 std::set<int> trials;
242 void UpdateStats(size_t len_in, size_t len_out);
244 virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
245 void SetEventMask(EventHandler* eh, int value);
254 * The constructor transparently initializes
255 * the socket engine which the ircd is using.
256 * Please note that if there is a catastrophic
257 * failure (for example, you try and enable
258 * epoll on a 2.4 linux kernel) then this
259 * function may bail back to the shell.
264 * The destructor transparently tidies up
265 * any resources used by the socket engine.
267 virtual ~SocketEngine();
269 /** Add an EventHandler object to the engine. Use AddFd to add a file
270 * descriptor to the engine and have the socket engine monitor it. You
271 * must provide an object derived from EventHandler which implements
273 * @param eh An event handling object to add
274 * @param event_mask The initial event mask for the object
276 virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
278 /** If you call this function and pass it an
279 * event handler, that event handler will
280 * receive the next available write event,
281 * even if the socket is a readable socket only.
282 * Developers should avoid constantly keeping
283 * an eventhandler in the writeable state,
284 * as this will consume large amounts of
286 * @param eh The event handler to change
287 * @param event_mask The changes to make to the wait state
289 void ChangeEventMask(EventHandler* eh, int event_mask);
291 /** Returns the highest file descriptor you may store in the socket engine
292 * @return The maximum fd value
294 inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
296 /** Returns the number of file descriptors being queried
297 * @return The set size
299 inline int GetUsedFds() const { return CurrentSetSize; }
301 /** Delete an event handler from the engine.
302 * This function call deletes an EventHandler
303 * from the engine, returning true if it succeeded
304 * and false if it failed. This does not free the
305 * EventHandler pointer using delete, if this is
306 * required you must do this yourself.
307 * Note on forcing deletes. DO NOT DO THIS! This is
308 * extremely dangerous and will most likely render the
309 * socketengine dead. This was added only for handling
310 * very rare cases where broken 3rd party libs destroys
311 * the OS socket beyond our control. If you can't explain
312 * in minute details why forcing is absolutely necessary
313 * then you don't need it. That was a NO!
314 * @param eh The event handler object to remove
315 * @param force *DANGEROUS* See method description!
316 * @return True if the event handler was removed
318 virtual bool DelFd(EventHandler* eh, bool force = false) = 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 * @return This method should return exactly the same values as the system call it emulates.
365 virtual int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
367 /** Abstraction for BSD sockets close(2).
368 * This function should emulate its namesake system call exactly.
369 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
370 * @return This method should return exactly the same values as the system call it emulates.
372 virtual int Close(EventHandler* fd);
374 /** Abstraction for BSD sockets close(2).
375 * This function should emulate its namesake system call exactly.
376 * This function should emulate its namesake system call exactly.
377 * @return This method should return exactly the same values as the system call it emulates.
379 virtual int Close(int fd);
381 /** Abstraction for BSD sockets send(2).
382 * This function should emulate its namesake system call exactly.
383 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
384 * @return This method should return exactly the same values as the system call it emulates.
386 virtual int Send(EventHandler* fd, const void *buf, size_t len, int flags);
388 /** Abstraction for BSD sockets recv(2).
389 * This function should emulate its namesake system call exactly.
390 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
391 * @return This method should return exactly the same values as the system call it emulates.
393 virtual int Recv(EventHandler* fd, void *buf, size_t len, int flags);
395 /** Abstraction for BSD sockets recvfrom(2).
396 * This function should emulate its namesake system call exactly.
397 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
398 * @return This method should return exactly the same values as the system call it emulates.
400 virtual int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
402 /** Abstraction for BSD sockets sendto(2).
403 * This function should emulate its namesake system call exactly.
404 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
405 * @return This method should return exactly the same values as the system call it emulates.
407 virtual int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
409 /** Abstraction for BSD sockets connect(2).
410 * This function should emulate its namesake system call exactly.
411 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
412 * @return This method should return exactly the same values as the system call it emulates.
414 virtual int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
416 /** Make a file descriptor blocking.
417 * @param fd a file descriptor to set to blocking mode
418 * @return 0 on success, -1 on failure, errno is set appropriately.
420 virtual int Blocking(int fd);
422 /** Make a file descriptor nonblocking.
423 * @param fd A file descriptor to set to nonblocking mode
424 * @return 0 on success, -1 on failure, errno is set appropriately.
426 virtual int NonBlocking(int fd);
428 /** Abstraction for BSD sockets shutdown(2).
429 * This function should emulate its namesake system call exactly.
430 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
431 * @return This method should return exactly the same values as the system call it emulates.
433 virtual int Shutdown(EventHandler* fd, int how);
435 /** Abstraction for BSD sockets shutdown(2).
436 * This function should emulate its namesake system call exactly.
437 * @return This method should return exactly the same values as the system call it emulates.
439 virtual int Shutdown(int fd, int how);
441 /** Abstraction for BSD sockets bind(2).
442 * This function should emulate its namesake system call exactly.
443 * @return This method should return exactly the same values as the system call it emulates.
445 virtual int Bind(int fd, const sockaddr *my_addr, socklen_t addrlen);
447 /** Abstraction for BSD sockets listen(2).
448 * This function should emulate its namesake system call exactly.
449 * @return This method should return exactly the same values as the system call it emulates.
451 virtual int Listen(int sockfd, int backlog);
453 /** Abstraction for BSD sockets getsockname(2).
454 * This function should emulate its namesake system call exactly.
455 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
456 * @return This method should return exactly the same values as the system call it emulates.
458 virtual int GetSockName(EventHandler* fd, sockaddr *name, socklen_t* namelen);
460 /** This function is called immediately after fork().
461 * Some socket engines (notably kqueue) cannot have their
462 * handles inherited by forked processes. This method
463 * allows for the socket engine to re-create its handle
464 * after the daemon forks as the socket engine is created
465 * long BEFORE the daemon forks.
466 * @return void, but it is acceptable for this function to bail back to
467 * the shell or operating system on fatal error.
469 virtual void RecoverFromFork();
471 /** Get data transfer statistics, kilobits per second in and out and total.
473 void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
476 SocketEngine* CreateSocketEngine();