]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Fixes for bug #12
[user/henk/code/inspircd.git] / include / socketengine.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 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 "socket.h"
22 #include "base.h"
23
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.
30  */
31 enum EventType
32 {
33         /** Read event */
34         EVENT_READ      =       0,
35         /** Write event */
36         EVENT_WRITE     =       1,
37         /** Error event */
38         EVENT_ERROR     =       2
39 };
40
41 /**
42  * Event mask for SocketEngine events
43  */
44 enum EventMask
45 {
46         /** Do not test this socket for readability
47          */
48         FD_WANT_NO_READ = 0x1,
49         /** Give a read event at all times when reads will not block.
50          */
51         FD_WANT_POLL_READ = 0x2,
52         /** Give a read event when there is new data to read.
53          *
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.
57          */
58         FD_WANT_FAST_READ = 0x4,
59         /** Give an optional read event when reads begin to unblock
60          *
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
64          */
65         FD_WANT_EDGE_READ = 0x8,
66
67         /** Mask for all read events */
68         FD_WANT_READ_MASK = 0x0F,
69
70         /** Do not test this socket for writeability
71          */
72         FD_WANT_NO_WRITE = 0x10,
73         /** Give a write event at all times when writes will not block.
74          *
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.
79          */
80         FD_WANT_POLL_WRITE = 0x20,
81         /** Give a write event when writes don't block any more
82          *
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
86          * block.
87          *
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
93          */
94         FD_WANT_FAST_WRITE = 0x40,
95         /** Give an optional write event on edge-triggered write unblock.
96          *
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.
99          */
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.
103          */
104         FD_WANT_SINGLE_WRITE = 0x100,
105
106         /** Mask for all write events */
107         FD_WANT_WRITE_MASK = 0x1F0,
108
109         /** Add a trial read. During the next DispatchEvents invocation, this
110          * will call HandleEvent with EVENT_READ unless reads are known to be
111          * blocking.
112          */
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
116          */
117         FD_READ_WILL_BLOCK = 0x2000,
118
119         /** Add a trial write. During the next DispatchEvents invocation, this
120          * will call HandleEvent with EVENT_WRITE unless writes are known to be
121          * blocking.
122          * 
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.
126          */
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
130          */
131         FD_WRITE_WILL_BLOCK = 0x8000, 
132
133         /** Mask for trial read/trial write */
134         FD_TRIAL_NOTE_MASK = 0x5000
135 };
136
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.
154  */
155 class CoreExport EventHandler : public classbase
156 {
157  private:
158         /** Private state maintained by socket engine */
159         int event_mask;
160  protected:
161         /** File descriptor.
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
166          */
167         int fd;
168  public:
169         /** Get the current file descriptor
170          * @return The file descriptor of this handler
171          */
172         inline int GetFd() const { return fd; }
173
174         inline int GetEventMask() const { return event_mask; }
175
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.
180          */
181         void SetFd(int FD);
182
183         /** Constructor
184          */
185         EventHandler();
186
187         /** Destructor
188          */
189         virtual ~EventHandler() {}
190
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.
197          */
198         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
199
200         friend class SocketEngine;
201 };
202
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.
220  */
221 class CoreExport SocketEngine
222 {
223  protected:
224         /** Current number of descriptors in the engine
225          */
226         int CurrentSetSize;
227         /** Reference table, contains all current handlers
228          */
229         EventHandler** ref;
230         /** List of handlers that want a trial read/write
231          */
232         std::set<int> trials;
233
234         int MAX_DESCRIPTORS;
235
236         size_t indata;
237         size_t outdata;
238         time_t lastempty;
239
240         void UpdateStats(size_t len_in, size_t len_out);
241
242         virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
243         void SetEventMask(EventHandler* eh, int value);
244 public:
245
246         unsigned long TotalEvents;
247         unsigned long ReadEvents;
248         unsigned long WriteEvents;
249         unsigned long ErrorEvents;
250
251         /** Constructor.
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.
258          */
259         SocketEngine();
260
261         /** Destructor.
262          * The destructor transparently tidies up
263          * any resources used by the socket engine.
264          */
265         virtual ~SocketEngine();
266
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
270          * HandleEvent().
271          * @param eh An event handling object to add
272          * @param event_mask The initial event mask for the object
273          */
274         virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
275
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
283          * CPU time.
284          * @param eh The event handler to change
285          * @param event_mask The changes to make to the wait state
286          */
287         void ChangeEventMask(EventHandler* eh, int event_mask);
288
289         /** Returns the highest file descriptor you may store in the socket engine
290          * @return The maximum fd value
291          */
292         inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
293
294         /** Returns the number of file descriptors being queried
295          * @return The set size
296          */
297         inline int GetUsedFds() const { return CurrentSetSize; }
298
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          * @param eh The event handler object to remove
306          */
307         virtual void DelFd(EventHandler* eh) = 0;
308
309         /** Returns true if a file descriptor exists in
310          * the socket engine's list.
311          * @param fd The event handler to look for
312          * @return True if this fd has an event handler
313          */
314         virtual bool HasFd(int fd);
315
316         /** Returns the EventHandler attached to a specific fd.
317          * If the fd isnt in the socketengine, returns NULL.
318          * @param fd The event handler to look for
319          * @return A pointer to the event handler, or NULL
320          */
321         virtual EventHandler* GetRef(int fd);
322
323         /** Waits for events and dispatches them to handlers.  Please note that
324          * this doesn't wait long, only a couple of milliseconds. It returns the
325          * number of events which occurred during this call.  This method will
326          * dispatch events to their handlers by calling their
327          * EventHandler::HandleEvent() methods with the necessary EventType
328          * value.
329          * @return The number of events which have occured.
330          */
331         virtual int DispatchEvents() = 0;
332
333         /** Dispatch trial reads and writes. This causes the actual socket I/O
334          * to happen when writes have been pre-buffered.
335          */
336         virtual void DispatchTrialWrites();
337
338         /** Returns the socket engines name.  This returns the name of the
339          * engine for use in /VERSION responses.
340          * @return The socket engine name
341          */
342         virtual std::string GetName() = 0;
343
344         /** Returns true if the file descriptors in the given event handler are
345          * within sensible ranges which can be handled by the socket engine.
346          */
347         virtual bool BoundsCheckFd(EventHandler* eh);
348
349         /** Abstraction for BSD sockets accept(2).
350          * This function should emulate its namesake system call exactly.
351          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
352          * @return This method should return exactly the same values as the system call it emulates.
353          */
354         int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
355
356         /** Abstraction for BSD sockets close(2).
357          * This function should emulate its namesake system call exactly.
358          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
359          * @return This method should return exactly the same values as the system call it emulates.
360          */
361         int Close(EventHandler* fd);
362
363         /** Abstraction for BSD sockets close(2).
364          * This function should emulate its namesake system call exactly.
365          * This function should emulate its namesake system call exactly.
366          * @return This method should return exactly the same values as the system call it emulates.
367          */
368         int Close(int fd);
369
370         /** Abstraction for BSD sockets send(2).
371          * This function should emulate its namesake system call exactly.
372          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
373          * @return This method should return exactly the same values as the system call it emulates.
374          */
375         int Send(EventHandler* fd, const void *buf, size_t len, int flags);
376
377         /** Abstraction for BSD sockets recv(2).
378          * This function should emulate its namesake system call exactly.
379          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
380          * @return This method should return exactly the same values as the system call it emulates.
381          */
382         int Recv(EventHandler* fd, void *buf, size_t len, int flags);
383
384         /** Abstraction for BSD sockets recvfrom(2).
385          * This function should emulate its namesake system call exactly.
386          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
387          * @return This method should return exactly the same values as the system call it emulates.
388          */
389         int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
390
391         /** Abstraction for BSD sockets sendto(2).
392          * This function should emulate its namesake system call exactly.
393          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
394          * @return This method should return exactly the same values as the system call it emulates.
395          */
396         int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
397
398         /** Abstraction for BSD sockets connect(2).
399          * This function should emulate its namesake system call exactly.
400          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
401          * @return This method should return exactly the same values as the system call it emulates.
402          */
403         int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
404
405         /** Make a file descriptor blocking.
406          * @param fd a file descriptor to set to blocking mode
407          * @return 0 on success, -1 on failure, errno is set appropriately.
408          */
409         int Blocking(int fd);
410
411         /** Make a file descriptor nonblocking.
412          * @param fd A file descriptor to set to nonblocking mode
413          * @return 0 on success, -1 on failure, errno is set appropriately.
414          */
415         int NonBlocking(int fd);
416
417         /** Abstraction for BSD sockets shutdown(2).
418          * This function should emulate its namesake system call exactly.
419          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
420          * @return This method should return exactly the same values as the system call it emulates.
421          */
422         int Shutdown(EventHandler* fd, int how);
423
424         /** Abstraction for BSD sockets shutdown(2).
425          * This function should emulate its namesake system call exactly.
426          * @return This method should return exactly the same values as the system call it emulates.
427          */
428         int Shutdown(int fd, int how);
429
430         /** Abstraction for BSD sockets bind(2).
431          * This function should emulate its namesake system call exactly.
432          * @return This method should return exactly the same values as the system call it emulates.
433          */
434         int Bind(int fd, const irc::sockets::sockaddrs& addr);
435
436         /** Abstraction for BSD sockets listen(2).
437          * This function should emulate its namesake system call exactly.
438          * @return This method should return exactly the same values as the system call it emulates.
439          */
440         int Listen(int sockfd, int backlog);
441
442         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
443          */
444         void SetReuse(int sockfd);
445
446         /** This function is called immediately after fork().
447          * Some socket engines (notably kqueue) cannot have their
448          * handles inherited by forked processes. This method
449          * allows for the socket engine to re-create its handle
450          * after the daemon forks as the socket engine is created
451          * long BEFORE the daemon forks.
452          * @return void, but it is acceptable for this function to bail back to
453          * the shell or operating system on fatal error.
454          */
455         virtual void RecoverFromFork();
456
457         /** Get data transfer statistics, kilobits per second in and out and total.
458          */
459         void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
460 };
461
462 SocketEngine* CreateSocketEngine();
463
464 #endif
465