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