]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Merge pull request #1018 from SaberUK/insp20+hidekills
[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          * EVENT_WRITE for write events and EVENT_ERROR for
206          * error events.
207          * @param errornum The error code which goes with an EVENT_ERROR.
208          */
209         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
210
211         friend class SocketEngine;
212 };
213
214 /** Provides basic file-descriptor-based I/O support.
215  * The actual socketengine class presents the
216  * same interface on all operating systems, but
217  * its private members and internal behaviour
218  * should be treated as blackboxed, and vary
219  * from system to system and upon the config
220  * settings chosen by the server admin. The current
221  * version supports select, epoll and kqueue.
222  * The configure script will enable a socket engine
223  * based upon what OS is detected, and will derive
224  * a class from SocketEngine based upon what it finds.
225  * The derived classes file will also implement a
226  * classfactory, SocketEngineFactory, which will
227  * create a derived instance of SocketEngine using
228  * polymorphism so that the core and modules do not
229  * have to be aware of which SocketEngine derived
230  * class they are using.
231  */
232 class CoreExport SocketEngine
233 {
234  protected:
235         /** Current number of descriptors in the engine
236          */
237         int CurrentSetSize;
238         /** Reference table, contains all current handlers
239          */
240         EventHandler** ref;
241         /** List of handlers that want a trial read/write
242          */
243         std::set<int> trials;
244
245         int MAX_DESCRIPTORS;
246
247         size_t indata;
248         size_t outdata;
249         time_t lastempty;
250
251         void UpdateStats(size_t len_in, size_t len_out);
252
253         virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
254         void SetEventMask(EventHandler* eh, int value);
255 public:
256
257         unsigned long TotalEvents;
258         unsigned long ReadEvents;
259         unsigned long WriteEvents;
260         unsigned long ErrorEvents;
261
262         /** Constructor.
263          * The constructor transparently initializes
264          * the socket engine which the ircd is using.
265          * Please note that if there is a catastrophic
266          * failure (for example, you try and enable
267          * epoll on a 2.4 linux kernel) then this
268          * function may bail back to the shell.
269          */
270         SocketEngine();
271
272         /** Destructor.
273          * The destructor transparently tidies up
274          * any resources used by the socket engine.
275          */
276         virtual ~SocketEngine();
277
278         /** Add an EventHandler object to the engine.  Use AddFd to add a file
279          * descriptor to the engine and have the socket engine monitor it. You
280          * must provide an object derived from EventHandler which implements
281          * HandleEvent().
282          * @param eh An event handling object to add
283          * @param event_mask The initial event mask for the object
284          */
285         virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
286
287         /** If you call this function and pass it an
288          * event handler, that event handler will
289          * receive the next available write event,
290          * even if the socket is a readable socket only.
291          * Developers should avoid constantly keeping
292          * an eventhandler in the writeable state,
293          * as this will consume large amounts of
294          * CPU time.
295          * @param eh The event handler to change
296          * @param event_mask The changes to make to the wait state
297          */
298         void ChangeEventMask(EventHandler* eh, int event_mask);
299
300         /** Returns the highest file descriptor you may store in the socket engine
301          * @return The maximum fd value
302          */
303         inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
304
305         /** Returns the number of file descriptors being queried
306          * @return The set size
307          */
308         inline int GetUsedFds() const { return CurrentSetSize; }
309
310         /** Delete an event handler from the engine.
311          * This function call deletes an EventHandler
312          * from the engine, returning true if it succeeded
313          * and false if it failed. This does not free the
314          * EventHandler pointer using delete, if this is
315          * required you must do this yourself.
316          * @param eh The event handler object to remove
317          */
318         virtual void DelFd(EventHandler* eh) = 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          * @param addr The client IP address and port
364          * @param addrlen The size of the sockaddr parameter.
365          * @return This method should return exactly the same values as the system call it emulates.
366          */
367         int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
368
369         /** Abstraction for BSD sockets close(2).
370          * This function should emulate its namesake system call exactly.
371          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
372          * @return This method should return exactly the same values as the system call it emulates.
373          */
374         int Close(EventHandler* fd);
375
376         /** Abstraction for BSD sockets close(2).
377          * This function should emulate its namesake system call exactly.
378          * This function should emulate its namesake system call exactly.
379          * @return This method should return exactly the same values as the system call it emulates.
380          */
381         int Close(int fd);
382
383         /** Abstraction for BSD sockets send(2).
384          * This function should emulate its namesake system call exactly.
385          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
386          * @param buf The buffer in which the data that is sent is stored.
387          * @param len The size of the buffer.
388          * @param flags A flag value that controls the sending of the data.
389          * @return This method should return exactly the same values as the system call it emulates.
390          */
391         int Send(EventHandler* fd, const void *buf, size_t len, int flags);
392
393         /** Abstraction for BSD sockets recv(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          * @param buf The buffer in which the data that is read is stored.
397          * @param len The size of the buffer.
398          * @param flags A flag value that controls the reception of the data.
399          * @return This method should return exactly the same values as the system call it emulates.
400          */
401         int Recv(EventHandler* fd, void *buf, size_t len, int flags);
402
403         /** Abstraction for BSD sockets recvfrom(2).
404          * This function should emulate its namesake system call exactly.
405          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
406          * @param buf The buffer in which the data that is read is stored.
407          * @param len The size of the buffer.
408          * @param flags A flag value that controls the reception of the data.
409          * @param from The remote IP address and port.
410          * @param fromlen The size of the from parameter.
411          * @return This method should return exactly the same values as the system call it emulates.
412          */
413         int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
414
415         /** Abstraction for BSD sockets sendto(2).
416          * This function should emulate its namesake system call exactly.
417          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
418          * @param buf The buffer in which the data that is sent is stored.
419          * @param len The size of the buffer.
420          * @param flags A flag value that controls the sending of the data.
421          * @param to The remote IP address and port.    
422          * @param tolen The size of the to parameter.
423          * @return This method should return exactly the same values as the system call it emulates.
424          */
425         int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
426
427         /** Abstraction for BSD sockets connect(2).
428          * This function should emulate its namesake system call exactly.
429          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
430          * @param serv_addr The server IP address and port.
431          * @param addrlen The size of the sockaddr parameter.
432          * @return This method should return exactly the same values as the system call it emulates.
433          */
434         int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
435
436         /** Make a file descriptor blocking.
437          * @param fd a file descriptor to set to blocking mode
438          * @return 0 on success, -1 on failure, errno is set appropriately.
439          */
440         int Blocking(int fd);
441
442         /** Make a file descriptor nonblocking.
443          * @param fd A file descriptor to set to nonblocking mode
444          * @return 0 on success, -1 on failure, errno is set appropriately.
445          */
446         int NonBlocking(int fd);
447
448         /** Abstraction for BSD sockets shutdown(2).
449          * This function should emulate its namesake system call exactly.
450          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
451          * @param how What part of the socket to shut down
452          * @return This method should return exactly the same values as the system call it emulates.
453          */
454         int Shutdown(EventHandler* fd, int how);
455
456         /** Abstraction for BSD sockets shutdown(2).
457          * This function should emulate its namesake system call exactly.
458          * @return This method should return exactly the same values as the system call it emulates.
459          */
460         int Shutdown(int fd, int how);
461
462         /** Abstraction for BSD sockets bind(2).
463          * This function should emulate its namesake system call exactly.
464          * @return This method should return exactly the same values as the system call it emulates.
465          */
466         int Bind(int fd, const irc::sockets::sockaddrs& addr);
467
468         /** Abstraction for BSD sockets listen(2).
469          * This function should emulate its namesake system call exactly.
470          * @return This method should return exactly the same values as the system call it emulates.
471          */
472         int Listen(int sockfd, int backlog);
473
474         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
475          */
476         void SetReuse(int sockfd);
477
478         /** This function is called immediately after fork().
479          * Some socket engines (notably kqueue) cannot have their
480          * handles inherited by forked processes. This method
481          * allows for the socket engine to re-create its handle
482          * after the daemon forks as the socket engine is created
483          * long BEFORE the daemon forks.
484          * @return void, but it is acceptable for this function to bail back to
485          * the shell or operating system on fatal error.
486          */
487         virtual void RecoverFromFork();
488
489         /** Get data transfer statistics, kilobits per second in and out and total.
490          */
491         void GetStats(float &kbitpersec_in, float &kbitpersec_out, float &kbitpersec_total);
492
493         /** Should we ignore the error in errno?
494          * Checks EAGAIN and WSAEWOULDBLOCK
495          */
496         static bool IgnoreError();
497
498         /** Return the last socket related error. strrerror(errno) on *nix
499          */
500         static std::string LastError();
501
502         /** Returns the error for the given error num, strerror(errnum) on *nix
503          */
504         static std::string GetError(int errnum);
505 };
506
507 inline bool SocketEngine::IgnoreError()
508 {
509         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
510                 return true;
511
512 #ifdef _WIN32
513         if (WSAGetLastError() == WSAEWOULDBLOCK)
514                 return true;
515 #endif
516
517         return false;
518 }
519
520 SocketEngine* CreateSocketEngine();
521
522 #endif
523