]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Replace copyright headers with headers granting specific authors copyright
[user/henk/code/inspircd.git] / include / socketengine.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2005-2007 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22
23 #ifndef SOCKETENGINE_H
24 #define SOCKETENGINE_H
25
26 #include <vector>
27 #include <string>
28 #include <map>
29 #include "inspircd_config.h"
30 #include "socket.h"
31 #include "base.h"
32
33 /** Types of event an EventHandler may receive.
34  * EVENT_READ is a readable file descriptor,
35  * and EVENT_WRITE is a writeable file descriptor.
36  * EVENT_ERROR can always occur, and indicates
37  * a write error or read error on the socket,
38  * e.g. EOF condition or broken pipe.
39  */
40 enum EventType
41 {
42         /** Read event */
43         EVENT_READ      =       0,
44         /** Write event */
45         EVENT_WRITE     =       1,
46         /** Error event */
47         EVENT_ERROR     =       2
48 };
49
50 /**
51  * Event mask for SocketEngine events
52  */
53 enum EventMask
54 {
55         /** Do not test this socket for readability
56          */
57         FD_WANT_NO_READ = 0x1,
58         /** Give a read event at all times when reads will not block.
59          */
60         FD_WANT_POLL_READ = 0x2,
61         /** Give a read event when there is new data to read.
62          *
63          * An event MUST be sent if there is new data to be read, and the most
64          * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
65          * at any time there is data to be read on the socket.
66          */
67         FD_WANT_FAST_READ = 0x4,
68         /** Give an optional read event when reads begin to unblock
69          *
70          * This state is useful if you want to leave data in the OS receive
71          * queue but not get continuous event notifications about it, because
72          * it may not require a system call to transition from FD_WANT_FAST_READ
73          */
74         FD_WANT_EDGE_READ = 0x8,
75
76         /** Mask for all read events */
77         FD_WANT_READ_MASK = 0x0F,
78
79         /** Do not test this socket for writeability
80          */
81         FD_WANT_NO_WRITE = 0x10,
82         /** Give a write event at all times when writes will not block.
83          *
84          * You probably shouldn't use this state; if it's likely that the write
85          * will not block, try it first, then use FD_WANT_FAST_WRITE if it
86          * fails. If it's likely to block (or you are using polling-style reads)
87          * then use FD_WANT_SINGLE_WRITE.
88          */
89         FD_WANT_POLL_WRITE = 0x20,
90         /** Give a write event when writes don't block any more
91          *
92          * An event MUST be sent if writes will not block, and the most recent
93          * write/send() on this FD returned EAGAIN, or connect() returned
94          * EINPROGRESS. An event MAY be sent at any time that writes will not
95          * block.
96          *
97          * Before calling HandleEvent, a socket engine MAY change the state of
98          * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
99          * one-shot notification was registered). If further writes are needed,
100          * it is the responsibility of the event handler to change the state to
101          * one that will generate the required notifications
102          */
103         FD_WANT_FAST_WRITE = 0x40,
104         /** Give an optional write event on edge-triggered write unblock.
105          *
106          * This state is useful to avoid system calls when moving to/from
107          * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
108          */
109         FD_WANT_EDGE_WRITE = 0x80,
110         /** Request a one-shot poll-style write notification. The socket will
111          * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
112          */
113         FD_WANT_SINGLE_WRITE = 0x100,
114
115         /** Mask for all write events */
116         FD_WANT_WRITE_MASK = 0x1F0,
117
118         /** Add a trial read. During the next DispatchEvents invocation, this
119          * will call HandleEvent with EVENT_READ unless reads are known to be
120          * blocking.
121          */
122         FD_ADD_TRIAL_READ  = 0x1000,
123         /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
124          * Reset by SE before running EVENT_READ
125          */
126         FD_READ_WILL_BLOCK = 0x2000,
127
128         /** Add a trial write. During the next DispatchEvents invocation, this
129          * will call HandleEvent with EVENT_WRITE unless writes are known to be
130          * blocking.
131          * 
132          * This could be used to group several writes together into a single
133          * send() syscall, or to ensure that writes are blocking when attempting
134          * to use FD_WANT_FAST_WRITE.
135          */
136         FD_ADD_TRIAL_WRITE = 0x4000,
137         /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
138          * Reset by SE before running EVENT_WRITE
139          */
140         FD_WRITE_WILL_BLOCK = 0x8000, 
141
142         /** Mask for trial read/trial write */
143         FD_TRIAL_NOTE_MASK = 0x5000
144 };
145
146 /** This class is a basic I/O handler class.
147  * Any object which wishes to receive basic I/O events
148  * from the socketengine must derive from this class and
149  * implement the HandleEvent() method. The derived class
150  * must then be added to SocketEngine using the method
151  * SocketEngine::AddFd(), after which point the derived
152  * class will receive events to its HandleEvent() method.
153  * The derived class should also implement one of Readable()
154  * and Writeable(). In the current implementation, only
155  * Readable() is used. If this returns true, the socketengine
156  * inserts a readable socket. If it is false, the socketengine
157  * inserts a writeable socket. The derived class should never
158  * change the value this function returns without first
159  * deleting the socket from the socket engine. The only
160  * requirement beyond this for an event handler is that it
161  * must have a file descriptor. What this file descriptor
162  * is actually attached to is completely up to you.
163  */
164 class CoreExport EventHandler : public classbase
165 {
166  private:
167         /** Private state maintained by socket engine */
168         int event_mask;
169  protected:
170         /** File descriptor.
171          * All events which can be handled must have a file descriptor.  This
172          * allows you to add events for sockets, fifo's, pipes, and various
173          * other forms of IPC.  Do not change this while the object is
174          * registered with the SocketEngine
175          */
176         int fd;
177  public:
178         /** Get the current file descriptor
179          * @return The file descriptor of this handler
180          */
181         inline int GetFd() const { return fd; }
182
183         inline int GetEventMask() const { return event_mask; }
184
185         /** Set a new file desciptor
186          * @param FD The new file descriptor. Do not call this method without
187          * first deleting the object from the SocketEngine if you have
188          * added it to a SocketEngine instance.
189          */
190         void SetFd(int FD);
191
192         /** Constructor
193          */
194         EventHandler();
195
196         /** Destructor
197          */
198         virtual ~EventHandler() {}
199
200         /** Process an I/O event.
201          * You MUST implement this function in your derived
202          * class, and it will be called whenever read or write
203          * events are received.
204          * @param et either one of EVENT_READ for read events,
205          * and EVENT_WRITE for write events.
206          */
207         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
208
209         friend class SocketEngine;
210 };
211
212 /** Provides basic file-descriptor-based I/O support.
213  * The actual socketengine class presents the
214  * same interface on all operating systems, but
215  * its private members and internal behaviour
216  * should be treated as blackboxed, and vary
217  * from system to system and upon the config
218  * settings chosen by the server admin. The current
219  * version supports select, epoll and kqueue.
220  * The configure script will enable a socket engine
221  * based upon what OS is detected, and will derive
222  * a class from SocketEngine based upon what it finds.
223  * The derived classes file will also implement a
224  * classfactory, SocketEngineFactory, which will
225  * create a derived instance of SocketEngine using
226  * polymorphism so that the core and modules do not
227  * have to be aware of which SocketEngine derived
228  * class they are using.
229  */
230 class CoreExport SocketEngine
231 {
232  protected:
233         /** Current number of descriptors in the engine
234          */
235         int CurrentSetSize;
236         /** Reference table, contains all current handlers
237          */
238         EventHandler** ref;
239         /** List of handlers that want a trial read/write
240          */
241         std::set<int> trials;
242
243         int MAX_DESCRIPTORS;
244
245         size_t indata;
246         size_t outdata;
247         time_t lastempty;
248
249         void UpdateStats(size_t len_in, size_t len_out);
250
251         virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
252         void SetEventMask(EventHandler* eh, int value);
253 public:
254
255         unsigned long TotalEvents;
256         unsigned long ReadEvents;
257         unsigned long WriteEvents;
258         unsigned long ErrorEvents;
259
260         /** Constructor.
261          * The constructor transparently initializes
262          * the socket engine which the ircd is using.
263          * Please note that if there is a catastrophic
264          * failure (for example, you try and enable
265          * epoll on a 2.4 linux kernel) then this
266          * function may bail back to the shell.
267          */
268         SocketEngine();
269
270         /** Destructor.
271          * The destructor transparently tidies up
272          * any resources used by the socket engine.
273          */
274         virtual ~SocketEngine();
275
276         /** Add an EventHandler object to the engine.  Use AddFd to add a file
277          * descriptor to the engine and have the socket engine monitor it. You
278          * must provide an object derived from EventHandler which implements
279          * HandleEvent().
280          * @param eh An event handling object to add
281          * @param event_mask The initial event mask for the object
282          */
283         virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
284
285         /** If you call this function and pass it an
286          * event handler, that event handler will
287          * receive the next available write event,
288          * even if the socket is a readable socket only.
289          * Developers should avoid constantly keeping
290          * an eventhandler in the writeable state,
291          * as this will consume large amounts of
292          * CPU time.
293          * @param eh The event handler to change
294          * @param event_mask The changes to make to the wait state
295          */
296         void ChangeEventMask(EventHandler* eh, int event_mask);
297
298         /** Returns the highest file descriptor you may store in the socket engine
299          * @return The maximum fd value
300          */
301         inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
302
303         /** Returns the number of file descriptors being queried
304          * @return The set size
305          */
306         inline int GetUsedFds() const { return CurrentSetSize; }
307
308         /** Delete an event handler from the engine.
309          * This function call deletes an EventHandler
310          * from the engine, returning true if it succeeded
311          * and false if it failed. This does not free the
312          * EventHandler pointer using delete, if this is
313          * required you must do this yourself.
314          * @param eh The event handler object to remove
315          */
316         virtual void DelFd(EventHandler* eh) = 0;
317
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
322          */
323         virtual bool HasFd(int fd);
324
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
329          */
330         virtual EventHandler* GetRef(int fd);
331
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
337          * value.
338          * @return The number of events which have occured.
339          */
340         virtual int DispatchEvents() = 0;
341
342         /** Dispatch trial reads and writes. This causes the actual socket I/O
343          * to happen when writes have been pre-buffered.
344          */
345         virtual void DispatchTrialWrites();
346
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
350          */
351         virtual std::string GetName() = 0;
352
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.
355          */
356         virtual bool BoundsCheckFd(EventHandler* eh);
357
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.
362          */
363         int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
364
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.
369          */
370         int Close(EventHandler* fd);
371
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.
376          */
377         int Close(int fd);
378
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.
383          */
384         int Send(EventHandler* fd, const void *buf, size_t len, int flags);
385
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.
390          */
391         int Recv(EventHandler* fd, void *buf, size_t len, int flags);
392
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.
397          */
398         int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
399
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.
404          */
405         int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
406
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.
411          */
412         int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
413
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.
417          */
418         int Blocking(int fd);
419
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.
423          */
424         int NonBlocking(int fd);
425
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.
430          */
431         int Shutdown(EventHandler* fd, int how);
432
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.
436          */
437         int Shutdown(int fd, int how);
438
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.
442          */
443         int Bind(int fd, const irc::sockets::sockaddrs& addr);
444
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.
448          */
449         int Listen(int sockfd, int backlog);
450
451         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
452          */
453         void SetReuse(int sockfd);
454
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.
463          */
464         virtual void RecoverFromFork();
465
466         /** Get data transfer statistics, kilobits per second in and out and total.
467          */
468         void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
469 };
470
471 SocketEngine* CreateSocketEngine();
472
473 #endif
474