]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Change all socketengine methods to be static
[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 /** Types of event an EventHandler may receive.
33  * EVENT_READ is a readable file descriptor,
34  * and EVENT_WRITE is a writeable file descriptor.
35  * EVENT_ERROR can always occur, and indicates
36  * a write error or read error on the socket,
37  * e.g. EOF condition or broken pipe.
38  */
39 enum EventType
40 {
41         /** Read event */
42         EVENT_READ      =       0,
43         /** Write event */
44         EVENT_WRITE     =       1,
45         /** Error event */
46         EVENT_ERROR     =       2
47 };
48
49 /**
50  * Event mask for SocketEngine events
51  */
52 enum EventMask
53 {
54         /** Do not test this socket for readability
55          */
56         FD_WANT_NO_READ = 0x1,
57         /** Give a read event at all times when reads will not block.
58          */
59         FD_WANT_POLL_READ = 0x2,
60         /** Give a read event when there is new data to read.
61          *
62          * An event MUST be sent if there is new data to be read, and the most
63          * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
64          * at any time there is data to be read on the socket.
65          */
66         FD_WANT_FAST_READ = 0x4,
67         /** Give an optional read event when reads begin to unblock
68          *
69          * This state is useful if you want to leave data in the OS receive
70          * queue but not get continuous event notifications about it, because
71          * it may not require a system call to transition from FD_WANT_FAST_READ
72          */
73         FD_WANT_EDGE_READ = 0x8,
74
75         /** Mask for all read events */
76         FD_WANT_READ_MASK = 0x0F,
77
78         /** Do not test this socket for writeability
79          */
80         FD_WANT_NO_WRITE = 0x10,
81         /** Give a write event at all times when writes will not block.
82          *
83          * You probably shouldn't use this state; if it's likely that the write
84          * will not block, try it first, then use FD_WANT_FAST_WRITE if it
85          * fails. If it's likely to block (or you are using polling-style reads)
86          * then use FD_WANT_SINGLE_WRITE.
87          */
88         FD_WANT_POLL_WRITE = 0x20,
89         /** Give a write event when writes don't block any more
90          *
91          * An event MUST be sent if writes will not block, and the most recent
92          * write/send() on this FD returned EAGAIN, or connect() returned
93          * EINPROGRESS. An event MAY be sent at any time that writes will not
94          * block.
95          *
96          * Before calling HandleEvent, a socket engine MAY change the state of
97          * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
98          * one-shot notification was registered). If further writes are needed,
99          * it is the responsibility of the event handler to change the state to
100          * one that will generate the required notifications
101          */
102         FD_WANT_FAST_WRITE = 0x40,
103         /** Give an optional write event on edge-triggered write unblock.
104          *
105          * This state is useful to avoid system calls when moving to/from
106          * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
107          */
108         FD_WANT_EDGE_WRITE = 0x80,
109         /** Request a one-shot poll-style write notification. The socket will
110          * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
111          */
112         FD_WANT_SINGLE_WRITE = 0x100,
113
114         /** Mask for all write events */
115         FD_WANT_WRITE_MASK = 0x1F0,
116
117         /** Add a trial read. During the next DispatchEvents invocation, this
118          * will call HandleEvent with EVENT_READ unless reads are known to be
119          * blocking.
120          */
121         FD_ADD_TRIAL_READ  = 0x1000,
122         /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
123          * Reset by SE before running EVENT_READ
124          */
125         FD_READ_WILL_BLOCK = 0x2000,
126
127         /** Add a trial write. During the next DispatchEvents invocation, this
128          * will call HandleEvent with EVENT_WRITE unless writes are known to be
129          * blocking.
130          *
131          * This could be used to group several writes together into a single
132          * send() syscall, or to ensure that writes are blocking when attempting
133          * to use FD_WANT_FAST_WRITE.
134          */
135         FD_ADD_TRIAL_WRITE = 0x4000,
136         /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
137          * Reset by SE before running EVENT_WRITE
138          */
139         FD_WRITE_WILL_BLOCK = 0x8000,
140
141         /** Mask for trial read/trial write */
142         FD_TRIAL_NOTE_MASK = 0x5000
143 };
144
145 /** This class is a basic I/O handler class.
146  * Any object which wishes to receive basic I/O events
147  * from the socketengine must derive from this class and
148  * implement the HandleEvent() method. The derived class
149  * must then be added to SocketEngine using the method
150  * SocketEngine::AddFd(), after which point the derived
151  * class will receive events to its HandleEvent() method.
152  * The derived class should also implement one of Readable()
153  * and Writeable(). In the current implementation, only
154  * Readable() is used. If this returns true, the socketengine
155  * inserts a readable socket. If it is false, the socketengine
156  * inserts a writeable socket. The derived class should never
157  * change the value this function returns without first
158  * deleting the socket from the socket engine. The only
159  * requirement beyond this for an event handler is that it
160  * must have a file descriptor. What this file descriptor
161  * is actually attached to is completely up to you.
162  */
163 class CoreExport EventHandler : public classbase
164 {
165  private:
166         /** Private state maintained by socket engine */
167         int event_mask;
168
169         void SetEventMask(int mask) { event_mask = mask; }
170
171  protected:
172         /** File descriptor.
173          * All events which can be handled must have a file descriptor.  This
174          * allows you to add events for sockets, fifo's, pipes, and various
175          * other forms of IPC.  Do not change this while the object is
176          * registered with the SocketEngine
177          */
178         int fd;
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         /** Process an I/O event.
203          * You MUST implement this function in your derived
204          * class, and it will be called whenever read or write
205          * events are received.
206          * @param et either one of EVENT_READ for read events,
207          * EVENT_WRITE for write events and EVENT_ERROR for
208          * error events.
209          * @param errornum The error code which goes with an EVENT_ERROR.
210          */
211         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
212
213         friend class SocketEngine;
214 };
215
216 /** Provides basic file-descriptor-based I/O support.
217  * The actual socketengine class presents the
218  * same interface on all operating systems, but
219  * its private members and internal behaviour
220  * should be treated as blackboxed, and vary
221  * from system to system and upon the config
222  * settings chosen by the server admin. The current
223  * version supports select, epoll and kqueue.
224  * The configure script will enable a socket engine
225  * based upon what OS is detected, and will derive
226  * a class from SocketEngine based upon what it finds.
227  * The derived classes file will also implement a
228  * classfactory, SocketEngineFactory, which will
229  * create a derived instance of SocketEngine using
230  * polymorphism so that the core and modules do not
231  * have to be aware of which SocketEngine derived
232  * class they are using.
233  */
234 class CoreExport SocketEngine
235 {
236  public:
237         /** Socket engine statistics: count of various events, bandwidth usage
238          */
239         class Statistics
240         {
241                 mutable size_t indata;
242                 mutable size_t outdata;
243                 mutable time_t lastempty;
244
245                 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
246                  */
247                 void CheckFlush() const;
248
249          public:
250                 /** Constructor, initializes member vars except indata and outdata because those are set to 0
251                  * in CheckFlush() the first time Update() or GetBandwidth() is called.
252                  */
253                 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
254
255                 /** Increase the counters for bytes sent/received in this second.
256                  * @param len_in Bytes received, 0 if updating number of bytes written.
257                  * @param len_out Bytes sent, 0 if updating number of bytes read.
258                  */
259                 void Update(size_t len_in, size_t 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         /** Constructor.
310          * The constructor transparently initializes
311          * the socket engine which the ircd is using.
312          * Please note that if there is a catastrophic
313          * failure (for example, you try and enable
314          * epoll on a 2.4 linux kernel) then this
315          * function may bail back to the shell.
316          * @return void, but it is acceptable for this function to bail back to
317          * the shell or operating system on fatal error.
318          */
319         static void Init();
320
321         /** Destructor.
322          * The destructor transparently tidies up
323          * any resources used by the socket engine.
324          */
325         static void Deinit();
326
327         /** Add an EventHandler object to the engine.  Use AddFd to add a file
328          * descriptor to the engine and have the socket engine monitor it. You
329          * must provide an object derived from EventHandler which implements
330          * HandleEvent().
331          * @param eh An event handling object to add
332          * @param event_mask The initial event mask for the object
333          */
334         static bool AddFd(EventHandler* eh, int event_mask);
335
336         /** If you call this function and pass it an
337          * event handler, that event handler will
338          * receive the next available write event,
339          * even if the socket is a readable socket only.
340          * Developers should avoid constantly keeping
341          * an eventhandler in the writeable state,
342          * as this will consume large amounts of
343          * CPU time.
344          * @param eh The event handler to change
345          * @param event_mask The changes to make to the wait state
346          */
347         static void ChangeEventMask(EventHandler* eh, int event_mask);
348
349         /** Returns the highest file descriptor you may store in the socket engine
350          * @return The maximum fd value
351          */
352         static int GetMaxFds() { return MAX_DESCRIPTORS; }
353
354         /** Returns the number of file descriptors being queried
355          * @return The set size
356          */
357         static size_t GetUsedFds() { return CurrentSetSize; }
358
359         /** Delete an event handler from the engine.
360          * This function call deletes an EventHandler
361          * from the engine, returning true if it succeeded
362          * and false if it failed. This does not free the
363          * EventHandler pointer using delete, if this is
364          * required you must do this yourself.
365          * @param eh The event handler object to remove
366          */
367         static void DelFd(EventHandler* eh);
368
369         /** Returns true if a file descriptor exists in
370          * the socket engine's list.
371          * @param fd The event handler to look for
372          * @return True if this fd has an event handler
373          */
374         static bool HasFd(int fd);
375
376         /** Returns the EventHandler attached to a specific fd.
377          * If the fd isnt in the socketengine, returns NULL.
378          * @param fd The event handler to look for
379          * @return A pointer to the event handler, or NULL
380          */
381         static EventHandler* GetRef(int fd);
382
383         /** Waits for events and dispatches them to handlers.  Please note that
384          * this doesn't wait long, only a couple of milliseconds. It returns the
385          * number of events which occurred during this call.  This method will
386          * dispatch events to their handlers by calling their
387          * EventHandler::HandleEvent() methods with the necessary EventType
388          * value.
389          * @return The number of events which have occured.
390          */
391         static int DispatchEvents();
392
393         /** Dispatch trial reads and writes. This causes the actual socket I/O
394          * to happen when writes have been pre-buffered.
395          */
396         static void DispatchTrialWrites();
397
398         /** Returns true if the file descriptors in the given event handler are
399          * within sensible ranges which can be handled by the socket engine.
400          */
401         static bool BoundsCheckFd(EventHandler* eh);
402
403         /** Abstraction for BSD sockets accept(2).
404          * This function should emulate its namesake system call exactly.
405          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
406          * @param addr The client IP address and port
407          * @param addrlen The size of the sockaddr parameter.
408          * @return This method should return exactly the same values as the system call it emulates.
409          */
410         static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
411
412         /** Abstraction for BSD sockets close(2).
413          * This function should emulate its namesake system call exactly.
414          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
415          * @return This method should return exactly the same values as the system call it emulates.
416          */
417         static int Close(EventHandler* fd);
418
419         /** Abstraction for BSD sockets close(2).
420          * This function should emulate its namesake system call exactly.
421          * This function should emulate its namesake system call exactly.
422          * @return This method should return exactly the same values as the system call it emulates.
423          */
424         static int Close(int fd);
425
426         /** Abstraction for BSD sockets send(2).
427          * This function should emulate its namesake system call exactly.
428          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
429          * @param buf The buffer in which the data that is sent is stored.
430          * @param len The size of the buffer.
431          * @param flags A flag value that controls the sending of the data.
432          * @return This method should return exactly the same values as the system call it emulates.
433          */
434         static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
435
436         /** Abstraction for BSD sockets recv(2).
437          * This function should emulate its namesake system call exactly.
438          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
439          * @param buf The buffer in which the data that is read is stored.
440          * @param len The size of the buffer.
441          * @param flags A flag value that controls the reception of the data.
442          * @return This method should return exactly the same values as the system call it emulates.
443          */
444         static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
445
446         /** Abstraction for BSD sockets recvfrom(2).
447          * This function should emulate its namesake system call exactly.
448          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
449          * @param buf The buffer in which the data that is read is stored.
450          * @param len The size of the buffer.
451          * @param flags A flag value that controls the reception of the data.
452          * @param from The remote IP address and port.
453          * @param fromlen The size of the from parameter.
454          * @return This method should return exactly the same values as the system call it emulates.
455          */
456         static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
457
458         /** Abstraction for BSD sockets sendto(2).
459          * This function should emulate its namesake system call exactly.
460          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
461          * @param buf The buffer in which the data that is sent is stored.
462          * @param len The size of the buffer.
463          * @param flags A flag value that controls the sending of the data.
464          * @param to The remote IP address and port.
465          * @param tolen The size of the to parameter.
466          * @return This method should return exactly the same values as the system call it emulates.
467          */
468         static int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
469
470         /** Abstraction for BSD sockets connect(2).
471          * This function should emulate its namesake system call exactly.
472          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
473          * @param serv_addr The server IP address and port.
474          * @param addrlen The size of the sockaddr parameter.
475          * @return This method should return exactly the same values as the system call it emulates.
476          */
477         static int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
478
479         /** Make a file descriptor blocking.
480          * @param fd a file descriptor to set to blocking mode
481          * @return 0 on success, -1 on failure, errno is set appropriately.
482          */
483         static int Blocking(int fd);
484
485         /** Make a file descriptor nonblocking.
486          * @param fd A file descriptor to set to nonblocking mode
487          * @return 0 on success, -1 on failure, errno is set appropriately.
488          */
489         static int NonBlocking(int fd);
490
491         /** Abstraction for BSD sockets shutdown(2).
492          * This function should emulate its namesake system call exactly.
493          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
494          * @param how What part of the socket to shut down
495          * @return This method should return exactly the same values as the system call it emulates.
496          */
497         static int Shutdown(EventHandler* fd, int how);
498
499         /** Abstraction for BSD sockets shutdown(2).
500          * This function should emulate its namesake system call exactly.
501          * @return This method should return exactly the same values as the system call it emulates.
502          */
503         static int Shutdown(int fd, int how);
504
505         /** Abstraction for BSD sockets bind(2).
506          * This function should emulate its namesake system call exactly.
507          * @return This method should return exactly the same values as the system call it emulates.
508          */
509         static int Bind(int fd, const irc::sockets::sockaddrs& addr);
510
511         /** Abstraction for BSD sockets listen(2).
512          * This function should emulate its namesake system call exactly.
513          * @return This method should return exactly the same values as the system call it emulates.
514          */
515         static int Listen(int sockfd, int backlog);
516
517         /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
518          */
519         static void SetReuse(int sockfd);
520
521         /** This function is called immediately after fork().
522          * Some socket engines (notably kqueue) cannot have their
523          * handles inherited by forked processes. This method
524          * allows for the socket engine to re-create its handle
525          * after the daemon forks as the socket engine is created
526          * long BEFORE the daemon forks.
527          * @return void, but it is acceptable for this function to bail back to
528          * the shell or operating system on fatal error.
529          */
530         static void RecoverFromFork();
531
532         /** Get data transfer and event statistics
533          */
534         static const Statistics& GetStats() { return stats; }
535
536         /** Should we ignore the error in errno?
537          * Checks EAGAIN and WSAEWOULDBLOCK
538          */
539         static bool IgnoreError();
540
541         /** Return the last socket related error. strrerror(errno) on *nix
542          */
543         static std::string LastError();
544
545         /** Returns the error for the given error num, strerror(errnum) on *nix
546          */
547         static std::string GetError(int errnum);
548 };
549
550 inline bool SocketEngine::IgnoreError()
551 {
552         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
553                 return true;
554
555 #ifdef _WIN32
556         if (WSAGetLastError() == WSAEWOULDBLOCK)
557                 return true;
558 #endif
559
560         return false;
561 }