2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
5 * Copyright (C) 2013-2014 Adam <Adam@anope.org>
6 * Copyright (C) 2012-2013, 2017-2020 Sadie Powell <sadie@witchery.services>
7 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
8 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
9 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
10 * Copyright (C) 2007-2008, 2017 Robin Burchell <robin+git@viroteck.net>
11 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
12 * Copyright (C) 2005-2008 Craig Edwards <brain@inspircd.org>
14 * This file is part of InspIRCd. InspIRCd is free software: you can
15 * redistribute it and/or modify it under the terms of the GNU General Public
16 * License as published by the Free Software Foundation, version 2.
18 * This program is distributed in the hope that it will be useful, but WITHOUT
19 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 * Event mask for SocketEngine events
47 /** Do not test this socket for readability
49 FD_WANT_NO_READ = 0x1,
50 /** Give a read event at all times when reads will not block.
52 FD_WANT_POLL_READ = 0x2,
53 /** Give a read event when there is new data to read.
55 * An event MUST be sent if there is new data to be read, and the most
56 * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
57 * at any time there is data to be read on the socket.
59 FD_WANT_FAST_READ = 0x4,
60 /** Give an optional read event when reads begin to unblock
62 * This state is useful if you want to leave data in the OS receive
63 * queue but not get continuous event notifications about it, because
64 * it may not require a system call to transition from FD_WANT_FAST_READ
66 FD_WANT_EDGE_READ = 0x8,
68 /** Mask for all read events */
69 FD_WANT_READ_MASK = 0x0F,
71 /** Do not test this socket for writeability
73 FD_WANT_NO_WRITE = 0x10,
74 /** Give a write event at all times when writes will not block.
76 * You probably shouldn't use this state; if it's likely that the write
77 * will not block, try it first, then use FD_WANT_FAST_WRITE if it
78 * fails. If it's likely to block (or you are using polling-style reads)
79 * then use FD_WANT_SINGLE_WRITE.
81 FD_WANT_POLL_WRITE = 0x20,
82 /** Give a write event when writes don't block any more
84 * An event MUST be sent if writes will not block, and the most recent
85 * write/send() on this FD returned EAGAIN, or connect() returned
86 * EINPROGRESS. An event MAY be sent at any time that writes will not
89 * Before calling OnEventHandler*(), a socket engine MAY change the state of
90 * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
91 * one-shot notification was registered). If further writes are needed,
92 * it is the responsibility of the event handler to change the state to
93 * one that will generate the required notifications
95 FD_WANT_FAST_WRITE = 0x40,
96 /** Give an optional write event on edge-triggered write unblock.
98 * This state is useful to avoid system calls when moving to/from
99 * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
101 FD_WANT_EDGE_WRITE = 0x80,
102 /** Request a one-shot poll-style write notification. The socket will
103 * return to the FD_WANT_NO_WRITE state before OnEventHandler*() is called.
105 FD_WANT_SINGLE_WRITE = 0x100,
107 /** Mask for all write events */
108 FD_WANT_WRITE_MASK = 0x1F0,
110 /** Add a trial read. During the next DispatchEvents invocation, this
111 * will call OnEventHandlerRead() unless reads are known to be
114 FD_ADD_TRIAL_READ = 0x1000,
115 /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
116 * Reset by SE before running OnEventHandlerRead().
118 FD_READ_WILL_BLOCK = 0x2000,
120 /** Add a trial write. During the next DispatchEvents invocation, this
121 * will call OnEventHandlerWrite() unless writes are known to be
124 * This could be used to group several writes together into a single
125 * send() syscall, or to ensure that writes are blocking when attempting
126 * to use FD_WANT_FAST_WRITE.
128 FD_ADD_TRIAL_WRITE = 0x4000,
129 /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
130 * Reset by SE before running OnEventHandlerWrite().
132 FD_WRITE_WILL_BLOCK = 0x8000,
134 /** Mask for trial read/trial write */
135 FD_TRIAL_NOTE_MASK = 0x5000
138 /** This class is a basic I/O handler class.
139 * Any object which wishes to receive basic I/O events
140 * from the socketengine must derive from this class and
141 * implement the OnEventHandler*() methods. The derived class
142 * must then be added to SocketEngine using the method
143 * SocketEngine::AddFd(), after which point the derived
144 * class will receive events to its OnEventHandler*() methods.
145 * The event mask passed to SocketEngine::AddFd() determines
146 * what events the EventHandler gets notified about and with
147 * what semantics. SocketEngine::ChangeEventMask() can be
148 * called to update the event mask later. The only
149 * requirement beyond this for an event handler is that it
150 * must have a file descriptor. What this file descriptor
151 * is actually attached to is completely up to you.
153 class CoreExport EventHandler : public classbase
156 /** Private state maintained by socket engine */
159 void SetEventMask(int mask) { event_mask = mask; }
163 * All events which can be handled must have a file descriptor. This
164 * allows you to add events for sockets, fifo's, pipes, and various
165 * other forms of IPC. Do not change this while the object is
166 * registered with the SocketEngine
170 /** Swaps the internals of this EventHandler with another one.
171 * @param other A EventHandler to swap internals with.
173 void SwapInternals(EventHandler& other);
176 /** Get the current file descriptor
177 * @return The file descriptor of this handler
179 inline int GetFd() const { return fd; }
181 /** Checks if this event handler has a fd associated with it. */
182 inline bool HasFd() const { return fd >= 0; }
184 inline int GetEventMask() const { return event_mask; }
186 /** Set a new file descriptor
187 * @param FD The new file descriptor. Do not call this method without
188 * first deleting the object from the SocketEngine if you have
189 * added it to a SocketEngine instance.
199 virtual ~EventHandler() {}
201 /** Called by the socket engine in case of a read event
203 virtual void OnEventHandlerRead() = 0;
205 /** Called by the socket engine in case of a write event.
206 * The default implementation does nothing.
208 virtual void OnEventHandlerWrite();
210 /** Called by the socket engine in case of an error event.
211 * The default implementation does nothing.
212 * @param errornum Error code
214 virtual void OnEventHandlerError(int errornum);
216 friend class SocketEngine;
219 /** Provides basic file-descriptor-based I/O support.
220 * The actual socketengine class presents the
221 * same interface on all operating systems, but
222 * its private members and internal behaviour
223 * should be treated as blackboxed, and vary
224 * from system to system and upon the config
225 * settings chosen by the server admin.
227 class CoreExport SocketEngine
230 /** Socket engine statistics: count of various events, bandwidth usage
234 mutable size_t indata;
235 mutable size_t outdata;
236 mutable time_t lastempty;
238 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
240 void CheckFlush() const;
243 /** Constructor, initializes member vars except indata and outdata because those are set to 0
244 * in CheckFlush() the first time Update() or GetBandwidth() is called.
246 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
248 /** Update counters for network data received.
249 * This should be called after every read-type syscall.
250 * @param len_in Number of bytes received, or -1 for error, as typically
251 * returned by a read-style syscall.
253 void UpdateReadCounters(int len_in);
255 /** Update counters for network data sent.
256 * This should be called after every write-type syscall.
257 * @param len_out Number of bytes sent, or -1 for error, as typically
258 * returned by a read-style syscall.
260 void UpdateWriteCounters(int len_out);
262 /** Get data transfer statistics.
263 * @param kbitpersec_in Filled with incoming traffic in this second in kbit/s.
264 * @param kbitpersec_out Filled with outgoing traffic in this second in kbit/s.
265 * @param kbitpersec_total Filled with total traffic in this second in kbit/s.
267 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
269 unsigned long TotalEvents;
270 unsigned long ReadEvents;
271 unsigned long WriteEvents;
272 unsigned long ErrorEvents;
276 /** Reference table, contains all current handlers
278 static std::vector<EventHandler*> ref;
280 /** Current number of descriptors in the engine. */
281 static size_t CurrentSetSize;
283 /** The maximum number of descriptors in the engine. */
284 static size_t MaxSetSize;
286 /** List of handlers that want a trial read/write
288 static std::set<int> trials;
290 /** Socket engine statistics: count of various events, bandwidth usage
292 static Statistics stats;
294 /** Look up the fd limit using rlimit. */
295 static void LookupMaxFds();
297 /** Terminates the program when the socket engine fails to initialize. */
298 static void InitError();
300 static void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
302 /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
304 static bool AddFdRef(EventHandler* eh);
306 static void DelFdRef(EventHandler* eh);
308 template <typename T>
309 static void ResizeDouble(std::vector<T>& vect)
311 if (SocketEngine::CurrentSetSize > vect.size())
312 vect.resize(SocketEngine::CurrentSetSize * 2);
317 typedef iovec IOVector;
319 typedef WindowsIOVec IOVector;
323 * The constructor transparently initializes
324 * the socket engine which the ircd is using.
325 * Please note that if there is a catastrophic
326 * failure (for example, you try and enable
327 * epoll on a 2.4 linux kernel) then this
328 * function may bail back to the shell.
329 * @return void, but it is acceptable for this function to bail back to
330 * the shell or operating system on fatal error.
335 * The destructor transparently tidies up
336 * any resources used by the socket engine.
338 static void Deinit();
340 /** Add an EventHandler object to the engine. Use AddFd to add a file
341 * descriptor to the engine and have the socket engine monitor it. You
342 * must provide an object derived from EventHandler which implements
343 * the required OnEventHandler*() methods.
344 * @param eh An event handling object to add
345 * @param event_mask The initial event mask for the object
347 static bool AddFd(EventHandler* eh, int event_mask);
349 /** If you call this function and pass it an
350 * event handler, that event handler will
351 * receive the next available write event,
352 * even if the socket is a readable socket only.
353 * Developers should avoid constantly keeping
354 * an eventhandler in the writeable state,
355 * as this will consume large amounts of
357 * @param eh The event handler to change
358 * @param event_mask The changes to make to the wait state
360 static void ChangeEventMask(EventHandler* eh, int event_mask);
362 /** Returns the number of file descriptors reported by the system this program may use
363 * when it was started.
364 * @return If non-zero the number of file descriptors that the system reported that we
367 static size_t GetMaxFds() { return MaxSetSize; }
369 /** Returns the number of file descriptors being queried
370 * @return The set size
372 static size_t GetUsedFds() { return CurrentSetSize; }
374 /** Delete an event handler from the engine.
375 * This function call deletes an EventHandler
376 * from the engine, returning true if it succeeded
377 * and false if it failed. This does not free the
378 * EventHandler pointer using delete, if this is
379 * required you must do this yourself.
380 * @param eh The event handler object to remove
382 static void DelFd(EventHandler* eh);
384 /** Returns true if a file descriptor exists in
385 * the socket engine's list.
386 * @param fd The event handler to look for
387 * @return True if this fd has an event handler
389 static bool HasFd(int fd);
391 /** Returns the EventHandler attached to a specific fd.
392 * If the fd isn't in the socketengine, returns NULL.
393 * @param fd The event handler to look for
394 * @return A pointer to the event handler, or NULL
396 static EventHandler* GetRef(int fd);
398 /** Waits for events and dispatches them to handlers. Please note that
399 * this doesn't wait long, only a couple of milliseconds. It returns the
400 * number of events which occurred during this call. This method will
401 * dispatch events to their handlers by calling their
402 * EventHandler::OnEventHandler*() methods.
403 * @return The number of events which have occurred.
405 static int DispatchEvents();
407 /** Dispatch trial reads and writes. This causes the actual socket I/O
408 * to happen when writes have been pre-buffered.
410 static void DispatchTrialWrites();
412 /** Returns true if the file descriptors in the given event handler are
413 * within sensible ranges which can be handled by the socket engine.
415 static bool BoundsCheckFd(EventHandler* eh);
417 /** Abstraction for BSD sockets accept(2).
418 * This function should emulate its namesake system call exactly.
419 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
420 * @param addr The client IP address and port
421 * @param addrlen The size of the sockaddr parameter.
422 * @return This method should return exactly the same values as the system call it emulates.
424 static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
426 /** Close the underlying fd of an event handler, remove it from the socket engine and set the fd to -1.
427 * @param eh The EventHandler to close.
428 * @return 0 on success, a negative value on error
430 static int Close(EventHandler* eh);
432 /** Abstraction for BSD sockets close(2).
433 * This function should emulate its namesake system call exactly.
434 * This function should emulate its namesake system call exactly.
435 * @return This method should return exactly the same values as the system call it emulates.
437 static int Close(int fd);
439 /** Abstraction for BSD sockets send(2).
440 * This function should emulate its namesake system call exactly.
441 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
442 * @param buf The buffer in which the data that is sent is stored.
443 * @param len The size of the buffer.
444 * @param flags A flag value that controls the sending of the data.
445 * @return This method should return exactly the same values as the system call it emulates.
447 static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
449 /** Abstraction for vector write function writev().
450 * This function should emulate its namesake system call exactly.
451 * @param fd EventHandler to send data with
452 * @param iov Array of IOVectors containing the buffers to send and their lengths in the platform's
454 * @param count Number of elements in iov.
455 * @return This method should return exactly the same values as the system call it emulates.
457 static int WriteV(EventHandler* fd, const IOVector* iov, int count);
460 /** Abstraction for vector write function writev() that accepts a POSIX format iovec.
461 * This function should emulate its namesake system call exactly.
462 * @param fd EventHandler to send data with
463 * @param iov Array of iovecs containing the buffers to send and their lengths in POSIX format.
464 * @param count Number of elements in iov.
465 * @return This method should return exactly the same values as the system call it emulates.
467 static int WriteV(EventHandler* fd, const iovec* iov, int count);
470 /** Abstraction for BSD sockets recv(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 buf The buffer in which the data that is read is stored.
474 * @param len The size of the buffer.
475 * @param flags A flag value that controls the reception of the data.
476 * @return This method should return exactly the same values as the system call it emulates.
478 static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
480 /** Abstraction for BSD sockets recvfrom(2).
481 * This function should emulate its namesake system call exactly.
482 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
483 * @param buf The buffer in which the data that is read is stored.
484 * @param len The size of the buffer.
485 * @param flags A flag value that controls the reception of the data.
486 * @param from The remote IP address and port.
487 * @param fromlen The size of the from parameter.
488 * @return This method should return exactly the same values as the system call it emulates.
490 static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
492 /** Abstraction for BSD sockets sendto(2).
493 * This function should emulate its namesake system call exactly.
494 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
495 * @param buf The buffer in which the data that is sent is stored.
496 * @param len The size of the buffer.
497 * @param flags A flag value that controls the sending of the data.
498 * @param address The remote IP address and port.
499 * @return This method should return exactly the same values as the system call it emulates.
501 static int SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address);
503 /** Abstraction for BSD sockets connect(2).
504 * This function should emulate its namesake system call exactly.
505 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
506 * @param address The server IP address and port.
507 * @return This method should return exactly the same values as the system call it emulates.
509 static int Connect(EventHandler* fd, const irc::sockets::sockaddrs& address);
511 /** Make a file descriptor blocking.
512 * @param fd a file descriptor to set to blocking mode
513 * @return 0 on success, -1 on failure, errno is set appropriately.
515 static int Blocking(int fd);
517 /** Make a file descriptor nonblocking.
518 * @param fd A file descriptor to set to nonblocking mode
519 * @return 0 on success, -1 on failure, errno is set appropriately.
521 static int NonBlocking(int fd);
523 /** Abstraction for BSD sockets shutdown(2).
524 * This function should emulate its namesake system call exactly.
525 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
526 * @param how What part of the socket to shut down
527 * @return This method should return exactly the same values as the system call it emulates.
529 static int Shutdown(EventHandler* fd, int how);
531 /** Abstraction for BSD sockets shutdown(2).
532 * This function should emulate its namesake system call exactly.
533 * @return This method should return exactly the same values as the system call it emulates.
535 static int Shutdown(int fd, int how);
537 /** Abstraction for BSD sockets bind(2).
538 * This function should emulate its namesake system call exactly.
539 * @return This method should return exactly the same values as the system call it emulates.
541 static int Bind(int fd, const irc::sockets::sockaddrs& addr);
543 /** Abstraction for BSD sockets listen(2).
544 * This function should emulate its namesake system call exactly.
545 * @return This method should return exactly the same values as the system call it emulates.
547 static int Listen(int sockfd, int backlog);
549 /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
551 static void SetReuse(int sockfd);
553 /** This function is called immediately after fork().
554 * Some socket engines (notably kqueue) cannot have their
555 * handles inherited by forked processes. This method
556 * allows for the socket engine to re-create its handle
557 * after the daemon forks as the socket engine is created
558 * long BEFORE the daemon forks.
559 * @return void, but it is acceptable for this function to bail back to
560 * the shell or operating system on fatal error.
562 static void RecoverFromFork();
564 /** Get data transfer and event statistics
566 static const Statistics& GetStats() { return stats; }
568 /** Should we ignore the error in errno?
569 * Checks EAGAIN and WSAEWOULDBLOCK
571 static bool IgnoreError();
573 /** Return the last socket related error. strrerror(errno) on *nix
575 static std::string LastError();
577 /** Returns the error for the given error num, strerror(errnum) on *nix
579 static std::string GetError(int errnum);
582 inline bool SocketEngine::IgnoreError()
584 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
588 if (WSAGetLastError() == WSAEWOULDBLOCK)