]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Merge branch 'master+ehdispatch'
[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 #pragma once
24
25 #include <vector>
26 #include <string>
27 #include <map>
28 #include "config.h"
29 #include "socket.h"
30 #include "base.h"
31
32 #ifndef _WIN32
33 #include <sys/uio.h>
34 #endif
35
36 #ifndef IOV_MAX
37 #define IOV_MAX 1024
38 #endif
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 /** This class is a basic I/O handler class.
137  * Any object which wishes to receive basic I/O events
138  * from the socketengine must derive from this class and
139  * implement the HandleEvent() method. The derived class
140  * must then be added to SocketEngine using the method
141  * SocketEngine::AddFd(), after which point the derived
142  * class will receive events to its HandleEvent() method.
143  * The derived class should also implement one of Readable()
144  * and Writeable(). In the current implementation, only
145  * Readable() is used. If this returns true, the socketengine
146  * inserts a readable socket. If it is false, the socketengine
147  * inserts a writeable socket. The derived class should never
148  * change the value this function returns without first
149  * deleting the socket from the socket engine. The only
150  * requirement beyond this for an event handler is that it
151  * must have a file descriptor. What this file descriptor
152  * is actually attached to is completely up to you.
153  */
154 class CoreExport EventHandler : public classbase
155 {
156  private:
157         /** Private state maintained by socket engine */
158         int event_mask;
159
160         void SetEventMask(int mask) { event_mask = mask; }
161
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         /** Called by the socket engine in case of a read event
194          */
195         virtual void OnEventHandlerRead() = 0;
196
197         /** Called by the socket engine in case of a write event.
198          * The default implementation does nothing.
199          */
200         virtual void OnEventHandlerWrite();
201
202         /** Called by the socket engine in case of an error event.
203          * The default implementation does nothing.
204          * @param errornum Error code
205          */
206         virtual void OnEventHandlerError(int errornum);
207
208         friend class SocketEngine;
209 };
210
211 /** Provides basic file-descriptor-based I/O support.
212  * The actual socketengine class presents the
213  * same interface on all operating systems, but
214  * its private members and internal behaviour
215  * should be treated as blackboxed, and vary
216  * from system to system and upon the config
217  * settings chosen by the server admin. The current
218  * version supports select, epoll and kqueue.
219  * The configure script will enable a socket engine
220  * based upon what OS is detected, and will derive
221  * a class from SocketEngine based upon what it finds.
222  * The derived classes file will also implement a
223  * classfactory, SocketEngineFactory, which will
224  * create a derived instance of SocketEngine using
225  * polymorphism so that the core and modules do not
226  * have to be aware of which SocketEngine derived
227  * class they are using.
228  */
229 class CoreExport SocketEngine
230 {
231  public:
232         /** Socket engine statistics: count of various events, bandwidth usage
233          */
234         class Statistics
235         {
236                 mutable size_t indata;
237                 mutable size_t outdata;
238                 mutable time_t lastempty;
239
240                 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
241                  */
242                 void CheckFlush() const;
243
244          public:
245                 /** Constructor, initializes member vars except indata and outdata because those are set to 0
246                  * in CheckFlush() the first time Update() or GetBandwidth() is called.
247                  */
248                 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
249
250                 /** Increase the counters for bytes sent/received in this second.
251                  * @param len_in Bytes received, 0 if updating number of bytes written.
252                  * @param len_out Bytes sent, 0 if updating number of bytes read.
253                  */
254                 void Update(size_t len_in, size_t len_out);
255
256                 /** Get data transfer statistics.
257                  * @param kbitspersec_in Filled with incoming traffic in this second in kbit/s.
258                  * @param kbitspersec_out Filled with outgoing traffic in this second in kbit/s.
259                  * @param kbitspersec_total Filled with total traffic in this second in kbit/s.
260                  */
261                 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
262
263                 unsigned long TotalEvents;
264                 unsigned long ReadEvents;
265                 unsigned long WriteEvents;
266                 unsigned long ErrorEvents;
267         };
268
269  private:
270         /** Reference table, contains all current handlers
271          **/
272         static std::vector<EventHandler*> ref;
273
274  protected:
275         /** Current number of descriptors in the engine
276          */
277         static size_t CurrentSetSize;
278         /** List of handlers that want a trial read/write
279          */
280         static std::set<int> trials;
281
282         static int MAX_DESCRIPTORS;
283
284         /** Socket engine statistics: count of various events, bandwidth usage
285          */
286         static Statistics stats;
287
288         static void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
289
290         /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
291          */
292         static bool AddFdRef(EventHandler* eh);
293
294         static void DelFdRef(EventHandler* eh);
295
296         template <typename T>
297         static void ResizeDouble(std::vector<T>& vect)
298         {
299                 if (SocketEngine::CurrentSetSize > vect.size())
300                         vect.resize(vect.size() * 2);
301         }
302
303 public:
304 #ifndef _WIN32
305         typedef iovec IOVector;
306 #else
307         typedef WindowsIOVec IOVector;
308 #endif
309
310         /** Constructor.
311          * The constructor transparently initializes
312          * the socket engine which the ircd is using.
313          * Please note that if there is a catastrophic
314          * failure (for example, you try and enable
315          * epoll on a 2.4 linux kernel) then this
316          * function may bail back to the shell.
317          * @return void, but it is acceptable for this function to bail back to
318          * the shell or operating system on fatal error.
319          */
320         static void Init();
321
322         /** Destructor.
323          * The destructor transparently tidies up
324          * any resources used by the socket engine.
325          */
326         static void Deinit();
327
328         /** Add an EventHandler object to the engine.  Use AddFd to add a file
329          * descriptor to the engine and have the socket engine monitor it. You
330          * must provide an object derived from EventHandler which implements
331          * HandleEvent().
332          * @param eh An event handling object to add
333          * @param event_mask The initial event mask for the object
334          */
335         static bool AddFd(EventHandler* eh, int event_mask);
336
337         /** If you call this function and pass it an
338          * event handler, that event handler will
339          * receive the next available write event,
340          * even if the socket is a readable socket only.
341          * Developers should avoid constantly keeping
342          * an eventhandler in the writeable state,
343          * as this will consume large amounts of
344          * CPU time.
345          * @param eh The event handler to change
346          * @param event_mask The changes to make to the wait state
347          */
348         static void ChangeEventMask(EventHandler* eh, int event_mask);
349
350         /** Returns the number of file descriptors reported by the system this program may use
351          * when it was started.
352          * @return If positive, the number of file descriptors that the system reported that we
353          * may use. Otherwise (<= 0) this number could not be determined.
354          */
355         static int GetMaxFds() { return MAX_DESCRIPTORS; }
356
357         /** Returns the number of file descriptors being queried
358          * @return The set size
359          */
360         static size_t GetUsedFds() { return CurrentSetSize; }
361
362         /** Delete an event handler from the engine.
363          * This function call deletes an EventHandler
364          * from the engine, returning true if it succeeded
365          * and false if it failed. This does not free the
366          * EventHandler pointer using delete, if this is
367          * required you must do this yourself.
368          * @param eh The event handler object to remove
369          */
370         static void DelFd(EventHandler* eh);
371
372         /** Returns true if a file descriptor exists in
373          * the socket engine's list.
374          * @param fd The event handler to look for
375          * @return True if this fd has an event handler
376          */
377         static bool HasFd(int fd);
378
379         /** Returns the EventHandler attached to a specific fd.
380          * If the fd isnt in the socketengine, returns NULL.
381          * @param fd The event handler to look for
382          * @return A pointer to the event handler, or NULL
383          */
384         static EventHandler* GetRef(int fd);
385
386         /** Waits for events and dispatches them to handlers.  Please note that
387          * this doesn't wait long, only a couple of milliseconds. It returns the
388          * number of events which occurred during this call.  This method will
389          * dispatch events to their handlers by calling their
390          * EventHandler::HandleEvent() methods with the necessary EventType
391          * value.
392          * @return The number of events which have occured.
393          */
394         static int DispatchEvents();
395
396         /** Dispatch trial reads and writes. This causes the actual socket I/O
397          * to happen when writes have been pre-buffered.
398          */
399         static void DispatchTrialWrites();
400
401         /** Returns true if the file descriptors in the given event handler are
402          * within sensible ranges which can be handled by the socket engine.
403          */
404         static bool BoundsCheckFd(EventHandler* eh);
405
406         /** Abstraction for BSD sockets accept(2).
407          * This function should emulate its namesake system call exactly.
408          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
409          * @param addr The client IP address and port
410          * @param addrlen The size of the sockaddr parameter.
411          * @return This method should return exactly the same values as the system call it emulates.
412          */
413         static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
414
415         /** Close the underlying fd of an event handler, remove it from the socket engine and set the fd to -1.
416          * @param eh The EventHandler to close.
417          * @return 0 on success, a negative value on error
418          */
419         static int Close(EventHandler* eh);
420
421         /** Abstraction for BSD sockets close(2).
422          * This function should emulate its namesake system call exactly.
423          * This function should emulate its namesake system call exactly.
424          * @return This method should return exactly the same values as the system call it emulates.
425          */
426         static int Close(int fd);
427
428         /** Abstraction for BSD sockets send(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          * @param buf The buffer in which the data that is sent is stored.
432          * @param len The size of the buffer.
433          * @param flags A flag value that controls the sending of the data.
434          * @return This method should return exactly the same values as the system call it emulates.
435          */
436         static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
437
438         /** Abstraction for vector write function writev().
439          * This function should emulate its namesake system call exactly.
440          * @param fd EventHandler to send data with
441          * @param iov Array of IOVectors containing the buffers to send and their lengths in the platform's
442          * native format.
443          * @param count Number of elements in iov.
444          * @return This method should return exactly the same values as the system call it emulates.
445          */
446         static int WriteV(EventHandler* fd, const IOVector* iov, int count);
447
448 #ifdef _WIN32
449         /** Abstraction for vector write function writev() that accepts a POSIX format iovec.
450          * This function should emulate its namesake system call exactly.
451          * @param fd EventHandler to send data with
452          * @param iov Array of iovecs containing the buffers to send and their lengths in POSIX format.
453          * @param count Number of elements in iov.
454          * @return This method should return exactly the same values as the system call it emulates.
455          */
456         static int WriteV(EventHandler* fd, const iovec* iov, int count);
457 #endif
458
459         /** Abstraction for BSD sockets recv(2).
460          * This function should emulate its namesake system call exactly.
461          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
462          * @param buf The buffer in which the data that is read is stored.
463          * @param len The size of the buffer.
464          * @param flags A flag value that controls the reception of the data.
465          * @return This method should return exactly the same values as the system call it emulates.
466          */
467         static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
468
469         /** Abstraction for BSD sockets recvfrom(2).
470          * This function should emulate its namesake system call exactly.
471          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
472          * @param buf The buffer in which the data that is read is stored.
473          * @param len The size of the buffer.
474          * @param flags A flag value that controls the reception of the data.
475          * @param from The remote IP address and port.
476          * @param fromlen The size of the from parameter.
477          * @return This method should return exactly the same values as the system call it emulates.
478          */
479         static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
480
481         /** Abstraction for BSD sockets sendto(2).
482          * This function should emulate its namesake system call exactly.
483          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
484          * @param buf The buffer in which the data that is sent is stored.
485          * @param len The size of the buffer.
486          * @param flags A flag value that controls the sending of the data.
487          * @param to The remote IP address and port.
488          * @param tolen The size of the to parameter.
489          * @return This method should return exactly the same values as the system call it emulates.
490          */
491         static int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
492
493         /** Abstraction for BSD sockets connect(2).
494          * This function should emulate its namesake system call exactly.
495          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
496          * @param serv_addr The server IP address and port.
497          * @param addrlen The size of the sockaddr parameter.
498          * @return This method should return exactly the same values as the system call it emulates.
499          */
500         static int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
501
502         /** Make a file descriptor blocking.
503          * @param fd a file descriptor to set to blocking mode
504          * @return 0 on success, -1 on failure, errno is set appropriately.
505          */
506         static int Blocking(int fd);
507
508         /** Make a file descriptor nonblocking.
509          * @param fd A file descriptor to set to nonblocking mode
510          * @return 0 on success, -1 on failure, errno is set appropriately.
511          */
512         static int NonBlocking(int fd);
513
514         /** Abstraction for BSD sockets shutdown(2).
515          * This function should emulate its namesake system call exactly.
516          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
517          * @param how What part of the socket to shut down
518          * @return This method should return exactly the same values as the system call it emulates.
519          */
520         static int Shutdown(EventHandler* fd, int how);
521
522         /** Abstraction for BSD sockets shutdown(2).
523          * This function should emulate its namesake system call exactly.
524          * @return This method should return exactly the same values as the system call it emulates.
525          */
526         static int Shutdown(int fd, int how);
527
528         /** Abstraction for BSD sockets bind(2).
529          * This function should emulate its namesake system call exactly.
530          * @return This method should return exactly the same values as the system call it emulates.
531          */
532         static int Bind(int fd, const irc::sockets::sockaddrs& addr);
533
534         /** Abstraction for BSD sockets listen(2).
535          * This function should emulate its namesake system call exactly.
536          * @return This method should return exactly the same values as the system call it emulates.
537          */
538         static int Listen(int sockfd, int backlog);
539
540         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
541          */
542         static void SetReuse(int sockfd);
543
544         /** This function is called immediately after fork().
545          * Some socket engines (notably kqueue) cannot have their
546          * handles inherited by forked processes. This method
547          * allows for the socket engine to re-create its handle
548          * after the daemon forks as the socket engine is created
549          * long BEFORE the daemon forks.
550          * @return void, but it is acceptable for this function to bail back to
551          * the shell or operating system on fatal error.
552          */
553         static void RecoverFromFork();
554
555         /** Get data transfer and event statistics
556          */
557         static const Statistics& GetStats() { return stats; }
558
559         /** Should we ignore the error in errno?
560          * Checks EAGAIN and WSAEWOULDBLOCK
561          */
562         static bool IgnoreError();
563
564         /** Return the last socket related error. strrerror(errno) on *nix
565          */
566         static std::string LastError();
567
568         /** Returns the error for the given error num, strerror(errnum) on *nix
569          */
570         static std::string GetError(int errnum);
571 };
572
573 inline bool SocketEngine::IgnoreError()
574 {
575         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
576                 return true;
577
578 #ifdef _WIN32
579         if (WSAGetLastError() == WSAEWOULDBLOCK)
580                 return true;
581 #endif
582
583         return false;
584 }