2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
41 * Event mask for SocketEngine events
45 /** Do not test this socket for readability
47 FD_WANT_NO_READ = 0x1,
48 /** Give a read event at all times when reads will not block.
50 FD_WANT_POLL_READ = 0x2,
51 /** Give a read event when there is new data to read.
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.
57 FD_WANT_FAST_READ = 0x4,
58 /** Give an optional read event when reads begin to unblock
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
64 FD_WANT_EDGE_READ = 0x8,
66 /** Mask for all read events */
67 FD_WANT_READ_MASK = 0x0F,
69 /** Do not test this socket for writeability
71 FD_WANT_NO_WRITE = 0x10,
72 /** Give a write event at all times when writes will not block.
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.
79 FD_WANT_POLL_WRITE = 0x20,
80 /** Give a write event when writes don't block any more
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
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
93 FD_WANT_FAST_WRITE = 0x40,
94 /** Give an optional write event on edge-triggered write unblock.
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.
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.
103 FD_WANT_SINGLE_WRITE = 0x100,
105 /** Mask for all write events */
106 FD_WANT_WRITE_MASK = 0x1F0,
108 /** Add a trial read. During the next DispatchEvents invocation, this
109 * will call OnEventHandlerRead() unless reads are known to be
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().
116 FD_READ_WILL_BLOCK = 0x2000,
118 /** Add a trial write. During the next DispatchEvents invocation, this
119 * will call OnEventHandlerWrite() unless writes are known to be
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.
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().
130 FD_WRITE_WILL_BLOCK = 0x8000,
132 /** Mask for trial read/trial write */
133 FD_TRIAL_NOTE_MASK = 0x5000
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.
151 class CoreExport EventHandler : public classbase
154 /** Private state maintained by socket engine */
157 void SetEventMask(int mask) { event_mask = mask; }
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
168 /** Get the current file descriptor
169 * @return The file descriptor of this handler
171 inline int GetFd() const { return fd; }
173 inline int GetEventMask() const { return event_mask; }
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.
188 virtual ~EventHandler() {}
190 /** Called by the socket engine in case of a read event
192 virtual void OnEventHandlerRead() = 0;
194 /** Called by the socket engine in case of a write event.
195 * The default implementation does nothing.
197 virtual void OnEventHandlerWrite();
199 /** Called by the socket engine in case of an error event.
200 * The default implementation does nothing.
201 * @param errornum Error code
203 virtual void OnEventHandlerError(int errornum);
205 friend class SocketEngine;
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.
226 class CoreExport SocketEngine
229 /** Socket engine statistics: count of various events, bandwidth usage
233 mutable size_t indata;
234 mutable size_t outdata;
235 mutable time_t lastempty;
237 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
239 void CheckFlush() const;
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.
245 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
247 /** Increase the counters for bytes sent/received in this second.
248 * @param len_in Bytes received, 0 if updating number of bytes written.
249 * @param len_out Bytes sent, 0 if updating number of bytes read.
251 void Update(size_t len_in, size_t len_out);
253 /** Get data transfer statistics.
254 * @param kbitspersec_in Filled with incoming traffic in this second in kbit/s.
255 * @param kbitspersec_out Filled with outgoing traffic in this second in kbit/s.
256 * @param kbitspersec_total Filled with total traffic in this second in kbit/s.
258 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
260 unsigned long TotalEvents;
261 unsigned long ReadEvents;
262 unsigned long WriteEvents;
263 unsigned long ErrorEvents;
267 /** Reference table, contains all current handlers
269 static std::vector<EventHandler*> ref;
272 /** Current number of descriptors in the engine
274 static size_t CurrentSetSize;
275 /** List of handlers that want a trial read/write
277 static std::set<int> trials;
279 static int MAX_DESCRIPTORS;
281 /** Socket engine statistics: count of various events, bandwidth usage
283 static Statistics stats;
285 static void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
287 /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
289 static bool AddFdRef(EventHandler* eh);
291 static void DelFdRef(EventHandler* eh);
293 template <typename T>
294 static void ResizeDouble(std::vector<T>& vect)
296 if (SocketEngine::CurrentSetSize > vect.size())
297 vect.resize(vect.size() * 2);
302 typedef iovec IOVector;
304 typedef WindowsIOVec IOVector;
308 * The constructor transparently initializes
309 * the socket engine which the ircd is using.
310 * Please note that if there is a catastrophic
311 * failure (for example, you try and enable
312 * epoll on a 2.4 linux kernel) then this
313 * function may bail back to the shell.
314 * @return void, but it is acceptable for this function to bail back to
315 * the shell or operating system on fatal error.
320 * The destructor transparently tidies up
321 * any resources used by the socket engine.
323 static void Deinit();
325 /** Add an EventHandler object to the engine. Use AddFd to add a file
326 * descriptor to the engine and have the socket engine monitor it. You
327 * must provide an object derived from EventHandler which implements
328 * the required OnEventHandler*() methods.
329 * @param eh An event handling object to add
330 * @param event_mask The initial event mask for the object
332 static bool AddFd(EventHandler* eh, int event_mask);
334 /** If you call this function and pass it an
335 * event handler, that event handler will
336 * receive the next available write event,
337 * even if the socket is a readable socket only.
338 * Developers should avoid constantly keeping
339 * an eventhandler in the writeable state,
340 * as this will consume large amounts of
342 * @param eh The event handler to change
343 * @param event_mask The changes to make to the wait state
345 static void ChangeEventMask(EventHandler* eh, int event_mask);
347 /** Returns the number of file descriptors reported by the system this program may use
348 * when it was started.
349 * @return If positive, the number of file descriptors that the system reported that we
350 * may use. Otherwise (<= 0) this number could not be determined.
352 static int GetMaxFds() { return MAX_DESCRIPTORS; }
354 /** Returns the number of file descriptors being queried
355 * @return The set size
357 static size_t GetUsedFds() { return CurrentSetSize; }
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
367 static void DelFd(EventHandler* eh);
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
374 static bool HasFd(int fd);
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
381 static EventHandler* GetRef(int fd);
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::OnEventHandler*() methods.
388 * @return The number of events which have occured.
390 static int DispatchEvents();
392 /** Dispatch trial reads and writes. This causes the actual socket I/O
393 * to happen when writes have been pre-buffered.
395 static void DispatchTrialWrites();
397 /** Returns true if the file descriptors in the given event handler are
398 * within sensible ranges which can be handled by the socket engine.
400 static bool BoundsCheckFd(EventHandler* eh);
402 /** Abstraction for BSD sockets accept(2).
403 * This function should emulate its namesake system call exactly.
404 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
405 * @param addr The client IP address and port
406 * @param addrlen The size of the sockaddr parameter.
407 * @return This method should return exactly the same values as the system call it emulates.
409 static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
411 /** Close the underlying fd of an event handler, remove it from the socket engine and set the fd to -1.
412 * @param eh The EventHandler to close.
413 * @return 0 on success, a negative value on error
415 static int Close(EventHandler* eh);
417 /** Abstraction for BSD sockets close(2).
418 * This function should emulate its namesake system call exactly.
419 * This function should emulate its namesake system call exactly.
420 * @return This method should return exactly the same values as the system call it emulates.
422 static int Close(int fd);
424 /** Abstraction for BSD sockets send(2).
425 * This function should emulate its namesake system call exactly.
426 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
427 * @param buf The buffer in which the data that is sent is stored.
428 * @param len The size of the buffer.
429 * @param flags A flag value that controls the sending of the data.
430 * @return This method should return exactly the same values as the system call it emulates.
432 static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
434 /** Abstraction for vector write function writev().
435 * This function should emulate its namesake system call exactly.
436 * @param fd EventHandler to send data with
437 * @param iov Array of IOVectors containing the buffers to send and their lengths in the platform's
439 * @param count Number of elements in iov.
440 * @return This method should return exactly the same values as the system call it emulates.
442 static int WriteV(EventHandler* fd, const IOVector* iov, int count);
445 /** Abstraction for vector write function writev() that accepts a POSIX format iovec.
446 * This function should emulate its namesake system call exactly.
447 * @param fd EventHandler to send data with
448 * @param iov Array of iovecs containing the buffers to send and their lengths in POSIX format.
449 * @param count Number of elements in iov.
450 * @return This method should return exactly the same values as the system call it emulates.
452 static int WriteV(EventHandler* fd, const iovec* iov, int count);
455 /** Abstraction for BSD sockets recv(2).
456 * This function should emulate its namesake system call exactly.
457 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
458 * @param buf The buffer in which the data that is read is stored.
459 * @param len The size of the buffer.
460 * @param flags A flag value that controls the reception of the data.
461 * @return This method should return exactly the same values as the system call it emulates.
463 static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
465 /** Abstraction for BSD sockets recvfrom(2).
466 * This function should emulate its namesake system call exactly.
467 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
468 * @param buf The buffer in which the data that is read is stored.
469 * @param len The size of the buffer.
470 * @param flags A flag value that controls the reception of the data.
471 * @param from The remote IP address and port.
472 * @param fromlen The size of the from parameter.
473 * @return This method should return exactly the same values as the system call it emulates.
475 static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
477 /** Abstraction for BSD sockets sendto(2).
478 * This function should emulate its namesake system call exactly.
479 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
480 * @param buf The buffer in which the data that is sent is stored.
481 * @param len The size of the buffer.
482 * @param flags A flag value that controls the sending of the data.
483 * @param to The remote IP address and port.
484 * @param tolen The size of the to parameter.
485 * @return This method should return exactly the same values as the system call it emulates.
487 static int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
489 /** Abstraction for BSD sockets connect(2).
490 * This function should emulate its namesake system call exactly.
491 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
492 * @param serv_addr The server IP address and port.
493 * @param addrlen The size of the sockaddr parameter.
494 * @return This method should return exactly the same values as the system call it emulates.
496 static int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
498 /** Make a file descriptor blocking.
499 * @param fd a file descriptor to set to blocking mode
500 * @return 0 on success, -1 on failure, errno is set appropriately.
502 static int Blocking(int fd);
504 /** Make a file descriptor nonblocking.
505 * @param fd A file descriptor to set to nonblocking mode
506 * @return 0 on success, -1 on failure, errno is set appropriately.
508 static int NonBlocking(int fd);
510 /** Abstraction for BSD sockets shutdown(2).
511 * This function should emulate its namesake system call exactly.
512 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
513 * @param how What part of the socket to shut down
514 * @return This method should return exactly the same values as the system call it emulates.
516 static int Shutdown(EventHandler* fd, int how);
518 /** Abstraction for BSD sockets shutdown(2).
519 * This function should emulate its namesake system call exactly.
520 * @return This method should return exactly the same values as the system call it emulates.
522 static int Shutdown(int fd, int how);
524 /** Abstraction for BSD sockets bind(2).
525 * This function should emulate its namesake system call exactly.
526 * @return This method should return exactly the same values as the system call it emulates.
528 static int Bind(int fd, const irc::sockets::sockaddrs& addr);
530 /** Abstraction for BSD sockets listen(2).
531 * This function should emulate its namesake system call exactly.
532 * @return This method should return exactly the same values as the system call it emulates.
534 static int Listen(int sockfd, int backlog);
536 /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
538 static void SetReuse(int sockfd);
540 /** This function is called immediately after fork().
541 * Some socket engines (notably kqueue) cannot have their
542 * handles inherited by forked processes. This method
543 * allows for the socket engine to re-create its handle
544 * after the daemon forks as the socket engine is created
545 * long BEFORE the daemon forks.
546 * @return void, but it is acceptable for this function to bail back to
547 * the shell or operating system on fatal error.
549 static void RecoverFromFork();
551 /** Get data transfer and event statistics
553 static const Statistics& GetStats() { return stats; }
555 /** Should we ignore the error in errno?
556 * Checks EAGAIN and WSAEWOULDBLOCK
558 static bool IgnoreError();
560 /** Return the last socket related error. strrerror(errno) on *nix
562 static std::string LastError();
564 /** Returns the error for the given error num, strerror(errnum) on *nix
566 static std::string GetError(int errnum);
569 inline bool SocketEngine::IgnoreError()
571 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
575 if (WSAGetLastError() == WSAEWOULDBLOCK)