]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
9ca8aba6a41469981bb644a41fbaab1e8401e2d8
[user/henk/code/inspircd.git] / include / socketengine.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
5  *   Copyright (C) 2013-2014 Adam <Adam@anope.org>
6  *   Copyright (C) 2012-2013, 2017-2020 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
8  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
9  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
10  *   Copyright (C) 2007-2008, 2017 Robin Burchell <robin+git@viroteck.net>
11  *   Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
12  *   Copyright (C) 2007 burlex <burlex@e03df62e-2008-0410-955e-edbf42e46eb7>
13  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 #pragma once
30
31 #include <vector>
32 #include <string>
33 #include <map>
34 #include "config.h"
35 #include "socket.h"
36 #include "base.h"
37
38 #ifndef _WIN32
39 #include <sys/uio.h>
40 #endif
41
42 #ifndef IOV_MAX
43 #define IOV_MAX 1024
44 #endif
45
46 /**
47  * Event mask for SocketEngine events
48  */
49 enum EventMask
50 {
51         /** Do not test this socket for readability
52          */
53         FD_WANT_NO_READ = 0x1,
54         /** Give a read event at all times when reads will not block.
55          */
56         FD_WANT_POLL_READ = 0x2,
57         /** Give a read event when there is new data to read.
58          *
59          * An event MUST be sent if there is new data to be read, and the most
60          * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
61          * at any time there is data to be read on the socket.
62          */
63         FD_WANT_FAST_READ = 0x4,
64         /** Give an optional read event when reads begin to unblock
65          *
66          * This state is useful if you want to leave data in the OS receive
67          * queue but not get continuous event notifications about it, because
68          * it may not require a system call to transition from FD_WANT_FAST_READ
69          */
70         FD_WANT_EDGE_READ = 0x8,
71
72         /** Mask for all read events */
73         FD_WANT_READ_MASK = 0x0F,
74
75         /** Do not test this socket for writeability
76          */
77         FD_WANT_NO_WRITE = 0x10,
78         /** Give a write event at all times when writes will not block.
79          *
80          * You probably shouldn't use this state; if it's likely that the write
81          * will not block, try it first, then use FD_WANT_FAST_WRITE if it
82          * fails. If it's likely to block (or you are using polling-style reads)
83          * then use FD_WANT_SINGLE_WRITE.
84          */
85         FD_WANT_POLL_WRITE = 0x20,
86         /** Give a write event when writes don't block any more
87          *
88          * An event MUST be sent if writes will not block, and the most recent
89          * write/send() on this FD returned EAGAIN, or connect() returned
90          * EINPROGRESS. An event MAY be sent at any time that writes will not
91          * block.
92          *
93          * Before calling OnEventHandler*(), a socket engine MAY change the state of
94          * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
95          * one-shot notification was registered). If further writes are needed,
96          * it is the responsibility of the event handler to change the state to
97          * one that will generate the required notifications
98          */
99         FD_WANT_FAST_WRITE = 0x40,
100         /** Give an optional write event on edge-triggered write unblock.
101          *
102          * This state is useful to avoid system calls when moving to/from
103          * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
104          */
105         FD_WANT_EDGE_WRITE = 0x80,
106         /** Request a one-shot poll-style write notification. The socket will
107          * return to the FD_WANT_NO_WRITE state before OnEventHandler*() is called.
108          */
109         FD_WANT_SINGLE_WRITE = 0x100,
110
111         /** Mask for all write events */
112         FD_WANT_WRITE_MASK = 0x1F0,
113
114         /** Add a trial read. During the next DispatchEvents invocation, this
115          * will call OnEventHandlerRead() unless reads are known to be
116          * blocking.
117          */
118         FD_ADD_TRIAL_READ  = 0x1000,
119         /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
120          * Reset by SE before running OnEventHandlerRead().
121          */
122         FD_READ_WILL_BLOCK = 0x2000,
123
124         /** Add a trial write. During the next DispatchEvents invocation, this
125          * will call OnEventHandlerWrite() unless writes are known to be
126          * blocking.
127          *
128          * This could be used to group several writes together into a single
129          * send() syscall, or to ensure that writes are blocking when attempting
130          * to use FD_WANT_FAST_WRITE.
131          */
132         FD_ADD_TRIAL_WRITE = 0x4000,
133         /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
134          * Reset by SE before running OnEventHandlerWrite().
135          */
136         FD_WRITE_WILL_BLOCK = 0x8000,
137
138         /** Mask for trial read/trial write */
139         FD_TRIAL_NOTE_MASK = 0x5000
140 };
141
142 /** This class is a basic I/O handler class.
143  * Any object which wishes to receive basic I/O events
144  * from the socketengine must derive from this class and
145  * implement the OnEventHandler*() methods. The derived class
146  * must then be added to SocketEngine using the method
147  * SocketEngine::AddFd(), after which point the derived
148  * class will receive events to its OnEventHandler*() methods.
149  * The event mask passed to SocketEngine::AddFd() determines
150  * what events the EventHandler gets notified about and with
151  * what semantics. SocketEngine::ChangeEventMask() can be
152  * called to update the event mask later. The only
153  * requirement beyond this for an event handler is that it
154  * must have a file descriptor. What this file descriptor
155  * is actually attached to is completely up to you.
156  */
157 class CoreExport EventHandler : public classbase
158 {
159  private:
160         /** Private state maintained by socket engine */
161         int event_mask;
162
163         void SetEventMask(int mask) { event_mask = mask; }
164
165  protected:
166         /** File descriptor.
167          * All events which can be handled must have a file descriptor.  This
168          * allows you to add events for sockets, fifo's, pipes, and various
169          * other forms of IPC.  Do not change this while the object is
170          * registered with the SocketEngine
171          */
172         int fd;
173
174         /** Swaps the internals of this EventHandler with another one.
175          * @param other A EventHandler to swap internals with.
176          */
177         void SwapInternals(EventHandler& other);
178
179  public:
180         /** Get the current file descriptor
181          * @return The file descriptor of this handler
182          */
183         inline int GetFd() const { return fd; }
184
185         /** Checks if this event handler has a fd associated with it. */
186         inline bool HasFd() const { return fd >= 0; }
187
188         inline int GetEventMask() const { return event_mask; }
189
190         /** Set a new file descriptor
191          * @param FD The new file descriptor. Do not call this method without
192          * first deleting the object from the SocketEngine if you have
193          * added it to a SocketEngine instance.
194          */
195         void SetFd(int FD);
196
197         /** Constructor
198          */
199         EventHandler();
200
201         /** Destructor
202          */
203         virtual ~EventHandler() {}
204
205         /** Called by the socket engine in case of a read event
206          */
207         virtual void OnEventHandlerRead() = 0;
208
209         /** Called by the socket engine in case of a write event.
210          * The default implementation does nothing.
211          */
212         virtual void OnEventHandlerWrite();
213
214         /** Called by the socket engine in case of an error event.
215          * The default implementation does nothing.
216          * @param errornum Error code
217          */
218         virtual void OnEventHandlerError(int errornum);
219
220         friend class SocketEngine;
221 };
222
223 /** Provides basic file-descriptor-based I/O support.
224  * The actual socketengine class presents the
225  * same interface on all operating systems, but
226  * its private members and internal behaviour
227  * should be treated as blackboxed, and vary
228  * from system to system and upon the config
229  * settings chosen by the server admin.
230  */
231 class CoreExport SocketEngine
232 {
233  public:
234         /** Socket engine statistics: count of various events, bandwidth usage
235          */
236         class Statistics
237         {
238                 mutable size_t indata;
239                 mutable size_t outdata;
240                 mutable time_t lastempty;
241
242                 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
243                  */
244                 void CheckFlush() const;
245
246          public:
247                 /** Constructor, initializes member vars except indata and outdata because those are set to 0
248                  * in CheckFlush() the first time Update() or GetBandwidth() is called.
249                  */
250                 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
251
252                 /** Update counters for network data received.
253                  * This should be called after every read-type syscall.
254                  * @param len_in Number of bytes received, or -1 for error, as typically
255                  * returned by a read-style syscall.
256                  */
257                 void UpdateReadCounters(int len_in);
258
259                 /** Update counters for network data sent.
260                  * This should be called after every write-type syscall.
261                  * @param len_out Number of bytes sent, or -1 for error, as typically
262                  * returned by a read-style syscall.
263                  */
264                 void UpdateWriteCounters(int len_out);
265
266                 /** Get data transfer statistics.
267                  * @param kbitpersec_in Filled with incoming traffic in this second in kbit/s.
268                  * @param kbitpersec_out Filled with outgoing traffic in this second in kbit/s.
269                  * @param kbitpersec_total Filled with total traffic in this second in kbit/s.
270                  */
271                 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
272
273                 unsigned long TotalEvents;
274                 unsigned long ReadEvents;
275                 unsigned long WriteEvents;
276                 unsigned long ErrorEvents;
277         };
278
279  private:
280         /** Reference table, contains all current handlers
281          **/
282         static std::vector<EventHandler*> ref;
283
284         /** Current number of descriptors in the engine. */
285         static size_t CurrentSetSize;
286
287         /** The maximum number of descriptors in the engine. */
288         static size_t MaxSetSize;
289
290         /** List of handlers that want a trial read/write
291          */
292         static std::set<int> trials;
293
294         /** Socket engine statistics: count of various events, bandwidth usage
295          */
296         static Statistics stats;
297
298         /** Look up the fd limit using rlimit. */
299         static void LookupMaxFds();
300
301         /** Terminates the program when the socket engine fails to initialize. */
302         static void InitError();
303
304         static void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
305
306         /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
307          */
308         static bool AddFdRef(EventHandler* eh);
309
310         static void DelFdRef(EventHandler* eh);
311
312         template <typename T>
313         static void ResizeDouble(std::vector<T>& vect)
314         {
315                 if (SocketEngine::CurrentSetSize > vect.size())
316                         vect.resize(SocketEngine::CurrentSetSize * 2);
317         }
318
319 public:
320 #ifndef _WIN32
321         typedef iovec IOVector;
322 #else
323         typedef WindowsIOVec IOVector;
324 #endif
325
326         /** Constructor.
327          * The constructor transparently initializes
328          * the socket engine which the ircd is using.
329          * Please note that if there is a catastrophic
330          * failure (for example, you try and enable
331          * epoll on a 2.4 linux kernel) then this
332          * function may bail back to the shell.
333          * @return void, but it is acceptable for this function to bail back to
334          * the shell or operating system on fatal error.
335          */
336         static void Init();
337
338         /** Destructor.
339          * The destructor transparently tidies up
340          * any resources used by the socket engine.
341          */
342         static void Deinit();
343
344         /** Add an EventHandler object to the engine.  Use AddFd to add a file
345          * descriptor to the engine and have the socket engine monitor it. You
346          * must provide an object derived from EventHandler which implements
347          * the required OnEventHandler*() methods.
348          * @param eh An event handling object to add
349          * @param event_mask The initial event mask for the object
350          */
351         static bool AddFd(EventHandler* eh, int event_mask);
352
353         /** If you call this function and pass it an
354          * event handler, that event handler will
355          * receive the next available write event,
356          * even if the socket is a readable socket only.
357          * Developers should avoid constantly keeping
358          * an eventhandler in the writeable state,
359          * as this will consume large amounts of
360          * CPU time.
361          * @param eh The event handler to change
362          * @param event_mask The changes to make to the wait state
363          */
364         static void ChangeEventMask(EventHandler* eh, int event_mask);
365
366         /** Returns the number of file descriptors reported by the system this program may use
367          * when it was started.
368          * @return If non-zero the number of file descriptors that the system reported that we
369          * may use.
370          */
371         static size_t GetMaxFds() { return MaxSetSize; }
372
373         /** Returns the number of file descriptors being queried
374          * @return The set size
375          */
376         static size_t GetUsedFds() { return CurrentSetSize; }
377
378         /** Delete an event handler from the engine.
379          * This function call deletes an EventHandler
380          * from the engine, returning true if it succeeded
381          * and false if it failed. This does not free the
382          * EventHandler pointer using delete, if this is
383          * required you must do this yourself.
384          * @param eh The event handler object to remove
385          */
386         static void DelFd(EventHandler* eh);
387
388         /** Returns true if a file descriptor exists in
389          * the socket engine's list.
390          * @param fd The event handler to look for
391          * @return True if this fd has an event handler
392          */
393         static bool HasFd(int fd);
394
395         /** Returns the EventHandler attached to a specific fd.
396          * If the fd isn't in the socketengine, returns NULL.
397          * @param fd The event handler to look for
398          * @return A pointer to the event handler, or NULL
399          */
400         static EventHandler* GetRef(int fd);
401
402         /** Waits for events and dispatches them to handlers.  Please note that
403          * this doesn't wait long, only a couple of milliseconds. It returns the
404          * number of events which occurred during this call.  This method will
405          * dispatch events to their handlers by calling their
406          * EventHandler::OnEventHandler*() methods.
407          * @return The number of events which have occurred.
408          */
409         static int DispatchEvents();
410
411         /** Dispatch trial reads and writes. This causes the actual socket I/O
412          * to happen when writes have been pre-buffered.
413          */
414         static void DispatchTrialWrites();
415
416         /** Returns true if the file descriptors in the given event handler are
417          * within sensible ranges which can be handled by the socket engine.
418          */
419         static bool BoundsCheckFd(EventHandler* eh);
420
421         /** Abstraction for BSD sockets accept(2).
422          * This function should emulate its namesake system call exactly.
423          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
424          * @param addr The client IP address and port
425          * @param addrlen The size of the sockaddr parameter.
426          * @return This method should return exactly the same values as the system call it emulates.
427          */
428         static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
429
430         /** Close the underlying fd of an event handler, remove it from the socket engine and set the fd to -1.
431          * @param eh The EventHandler to close.
432          * @return 0 on success, a negative value on error
433          */
434         static int Close(EventHandler* eh);
435
436         /** Abstraction for BSD sockets close(2).
437          * This function should emulate its namesake system call exactly.
438          * This function should emulate its namesake system call exactly.
439          * @return This method should return exactly the same values as the system call it emulates.
440          */
441         static int Close(int fd);
442
443         /** Abstraction for BSD sockets send(2).
444          * This function should emulate its namesake system call exactly.
445          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
446          * @param buf The buffer in which the data that is sent is stored.
447          * @param len The size of the buffer.
448          * @param flags A flag value that controls the sending of the data.
449          * @return This method should return exactly the same values as the system call it emulates.
450          */
451         static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
452
453         /** Abstraction for vector write function writev().
454          * This function should emulate its namesake system call exactly.
455          * @param fd EventHandler to send data with
456          * @param iov Array of IOVectors containing the buffers to send and their lengths in the platform's
457          * native format.
458          * @param count Number of elements in iov.
459          * @return This method should return exactly the same values as the system call it emulates.
460          */
461         static int WriteV(EventHandler* fd, const IOVector* iov, int count);
462
463 #ifdef _WIN32
464         /** Abstraction for vector write function writev() that accepts a POSIX format iovec.
465          * This function should emulate its namesake system call exactly.
466          * @param fd EventHandler to send data with
467          * @param iov Array of iovecs containing the buffers to send and their lengths in POSIX format.
468          * @param count Number of elements in iov.
469          * @return This method should return exactly the same values as the system call it emulates.
470          */
471         static int WriteV(EventHandler* fd, const iovec* iov, int count);
472 #endif
473
474         /** Abstraction for BSD sockets recv(2).
475          * This function should emulate its namesake system call exactly.
476          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
477          * @param buf The buffer in which the data that is read is stored.
478          * @param len The size of the buffer.
479          * @param flags A flag value that controls the reception of the data.
480          * @return This method should return exactly the same values as the system call it emulates.
481          */
482         static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
483
484         /** Abstraction for BSD sockets recvfrom(2).
485          * This function should emulate its namesake system call exactly.
486          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
487          * @param buf The buffer in which the data that is read is stored.
488          * @param len The size of the buffer.
489          * @param flags A flag value that controls the reception of the data.
490          * @param from The remote IP address and port.
491          * @param fromlen The size of the from parameter.
492          * @return This method should return exactly the same values as the system call it emulates.
493          */
494         static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
495
496         /** Abstraction for BSD sockets sendto(2).
497          * This function should emulate its namesake system call exactly.
498          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
499          * @param buf The buffer in which the data that is sent is stored.
500          * @param len The size of the buffer.
501          * @param flags A flag value that controls the sending of the data.
502          * @param address The remote IP address and port.
503          * @return This method should return exactly the same values as the system call it emulates.
504          */
505         static int SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address);
506
507         /** Abstraction for BSD sockets connect(2).
508          * This function should emulate its namesake system call exactly.
509          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
510          * @param address The server IP address and port.
511          * @return This method should return exactly the same values as the system call it emulates.
512          */
513         static int Connect(EventHandler* fd, const irc::sockets::sockaddrs& address);
514
515         /** Make a file descriptor blocking.
516          * @param fd a file descriptor to set to blocking mode
517          * @return 0 on success, -1 on failure, errno is set appropriately.
518          */
519         static int Blocking(int fd);
520
521         /** Make a file descriptor nonblocking.
522          * @param fd A file descriptor to set to nonblocking mode
523          * @return 0 on success, -1 on failure, errno is set appropriately.
524          */
525         static int NonBlocking(int fd);
526
527         /** Abstraction for BSD sockets shutdown(2).
528          * This function should emulate its namesake system call exactly.
529          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
530          * @param how What part of the socket to shut down
531          * @return This method should return exactly the same values as the system call it emulates.
532          */
533         static int Shutdown(EventHandler* fd, int how);
534
535         /** Abstraction for BSD sockets shutdown(2).
536          * This function should emulate its namesake system call exactly.
537          * @return This method should return exactly the same values as the system call it emulates.
538          */
539         static int Shutdown(int fd, int how);
540
541         /** Abstraction for BSD sockets bind(2).
542          * This function should emulate its namesake system call exactly.
543          * @return This method should return exactly the same values as the system call it emulates.
544          */
545         static int Bind(int fd, const irc::sockets::sockaddrs& addr);
546
547         /** Abstraction for BSD sockets listen(2).
548          * This function should emulate its namesake system call exactly.
549          * @return This method should return exactly the same values as the system call it emulates.
550          */
551         static int Listen(int sockfd, int backlog);
552
553         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
554          */
555         static void SetReuse(int sockfd);
556
557         /** This function is called immediately after fork().
558          * Some socket engines (notably kqueue) cannot have their
559          * handles inherited by forked processes. This method
560          * allows for the socket engine to re-create its handle
561          * after the daemon forks as the socket engine is created
562          * long BEFORE the daemon forks.
563          * @return void, but it is acceptable for this function to bail back to
564          * the shell or operating system on fatal error.
565          */
566         static void RecoverFromFork();
567
568         /** Get data transfer and event statistics
569          */
570         static const Statistics& GetStats() { return stats; }
571
572         /** Should we ignore the error in errno?
573          * Checks EAGAIN and WSAEWOULDBLOCK
574          */
575         static bool IgnoreError();
576
577         /** Return the last socket related error. strrerror(errno) on *nix
578          */
579         static std::string LastError();
580
581         /** Returns the error for the given error num, strerror(errnum) on *nix
582          */
583         static std::string GetError(int errnum);
584 };
585
586 inline bool SocketEngine::IgnoreError()
587 {
588         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
589                 return true;
590
591 #ifdef _WIN32
592         if (WSAGetLastError() == WSAEWOULDBLOCK)
593                 return true;
594 #endif
595
596         return false;
597 }