]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Get rid of OpenTCPSocket
[user/henk/code/inspircd.git] / include / socketengine.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef __SOCKETENGINE__
15 #define __SOCKETENGINE__
16
17 #include <vector>
18 #include <string>
19 #include <map>
20 #include "inspircd_config.h"
21 #include "base.h"
22
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.
29  */
30 enum EventType
31 {
32         /** Read event */
33         EVENT_READ      =       0,
34         /** Write event */
35         EVENT_WRITE     =       1,
36         /** Error event */
37         EVENT_ERROR     =       2
38 };
39
40 /**
41  * Event mask for SocketEngine events
42  */
43 enum EventMask
44 {
45         /** Do not test this socket for readability
46          */
47         FD_WANT_NO_READ = 0x1,
48         /** Give a read event at all times when reads will not block.
49          */
50         FD_WANT_POLL_READ = 0x2,
51         /** Give a read event when there is new data to read.
52          *
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.
56          */
57         FD_WANT_FAST_READ = 0x4,
58         /** Give an optional read event when reads begin to unblock
59          *
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
63          */
64         FD_WANT_EDGE_READ = 0x8,
65
66         /** Mask for all read events */
67         FD_WANT_READ_MASK = 0x0F,
68
69         /** Do not test this socket for writeability
70          */
71         FD_WANT_NO_WRITE = 0x10,
72         /** Give a write event at all times when writes will not block.
73          *
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.
78          */
79         FD_WANT_POLL_WRITE = 0x20,
80         /** Give a write event when writes don't block any more
81          *
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
85          * block.
86          *
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
92          */
93         FD_WANT_FAST_WRITE = 0x40,
94         /** Give an optional write event on edge-triggered write unblock.
95          *
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.
98          */
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.
102          */
103         FD_WANT_SINGLE_WRITE = 0x100,
104
105         /** Mask for all write events */
106         FD_WANT_WRITE_MASK = 0x1F0,
107
108         /** Add a trial read. During the next DispatchEvents invocation, this
109          * will call HandleEvent with EVENT_READ unless reads are known to be
110          * blocking.
111          */
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
115          */
116         FD_READ_WILL_BLOCK = 0x2000,
117
118         /** Add a trial write. During the next DispatchEvents invocation, this
119          * will call HandleEvent with EVENT_WRITE unless writes are known to be
120          * blocking.
121          * 
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.
125          */
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
129          */
130         FD_WRITE_WILL_BLOCK = 0x8000, 
131
132         /** Mask for trial read/trial write */
133         FD_TRIAL_NOTE_MASK = 0x5000
134 };
135
136 class InspIRCd;
137 class Module;
138
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.
156  */
157 class CoreExport EventHandler : public Extensible
158 {
159  private:
160         /** Private state maintained by socket engine */
161         int event_mask;
162  protected:
163         /** File descriptor.
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
168          */
169         int fd;
170  public:
171         /** Get the current file descriptor
172          * @return The file descriptor of this handler
173          */
174         inline int GetFd() const { return fd; }
175
176         inline int GetEventMask() const { return event_mask; }
177
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.
182          */
183         void SetFd(int FD);
184
185         /** Constructor
186          */
187         EventHandler();
188
189         /** Destructor
190          */
191         virtual ~EventHandler() {}
192
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.
199          */
200         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
201
202         friend class SocketEngine;
203 };
204
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.
222  */
223 class CoreExport SocketEngine
224 {
225  protected:
226         /** Current number of descriptors in the engine
227          */
228         int CurrentSetSize;
229         /** Reference table, contains all current handlers
230          */
231         EventHandler** ref;
232         /** List of handlers that want a trial read/write
233          */
234         std::set<int> trials;
235
236         int MAX_DESCRIPTORS;
237
238         size_t indata;
239         size_t outdata;
240         time_t lastempty;
241
242         void UpdateStats(size_t len_in, size_t len_out);
243
244         virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
245         void SetEventMask(EventHandler* eh, int value);
246 public:
247
248         double TotalEvents;
249         double ReadEvents;
250         double WriteEvents;
251         double ErrorEvents;
252
253         /** Constructor.
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.
260          */
261         SocketEngine();
262
263         /** Destructor.
264          * The destructor transparently tidies up
265          * any resources used by the socket engine.
266          */
267         virtual ~SocketEngine();
268
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
272          * HandleEvent().
273          * @param eh An event handling object to add
274          * @param event_mask The initial event mask for the object
275          */
276         virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
277
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
285          * CPU time.
286          * @param eh The event handler to change
287          * @param event_mask The changes to make to the wait state
288          */
289         void ChangeEventMask(EventHandler* eh, int event_mask);
290
291         /** Returns the highest file descriptor you may store in the socket engine
292          * @return The maximum fd value
293          */
294         inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
295
296         /** Returns the number of file descriptors being queried
297          * @return The set size
298          */
299         inline int GetUsedFds() const { return CurrentSetSize; }
300
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
317          */
318         virtual bool DelFd(EventHandler* eh, bool force = false) = 0;
319
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
324          */
325         virtual bool HasFd(int fd);
326
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
331          */
332         virtual EventHandler* GetRef(int fd);
333
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
339          * value.
340          * @return The number of events which have occured.
341          */
342         virtual int DispatchEvents() = 0;
343
344         /** Dispatch trial reads and writes. This causes the actual socket I/O
345          * to happen when writes have been pre-buffered.
346          */
347         virtual void DispatchTrialWrites();
348
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
352          */
353         virtual std::string GetName() = 0;
354
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.
357          */
358         virtual bool BoundsCheckFd(EventHandler* eh);
359
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.
364          */
365         int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
366
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.
371          */
372         int Close(EventHandler* fd);
373
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.
378          */
379         int Close(int fd);
380
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.
385          */
386         int Send(EventHandler* fd, const void *buf, size_t len, int flags);
387
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.
392          */
393         int Recv(EventHandler* fd, void *buf, size_t len, int flags);
394
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.
399          */
400         int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
401
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.
406          */
407         int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
408
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.
413          */
414         int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
415
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.
419          */
420         int Blocking(int fd);
421
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.
425          */
426         int NonBlocking(int fd);
427
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.
432          */
433         int Shutdown(EventHandler* fd, int how);
434
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.
438          */
439         int Shutdown(int fd, int how);
440
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.
444          */
445         int Bind(int fd, const sockaddr *my_addr, socklen_t addrlen);
446
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.
450          */
451         int Listen(int sockfd, int backlog);
452
453         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
454          */
455         void SetReuse(int sockfd);
456
457         /** This function is called immediately after fork().
458          * Some socket engines (notably kqueue) cannot have their
459          * handles inherited by forked processes. This method
460          * allows for the socket engine to re-create its handle
461          * after the daemon forks as the socket engine is created
462          * long BEFORE the daemon forks.
463          * @return void, but it is acceptable for this function to bail back to
464          * the shell or operating system on fatal error.
465          */
466         virtual void RecoverFromFork();
467
468         /** Get data transfer statistics, kilobits per second in and out and total.
469          */
470         void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
471 };
472
473 SocketEngine* CreateSocketEngine();
474
475 #endif
476