]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/socketengine.h
Add SocketEngine::WriteV()
[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 /** Types of event an EventHandler may receive.
41  * EVENT_READ is a readable file descriptor,
42  * and EVENT_WRITE is a writeable file descriptor.
43  * EVENT_ERROR can always occur, and indicates
44  * a write error or read error on the socket,
45  * e.g. EOF condition or broken pipe.
46  */
47 enum EventType
48 {
49         /** Read event */
50         EVENT_READ      =       0,
51         /** Write event */
52         EVENT_WRITE     =       1,
53         /** Error event */
54         EVENT_ERROR     =       2
55 };
56
57 /**
58  * Event mask for SocketEngine events
59  */
60 enum EventMask
61 {
62         /** Do not test this socket for readability
63          */
64         FD_WANT_NO_READ = 0x1,
65         /** Give a read event at all times when reads will not block.
66          */
67         FD_WANT_POLL_READ = 0x2,
68         /** Give a read event when there is new data to read.
69          *
70          * An event MUST be sent if there is new data to be read, and the most
71          * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
72          * at any time there is data to be read on the socket.
73          */
74         FD_WANT_FAST_READ = 0x4,
75         /** Give an optional read event when reads begin to unblock
76          *
77          * This state is useful if you want to leave data in the OS receive
78          * queue but not get continuous event notifications about it, because
79          * it may not require a system call to transition from FD_WANT_FAST_READ
80          */
81         FD_WANT_EDGE_READ = 0x8,
82
83         /** Mask for all read events */
84         FD_WANT_READ_MASK = 0x0F,
85
86         /** Do not test this socket for writeability
87          */
88         FD_WANT_NO_WRITE = 0x10,
89         /** Give a write event at all times when writes will not block.
90          *
91          * You probably shouldn't use this state; if it's likely that the write
92          * will not block, try it first, then use FD_WANT_FAST_WRITE if it
93          * fails. If it's likely to block (or you are using polling-style reads)
94          * then use FD_WANT_SINGLE_WRITE.
95          */
96         FD_WANT_POLL_WRITE = 0x20,
97         /** Give a write event when writes don't block any more
98          *
99          * An event MUST be sent if writes will not block, and the most recent
100          * write/send() on this FD returned EAGAIN, or connect() returned
101          * EINPROGRESS. An event MAY be sent at any time that writes will not
102          * block.
103          *
104          * Before calling HandleEvent, a socket engine MAY change the state of
105          * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
106          * one-shot notification was registered). If further writes are needed,
107          * it is the responsibility of the event handler to change the state to
108          * one that will generate the required notifications
109          */
110         FD_WANT_FAST_WRITE = 0x40,
111         /** Give an optional write event on edge-triggered write unblock.
112          *
113          * This state is useful to avoid system calls when moving to/from
114          * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
115          */
116         FD_WANT_EDGE_WRITE = 0x80,
117         /** Request a one-shot poll-style write notification. The socket will
118          * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
119          */
120         FD_WANT_SINGLE_WRITE = 0x100,
121
122         /** Mask for all write events */
123         FD_WANT_WRITE_MASK = 0x1F0,
124
125         /** Add a trial read. During the next DispatchEvents invocation, this
126          * will call HandleEvent with EVENT_READ unless reads are known to be
127          * blocking.
128          */
129         FD_ADD_TRIAL_READ  = 0x1000,
130         /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
131          * Reset by SE before running EVENT_READ
132          */
133         FD_READ_WILL_BLOCK = 0x2000,
134
135         /** Add a trial write. During the next DispatchEvents invocation, this
136          * will call HandleEvent with EVENT_WRITE unless writes are known to be
137          * blocking.
138          *
139          * This could be used to group several writes together into a single
140          * send() syscall, or to ensure that writes are blocking when attempting
141          * to use FD_WANT_FAST_WRITE.
142          */
143         FD_ADD_TRIAL_WRITE = 0x4000,
144         /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
145          * Reset by SE before running EVENT_WRITE
146          */
147         FD_WRITE_WILL_BLOCK = 0x8000,
148
149         /** Mask for trial read/trial write */
150         FD_TRIAL_NOTE_MASK = 0x5000
151 };
152
153 /** This class is a basic I/O handler class.
154  * Any object which wishes to receive basic I/O events
155  * from the socketengine must derive from this class and
156  * implement the HandleEvent() method. The derived class
157  * must then be added to SocketEngine using the method
158  * SocketEngine::AddFd(), after which point the derived
159  * class will receive events to its HandleEvent() method.
160  * The derived class should also implement one of Readable()
161  * and Writeable(). In the current implementation, only
162  * Readable() is used. If this returns true, the socketengine
163  * inserts a readable socket. If it is false, the socketengine
164  * inserts a writeable socket. The derived class should never
165  * change the value this function returns without first
166  * deleting the socket from the socket engine. The only
167  * requirement beyond this for an event handler is that it
168  * must have a file descriptor. What this file descriptor
169  * is actually attached to is completely up to you.
170  */
171 class CoreExport EventHandler : public classbase
172 {
173  private:
174         /** Private state maintained by socket engine */
175         int event_mask;
176
177         void SetEventMask(int mask) { event_mask = mask; }
178
179  protected:
180         /** File descriptor.
181          * All events which can be handled must have a file descriptor.  This
182          * allows you to add events for sockets, fifo's, pipes, and various
183          * other forms of IPC.  Do not change this while the object is
184          * registered with the SocketEngine
185          */
186         int fd;
187  public:
188         /** Get the current file descriptor
189          * @return The file descriptor of this handler
190          */
191         inline int GetFd() const { return fd; }
192
193         inline int GetEventMask() const { return event_mask; }
194
195         /** Set a new file desciptor
196          * @param FD The new file descriptor. Do not call this method without
197          * first deleting the object from the SocketEngine if you have
198          * added it to a SocketEngine instance.
199          */
200         void SetFd(int FD);
201
202         /** Constructor
203          */
204         EventHandler();
205
206         /** Destructor
207          */
208         virtual ~EventHandler() {}
209
210         /** Process an I/O event.
211          * You MUST implement this function in your derived
212          * class, and it will be called whenever read or write
213          * events are received.
214          * @param et either one of EVENT_READ for read events,
215          * EVENT_WRITE for write events and EVENT_ERROR for
216          * error events.
217          * @param errornum The error code which goes with an EVENT_ERROR.
218          */
219         virtual void HandleEvent(EventType et, int errornum = 0) = 0;
220
221         friend class SocketEngine;
222 };
223
224 /** Provides basic file-descriptor-based I/O support.
225  * The actual socketengine class presents the
226  * same interface on all operating systems, but
227  * its private members and internal behaviour
228  * should be treated as blackboxed, and vary
229  * from system to system and upon the config
230  * settings chosen by the server admin. The current
231  * version supports select, epoll and kqueue.
232  * The configure script will enable a socket engine
233  * based upon what OS is detected, and will derive
234  * a class from SocketEngine based upon what it finds.
235  * The derived classes file will also implement a
236  * classfactory, SocketEngineFactory, which will
237  * create a derived instance of SocketEngine using
238  * polymorphism so that the core and modules do not
239  * have to be aware of which SocketEngine derived
240  * class they are using.
241  */
242 class CoreExport SocketEngine
243 {
244  public:
245         /** Socket engine statistics: count of various events, bandwidth usage
246          */
247         class Statistics
248         {
249                 mutable size_t indata;
250                 mutable size_t outdata;
251                 mutable time_t lastempty;
252
253                 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
254                  */
255                 void CheckFlush() const;
256
257          public:
258                 /** Constructor, initializes member vars except indata and outdata because those are set to 0
259                  * in CheckFlush() the first time Update() or GetBandwidth() is called.
260                  */
261                 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
262
263                 /** Increase the counters for bytes sent/received in this second.
264                  * @param len_in Bytes received, 0 if updating number of bytes written.
265                  * @param len_out Bytes sent, 0 if updating number of bytes read.
266                  */
267                 void Update(size_t len_in, size_t len_out);
268
269                 /** Get data transfer statistics.
270                  * @param kbitspersec_in Filled with incoming traffic in this second in kbit/s.
271                  * @param kbitspersec_out Filled with outgoing traffic in this second in kbit/s.
272                  * @param kbitspersec_total Filled with total traffic in this second in kbit/s.
273                  */
274                 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
275
276                 unsigned long TotalEvents;
277                 unsigned long ReadEvents;
278                 unsigned long WriteEvents;
279                 unsigned long ErrorEvents;
280         };
281
282  private:
283         /** Reference table, contains all current handlers
284          **/
285         static std::vector<EventHandler*> ref;
286
287  protected:
288         /** Current number of descriptors in the engine
289          */
290         static size_t CurrentSetSize;
291         /** List of handlers that want a trial read/write
292          */
293         static std::set<int> trials;
294
295         static int MAX_DESCRIPTORS;
296
297         /** Socket engine statistics: count of various events, bandwidth usage
298          */
299         static Statistics stats;
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(vect.size() * 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          * HandleEvent().
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 positive, the number of file descriptors that the system reported that we
366          * may use. Otherwise (<= 0) this number could not be determined.
367          */
368         static int GetMaxFds() { return MAX_DESCRIPTORS; }
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::HandleEvent() methods with the necessary EventType
404          * value.
405          * @return The number of events which have occured.
406          */
407         static int DispatchEvents();
408
409         /** Dispatch trial reads and writes. This causes the actual socket I/O
410          * to happen when writes have been pre-buffered.
411          */
412         static void DispatchTrialWrites();
413
414         /** Returns true if the file descriptors in the given event handler are
415          * within sensible ranges which can be handled by the socket engine.
416          */
417         static bool BoundsCheckFd(EventHandler* eh);
418
419         /** Abstraction for BSD sockets accept(2).
420          * This function should emulate its namesake system call exactly.
421          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
422          * @param addr The client IP address and port
423          * @param addrlen The size of the sockaddr parameter.
424          * @return This method should return exactly the same values as the system call it emulates.
425          */
426         static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
427
428         /** Close the underlying fd of an event handler, remove it from the socket engine and set the fd to -1.
429          * @param eh The EventHandler to close.
430          * @return 0 on success, a negative value on error
431          */
432         static int Close(EventHandler* eh);
433
434         /** Abstraction for BSD sockets close(2).
435          * This function should emulate its namesake system call exactly.
436          * This function should emulate its namesake system call exactly.
437          * @return This method should return exactly the same values as the system call it emulates.
438          */
439         static int Close(int fd);
440
441         /** Abstraction for BSD sockets send(2).
442          * This function should emulate its namesake system call exactly.
443          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
444          * @param buf The buffer in which the data that is sent is stored.
445          * @param len The size of the buffer.
446          * @param flags A flag value that controls the sending of the data.
447          * @return This method should return exactly the same values as the system call it emulates.
448          */
449         static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
450
451         /** Abstraction for vector write function writev().
452          * This function should emulate its namesake system call exactly.
453          * @param fd EventHandler to send data with
454          * @param iov Array of IOVectors containing the buffers to send and their lengths in the platform's
455          * native format.
456          * @param count Number of elements in iov.
457          * @return This method should return exactly the same values as the system call it emulates.
458          */
459         static int WriteV(EventHandler* fd, const IOVector* iov, int count);
460
461 #ifdef _WIN32
462         /** Abstraction for vector write function writev() that accepts a POSIX format iovec.
463          * This function should emulate its namesake system call exactly.
464          * @param fd EventHandler to send data with
465          * @param iov Array of iovecs containing the buffers to send and their lengths in POSIX format.
466          * @param count Number of elements in iov.
467          * @return This method should return exactly the same values as the system call it emulates.
468          */
469         static int WriteV(EventHandler* fd, const iovec* iov, int count);
470 #endif
471
472         /** Abstraction for BSD sockets recv(2).
473          * This function should emulate its namesake system call exactly.
474          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
475          * @param buf The buffer in which the data that is read is stored.
476          * @param len The size of the buffer.
477          * @param flags A flag value that controls the reception of the data.
478          * @return This method should return exactly the same values as the system call it emulates.
479          */
480         static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
481
482         /** Abstraction for BSD sockets recvfrom(2).
483          * This function should emulate its namesake system call exactly.
484          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
485          * @param buf The buffer in which the data that is read is stored.
486          * @param len The size of the buffer.
487          * @param flags A flag value that controls the reception of the data.
488          * @param from The remote IP address and port.
489          * @param fromlen The size of the from parameter.
490          * @return This method should return exactly the same values as the system call it emulates.
491          */
492         static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
493
494         /** Abstraction for BSD sockets sendto(2).
495          * This function should emulate its namesake system call exactly.
496          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
497          * @param buf The buffer in which the data that is sent is stored.
498          * @param len The size of the buffer.
499          * @param flags A flag value that controls the sending of the data.
500          * @param to The remote IP address and port.
501          * @param tolen The size of the to parameter.
502          * @return This method should return exactly the same values as the system call it emulates.
503          */
504         static int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
505
506         /** Abstraction for BSD sockets connect(2).
507          * This function should emulate its namesake system call exactly.
508          * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
509          * @param serv_addr The server IP address and port.
510          * @param addrlen The size of the sockaddr parameter.
511          * @return This method should return exactly the same values as the system call it emulates.
512          */
513         static int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
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 }