]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
f16ec3fea045272c8ef99e64c6b261f77f0ba867
[user/henk/code/inspircd.git] / include / socketengine.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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 class InspIRCd;
41
42 /** This class is a basic I/O handler class.
43  * Any object which wishes to receive basic I/O events
44  * from the socketengine must derive from this class and
45  * implement the HandleEvent() method. The derived class
46  * must then be added to SocketEngine using the method
47  * SocketEngine::AddFd(), after which point the derived
48  * class will receive events to its HandleEvent() method.
49  * The derived class should also implement one of Readable()
50  * and Writeable(). In the current implementation, only
51  * Readable() is used. If this returns true, the socketengine
52  * inserts a readable socket. If it is false, the socketengine
53  * inserts a writeable socket. The derived class should never
54  * change the value this function returns without first
55  * deleting the socket from the socket engine. The only
56  * requirement beyond this for an event handler is that it
57  * must have a file descriptor. What this file descriptor
58  * is actually attached to is completely up to you.
59  */
60 class CoreExport EventHandler : public Extensible
61 {
62  protected:
63         /** File descriptor.
64          * All events which can be handled
65          * must have a file descriptor.
66          * This allows you to add events for
67          * sockets, fifo's, pipes, and various
68          * other forms of IPC.
69          */
70         int fd;
71  public:
72
73         /** Get the current file descriptor
74          * @return The file descriptor of this handler
75          */
76         int GetFd();
77
78         /** Set a new file desciptor
79          * @param FD The new file descriptor. Do not
80          * call this method without first deleting the
81          * object from the SocketEngine if you have
82          * added it to a SocketEngine instance.
83          */
84         void SetFd(int FD);
85
86         /** Constructor
87          */
88         EventHandler() {}
89
90         /** Destructor
91          */
92         virtual ~EventHandler() {}
93
94         /** Override this function to indicate readability.
95          * @return This should return true if the function
96          * wishes to receive EVENT_READ events. Do not change
97          * what this function returns while the event handler
98          * is still added to a SocketEngine instance!
99          * If this function is unimplemented, the base class
100          * will return true.
101          *
102          * NOTE: You cannot set both Readable() and
103          * Writeable() to true. If you wish to receive
104          * a write event for your object, you must call
105          * SocketEngine::WantWrite() instead. This will
106          * trigger your objects next EVENT_WRITE type event.
107          */
108         virtual bool Readable();
109
110         /** Override this function to indicate writeability.
111          * @return This should return true if the function
112          * wishes to receive EVENT_WRITE events. Do not change
113          * what this function returns while the event handler
114          * is still added to a SocketEngine instance!
115          * If this function is unimplemented, the base class
116          * will return false.
117          *
118          * NOTE: You cannot set both Readable() and
119          * Writeable() to true. If you wish to receive
120          * a write event for your object, you must call
121          * SocketEngine::WantWrite() instead. This will
122          * trigger your objects next EVENT_WRITE type event.
123          */
124         virtual bool Writeable();
125
126         /** Process an I/O event.
127          * You MUST implement this function in your derived
128          * class, and it will be called whenever read or write
129          * events are received, depending on what your functions
130          * Readable() and Writeable() returns and wether you
131          * previously made a call to SocketEngine::WantWrite().
132          * @param et either one of EVENT_READ for read events,
133          * and EVENT_WRITE for write events.
134          */
135         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
136 };
137
138 /** Provides basic file-descriptor-based I/O support.
139  * The actual socketengine class presents the
140  * same interface on all operating systems, but
141  * its private members and internal behaviour
142  * should be treated as blackboxed, and vary
143  * from system to system and upon the config
144  * settings chosen by the server admin. The current
145  * version supports select, epoll and kqueue.
146  * The configure script will enable a socket engine
147  * based upon what OS is detected, and will derive
148  * a class from SocketEngine based upon what it finds.
149  * The derived classes file will also implement a
150  * classfactory, SocketEngineFactory, which will
151  * create a derived instance of SocketEngine using
152  * polymorphism so that the core and modules do not
153  * have to be aware of which SocketEngine derived
154  * class they are using.
155  */
156 class CoreExport SocketEngine : public Extensible
157 {
158 protected:
159         /** Owner/Creator
160          */
161         InspIRCd* ServerInstance;
162         /** Handle to socket engine, where needed.
163          */
164         int EngineHandle;
165         /** Current number of descriptors in the engine
166          */
167         int CurrentSetSize;
168         /** Reference table, contains all current handlers
169          */
170         EventHandler** ref;
171
172         int MAX_DESCRIPTORS;
173
174         size_t indata;
175         size_t outdata;
176         time_t lastempty;
177
178         void UpdateStats(size_t len_in, size_t len_out);
179 public:
180
181         double TotalEvents;
182         double ReadEvents;
183         double WriteEvents;
184         double ErrorEvents;
185
186         /** Constructor.
187          * The constructor transparently initializes
188          * the socket engine which the ircd is using.
189          * Please note that if there is a catastrophic
190          * failure (for example, you try and enable
191          * epoll on a 2.4 linux kernel) then this
192          * function may bail back to the shell.
193          * @param Instance The creator/owner of this object
194          */
195         SocketEngine(InspIRCd* Instance);
196
197         /** Destructor.
198          * The destructor transparently tidies up
199          * any resources used by the socket engine.
200          */
201         virtual ~SocketEngine();
202
203         /** Add an EventHandler object to the engine.
204          * Use AddFd to add a file descriptor to the
205          * engine and have the socket engine monitor
206          * it. You must provide an object derived from
207          * EventHandler which implements HandleEvent()
208          * and optionally Readable() and Writeable().
209          * @param eh An event handling object to add
210          */
211         virtual bool AddFd(EventHandler* eh);
212
213         /** If you call this function and pass it an
214          * event handler, that event handler will
215          * receive the next available write event,
216          * even if the socket is a readable socket only.
217          * Developers should avoid constantly keeping
218          * an eventhandler in the writeable state,
219          * as this will consume large amounts of
220          * CPU time.
221          * @param eh An event handler which wants to
222          * receive the next writeability event.
223          */
224         virtual void WantWrite(EventHandler* eh);
225
226         /** Returns the maximum number of file descriptors
227          * you may store in the socket engine at any one time.
228          * @return The maximum fd value
229          */
230         virtual int GetMaxFds();
231
232         /** Returns the number of file descriptor slots
233          * which are available for storing fds.
234          * @return The number of remaining fd's
235          */
236         virtual int GetRemainingFds();
237
238         /** Delete an event handler from the engine.
239          * This function call deletes an EventHandler
240          * from the engine, returning true if it succeeded
241          * and false if it failed. This does not free the
242          * EventHandler pointer using delete, if this is
243          * required you must do this yourself.
244          * Note on forcing deletes. DO NOT DO THIS! This is
245          * extremely dangerous and will most likely render the
246          * socketengine dead. This was added only for handling
247          * very rare cases where broken 3rd party libs destroys
248          * the OS socket beyond our control. If you can't explain
249          * in minute details why forcing is absolutely necessary
250          * then you don't need it. That was a NO!
251          * @param eh The event handler object to remove
252          * @param force *DANGEROUS* See method description!
253          * @return True if the event handler was removed
254          */
255         virtual bool DelFd(EventHandler* eh, bool force = false);
256
257         /** Returns true if a file descriptor exists in
258          * the socket engine's list.
259          * @param fd The event handler to look for
260          * @return True if this fd has an event handler
261          */
262         virtual bool HasFd(int fd);
263
264         /** Returns the EventHandler attached to a specific fd.
265          * If the fd isnt in the socketengine, returns NULL.
266          * @param fd The event handler to look for
267          * @return A pointer to the event handler, or NULL
268          */
269         virtual EventHandler* GetRef(int fd);
270
271         /** Waits for events and dispatches them to handlers.
272          * Please note that this doesnt wait long, only
273          * a couple of milliseconds. It returns the number of
274          * events which occured during this call.
275          * This method will dispatch events to their handlers
276          * by calling their EventHandler::HandleEvent()
277          * methods with the neccessary EventType value.
278          * @return The number of events which have occured.
279          */
280         virtual int DispatchEvents();
281
282         /** Returns the socket engines name.
283          * This returns the name of the engine for use
284          * in /VERSION responses.
285          * @return The socket engine name
286          */
287         virtual std::string GetName();
288
289         /** Returns true if the file descriptors in the
290          * given event handler are within sensible ranges
291          * which can be handled by the socket engine.
292          */
293         virtual bool BoundsCheckFd(EventHandler* eh);
294
295         /** Abstraction for BSD sockets accept(2).
296          * This function should emulate its namesake system call exactly.
297          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
298          * @return This method should return exactly the same values as the system call it emulates.
299          */
300         virtual int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
301
302         /** Abstraction for BSD sockets close(2).
303          * This function should emulate its namesake system call exactly.
304          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
305          * @return This method should return exactly the same values as the system call it emulates.
306          */
307         virtual int Close(EventHandler* fd);
308
309         /** Abstraction for BSD sockets close(2).
310          * This function should emulate its namesake system call exactly.
311          * This function should emulate its namesake system call exactly.
312          * @return This method should return exactly the same values as the system call it emulates.
313          */
314         virtual int Close(int fd);
315
316         /** Abstraction for BSD sockets send(2).
317          * This function should emulate its namesake system call exactly.
318          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
319          * @return This method should return exactly the same values as the system call it emulates.
320          */
321         virtual int Send(EventHandler* fd, const void *buf, size_t len, int flags);
322
323         /** Abstraction for BSD sockets recv(2).
324          * This function should emulate its namesake system call exactly.
325          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
326          * @return This method should return exactly the same values as the system call it emulates.
327          */
328         virtual int Recv(EventHandler* fd, void *buf, size_t len, int flags);
329
330         /** Abstraction for BSD sockets recvfrom(2).
331          * This function should emulate its namesake system call exactly.
332          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
333          * @return This method should return exactly the same values as the system call it emulates.
334          */
335         virtual int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
336
337         /** Abstraction for BSD sockets sendto(2).
338          * This function should emulate its namesake system call exactly.
339          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
340          * @return This method should return exactly the same values as the system call it emulates.
341          */
342         virtual int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
343
344         /** Abstraction for BSD sockets connect(2).
345          * This function should emulate its namesake system call exactly.
346          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
347          * @return This method should return exactly the same values as the system call it emulates.
348          */
349         virtual int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
350
351         /** Make a file descriptor blocking.
352          * @param fd a file descriptor to set to blocking mode
353          * @return 0 on success, -1 on failure, errno is set appropriately.
354          */
355         virtual int Blocking(int fd);
356
357         /** Make a file descriptor nonblocking.
358          * @param fd A file descriptor to set to nonblocking mode
359          * @return 0 on success, -1 on failure, errno is set appropriately.
360          */
361         virtual int NonBlocking(int fd);
362
363         /** Abstraction for BSD sockets shutdown(2).
364          * This function should emulate its namesake system call exactly.
365          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
366          * @return This method should return exactly the same values as the system call it emulates.
367          */
368         virtual int Shutdown(EventHandler* fd, int how);
369
370         /** Abstraction for BSD sockets shutdown(2).
371          * This function should emulate its namesake system call exactly.
372          * @return This method should return exactly the same values as the system call it emulates.
373          */
374         virtual int Shutdown(int fd, int how);
375
376         /** Abstraction for BSD sockets bind(2).
377          * This function should emulate its namesake system call exactly.
378          * @return This method should return exactly the same values as the system call it emulates.
379          */
380         virtual int Bind(int fd, const sockaddr *my_addr, socklen_t addrlen);
381
382         /** Abstraction for BSD sockets listen(2).
383          * This function should emulate its namesake system call exactly.
384          * @return This method should return exactly the same values as the system call it emulates.
385          */
386         virtual int Listen(int sockfd, int backlog);
387
388         /** Abstraction for BSD sockets getsockname(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         virtual int GetSockName(EventHandler* fd, sockaddr *name, socklen_t* namelen);
394
395         /** This function is called immediately after fork().
396          * Some socket engines (notably kqueue) cannot have their
397          * handles inherited by forked processes. This method
398          * allows for the socket engine to re-create its handle
399          * after the daemon forks as the socket engine is created
400          * long BEFORE the daemon forks.
401          * @return void, but it is acceptable for this function to bail back to
402          * the shell or operating system on fatal error.
403          */
404         virtual void RecoverFromFork();
405
406         /** Get data transfer statistics, kilobits per second in and out and total.
407          */
408         void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
409 };
410
411 #endif
412