1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 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"
24 /** Types of event an EventHandler may receive.
25 * EVENT_READ is a readable file descriptor,
26 * and EVENT_WRITE is a writeable file descriptor.
27 * EVENT_ERROR can always occur, and indicates
28 * a write error or read error on the socket,
29 * e.g. EOF condition or broken pipe.
42 * Event mask for SocketEngine events
46 /** Do not test this socket for readability
48 FD_WANT_NO_READ = 0x1,
49 /** Give a read event at all times when reads will not block.
51 FD_WANT_POLL_READ = 0x2,
52 /** Give a read event when there is new data to read.
54 * An event MUST be sent if there is new data to be read, and the most
55 * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
56 * at any time there is data to be read on the socket.
58 FD_WANT_FAST_READ = 0x4,
59 /** Give an optional read event when reads begin to unblock
61 * This state is useful if you want to leave data in the OS receive
62 * queue but not get continuous event notifications about it, because
63 * it may not require a system call to transition from FD_WANT_FAST_READ
65 FD_WANT_EDGE_READ = 0x8,
67 /** Mask for all read events */
68 FD_WANT_READ_MASK = 0x0F,
70 /** Do not test this socket for writeability
72 FD_WANT_NO_WRITE = 0x10,
73 /** Give a write event at all times when writes will not block.
75 * You probably shouldn't use this state; if it's likely that the write
76 * will not block, try it first, then use FD_WANT_FAST_WRITE if it
77 * fails. If it's likely to block (or you are using polling-style reads)
78 * then use FD_WANT_SINGLE_WRITE.
80 FD_WANT_POLL_WRITE = 0x20,
81 /** Give a write event when writes don't block any more
83 * An event MUST be sent if writes will not block, and the most recent
84 * write/send() on this FD returned EAGAIN, or connect() returned
85 * EINPROGRESS. An event MAY be sent at any time that writes will not
88 * Before calling HandleEvent, a socket engine MAY change the state of
89 * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
90 * one-shot notification was registered). If further writes are needed,
91 * it is the responsibility of the event handler to change the state to
92 * one that will generate the required notifications
94 FD_WANT_FAST_WRITE = 0x40,
95 /** Give an optional write event on edge-triggered write unblock.
97 * This state is useful to avoid system calls when moving to/from
98 * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
100 FD_WANT_EDGE_WRITE = 0x80,
101 /** Request a one-shot poll-style write notification. The socket will
102 * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
104 FD_WANT_SINGLE_WRITE = 0x100,
106 /** Mask for all write events */
107 FD_WANT_WRITE_MASK = 0x1F0,
109 /** Add a trial read. During the next DispatchEvents invocation, this
110 * will call HandleEvent with EVENT_READ unless reads are known to be
113 FD_ADD_TRIAL_READ = 0x1000,
114 /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
115 * Reset by SE before running EVENT_READ
117 FD_READ_WILL_BLOCK = 0x2000,
119 /** Add a trial write. During the next DispatchEvents invocation, this
120 * will call HandleEvent with EVENT_WRITE unless writes are known to be
123 * This could be used to group several writes together into a single
124 * send() syscall, or to ensure that writes are blocking when attempting
125 * to use FD_WANT_FAST_WRITE.
127 FD_ADD_TRIAL_WRITE = 0x4000,
128 /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
129 * Reset by SE before running EVENT_WRITE
131 FD_WRITE_WILL_BLOCK = 0x8000,
133 /** Mask for trial read/trial write */
134 FD_TRIAL_NOTE_MASK = 0x5000
137 /** This class is a basic I/O handler class.
138 * Any object which wishes to receive basic I/O events
139 * from the socketengine must derive from this class and
140 * implement the HandleEvent() method. The derived class
141 * must then be added to SocketEngine using the method
142 * SocketEngine::AddFd(), after which point the derived
143 * class will receive events to its HandleEvent() method.
144 * The derived class should also implement one of Readable()
145 * and Writeable(). In the current implementation, only
146 * Readable() is used. If this returns true, the socketengine
147 * inserts a readable socket. If it is false, the socketengine
148 * inserts a writeable socket. The derived class should never
149 * change the value this function returns without first
150 * deleting the socket from the socket engine. The only
151 * requirement beyond this for an event handler is that it
152 * must have a file descriptor. What this file descriptor
153 * is actually attached to is completely up to you.
155 class CoreExport EventHandler : public classbase
158 /** Private state maintained by socket engine */
162 * All events which can be handled must have a file descriptor. This
163 * allows you to add events for sockets, fifo's, pipes, and various
164 * other forms of IPC. Do not change this while the object is
165 * registered with the SocketEngine
169 /** Get the current file descriptor
170 * @return The file descriptor of this handler
172 inline int GetFd() const { return fd; }
174 inline int GetEventMask() const { return event_mask; }
176 /** Set a new file desciptor
177 * @param FD The new file descriptor. Do not call this method without
178 * first deleting the object from the SocketEngine if you have
179 * added it to a SocketEngine instance.
189 virtual ~EventHandler() {}
191 /** Process an I/O event.
192 * You MUST implement this function in your derived
193 * class, and it will be called whenever read or write
194 * events are received.
195 * @param et either one of EVENT_READ for read events,
196 * and EVENT_WRITE for write events.
198 virtual void HandleEvent(EventType et, int errornum = 0) = 0;
200 friend class SocketEngine;
203 /** Provides basic file-descriptor-based I/O support.
204 * The actual socketengine class presents the
205 * same interface on all operating systems, but
206 * its private members and internal behaviour
207 * should be treated as blackboxed, and vary
208 * from system to system and upon the config
209 * settings chosen by the server admin. The current
210 * version supports select, epoll and kqueue.
211 * The configure script will enable a socket engine
212 * based upon what OS is detected, and will derive
213 * a class from SocketEngine based upon what it finds.
214 * The derived classes file will also implement a
215 * classfactory, SocketEngineFactory, which will
216 * create a derived instance of SocketEngine using
217 * polymorphism so that the core and modules do not
218 * have to be aware of which SocketEngine derived
219 * class they are using.
221 class CoreExport SocketEngine
224 /** Current number of descriptors in the engine
227 /** Reference table, contains all current handlers
230 /** List of handlers that want a trial read/write
232 std::set<int> trials;
240 void UpdateStats(size_t len_in, size_t len_out);
242 virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
243 void SetEventMask(EventHandler* eh, int value);
252 * The constructor transparently initializes
253 * the socket engine which the ircd is using.
254 * Please note that if there is a catastrophic
255 * failure (for example, you try and enable
256 * epoll on a 2.4 linux kernel) then this
257 * function may bail back to the shell.
262 * The destructor transparently tidies up
263 * any resources used by the socket engine.
265 virtual ~SocketEngine();
267 /** Add an EventHandler object to the engine. Use AddFd to add a file
268 * descriptor to the engine and have the socket engine monitor it. You
269 * must provide an object derived from EventHandler which implements
271 * @param eh An event handling object to add
272 * @param event_mask The initial event mask for the object
274 virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
276 /** If you call this function and pass it an
277 * event handler, that event handler will
278 * receive the next available write event,
279 * even if the socket is a readable socket only.
280 * Developers should avoid constantly keeping
281 * an eventhandler in the writeable state,
282 * as this will consume large amounts of
284 * @param eh The event handler to change
285 * @param event_mask The changes to make to the wait state
287 void ChangeEventMask(EventHandler* eh, int event_mask);
289 /** Returns the highest file descriptor you may store in the socket engine
290 * @return The maximum fd value
292 inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
294 /** Returns the number of file descriptors being queried
295 * @return The set size
297 inline int GetUsedFds() const { return CurrentSetSize; }
299 /** Delete an event handler from the engine.
300 * This function call deletes an EventHandler
301 * from the engine, returning true if it succeeded
302 * and false if it failed. This does not free the
303 * EventHandler pointer using delete, if this is
304 * required you must do this yourself.
305 * Note on forcing deletes. DO NOT DO THIS! This is
306 * extremely dangerous and will most likely render the
307 * socketengine dead. This was added only for handling
308 * very rare cases where broken 3rd party libs destroys
309 * the OS socket beyond our control. If you can't explain
310 * in minute details why forcing is absolutely necessary
311 * then you don't need it. That was a NO!
312 * @param eh The event handler object to remove
313 * @param force *DANGEROUS* See method description!
314 * @return True if the event handler was removed
316 virtual bool DelFd(EventHandler* eh, bool force = false) = 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();