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