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-2019 Sadie Powell <sadie@witchery.services>
7 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
8 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
9 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
10 * Copyright (C) 2007-2008, 2017 Robin Burchell <robin+git@viroteck.net>
11 * Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
12 * Copyright (C) 2007 burlex <burlex@e03df62e-2008-0410-955e-edbf42e46eb7>
13 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
15 * This file is part of InspIRCd. InspIRCd is free software: you can
16 * redistribute it and/or modify it under the terms of the GNU General Public
17 * License as published by the Free Software Foundation, version 2.
19 * This program is distributed in the hope that it will be useful, but WITHOUT
20 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
47 * Event mask for SocketEngine events
51 /** Do not test this socket for readability
53 FD_WANT_NO_READ = 0x1,
54 /** Give a read event at all times when reads will not block.
56 FD_WANT_POLL_READ = 0x2,
57 /** Give a read event when there is new data to read.
59 * An event MUST be sent if there is new data to be read, and the most
60 * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
61 * at any time there is data to be read on the socket.
63 FD_WANT_FAST_READ = 0x4,
64 /** Give an optional read event when reads begin to unblock
66 * This state is useful if you want to leave data in the OS receive
67 * queue but not get continuous event notifications about it, because
68 * it may not require a system call to transition from FD_WANT_FAST_READ
70 FD_WANT_EDGE_READ = 0x8,
72 /** Mask for all read events */
73 FD_WANT_READ_MASK = 0x0F,
75 /** Do not test this socket for writeability
77 FD_WANT_NO_WRITE = 0x10,
78 /** Give a write event at all times when writes will not block.
80 * You probably shouldn't use this state; if it's likely that the write
81 * will not block, try it first, then use FD_WANT_FAST_WRITE if it
82 * fails. If it's likely to block (or you are using polling-style reads)
83 * then use FD_WANT_SINGLE_WRITE.
85 FD_WANT_POLL_WRITE = 0x20,
86 /** Give a write event when writes don't block any more
88 * An event MUST be sent if writes will not block, and the most recent
89 * write/send() on this FD returned EAGAIN, or connect() returned
90 * EINPROGRESS. An event MAY be sent at any time that writes will not
93 * Before calling OnEventHandler*(), a socket engine MAY change the state of
94 * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
95 * one-shot notification was registered). If further writes are needed,
96 * it is the responsibility of the event handler to change the state to
97 * one that will generate the required notifications
99 FD_WANT_FAST_WRITE = 0x40,
100 /** Give an optional write event on edge-triggered write unblock.
102 * This state is useful to avoid system calls when moving to/from
103 * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
105 FD_WANT_EDGE_WRITE = 0x80,
106 /** Request a one-shot poll-style write notification. The socket will
107 * return to the FD_WANT_NO_WRITE state before OnEventHandler*() is called.
109 FD_WANT_SINGLE_WRITE = 0x100,
111 /** Mask for all write events */
112 FD_WANT_WRITE_MASK = 0x1F0,
114 /** Add a trial read. During the next DispatchEvents invocation, this
115 * will call OnEventHandlerRead() unless reads are known to be
118 FD_ADD_TRIAL_READ = 0x1000,
119 /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
120 * Reset by SE before running OnEventHandlerRead().
122 FD_READ_WILL_BLOCK = 0x2000,
124 /** Add a trial write. During the next DispatchEvents invocation, this
125 * will call OnEventHandlerWrite() unless writes are known to be
128 * This could be used to group several writes together into a single
129 * send() syscall, or to ensure that writes are blocking when attempting
130 * to use FD_WANT_FAST_WRITE.
132 FD_ADD_TRIAL_WRITE = 0x4000,
133 /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
134 * Reset by SE before running OnEventHandlerWrite().
136 FD_WRITE_WILL_BLOCK = 0x8000,
138 /** Mask for trial read/trial write */
139 FD_TRIAL_NOTE_MASK = 0x5000
142 /** This class is a basic I/O handler class.
143 * Any object which wishes to receive basic I/O events
144 * from the socketengine must derive from this class and
145 * implement the OnEventHandler*() methods. The derived class
146 * must then be added to SocketEngine using the method
147 * SocketEngine::AddFd(), after which point the derived
148 * class will receive events to its OnEventHandler*() methods.
149 * The event mask passed to SocketEngine::AddFd() determines
150 * what events the EventHandler gets notified about and with
151 * what semantics. SocketEngine::ChangeEventMask() can be
152 * called to update the event mask later. The only
153 * requirement beyond this for an event handler is that it
154 * must have a file descriptor. What this file descriptor
155 * is actually attached to is completely up to you.
157 class CoreExport EventHandler : public classbase
160 /** Private state maintained by socket engine */
163 void SetEventMask(int mask) { event_mask = mask; }
167 * All events which can be handled must have a file descriptor. This
168 * allows you to add events for sockets, fifo's, pipes, and various
169 * other forms of IPC. Do not change this while the object is
170 * registered with the SocketEngine
174 /** Swaps the internals of this EventHandler with another one.
175 * @param other A EventHandler to swap internals with.
177 void SwapInternals(EventHandler& other);
180 /** Get the current file descriptor
181 * @return The file descriptor of this handler
183 inline int GetFd() const { return fd; }
185 /** Checks if this event handler has a fd associated with it. */
186 inline bool HasFd() const { return fd >= 0; }
188 inline int GetEventMask() const { return event_mask; }
190 /** Set a new file desciptor
191 * @param FD The new file descriptor. Do not call this method without
192 * first deleting the object from the SocketEngine if you have
193 * added it to a SocketEngine instance.
203 virtual ~EventHandler() {}
205 /** Called by the socket engine in case of a read event
207 virtual void OnEventHandlerRead() = 0;
209 /** Called by the socket engine in case of a write event.
210 * The default implementation does nothing.
212 virtual void OnEventHandlerWrite();
214 /** Called by the socket engine in case of an error event.
215 * The default implementation does nothing.
216 * @param errornum Error code
218 virtual void OnEventHandlerError(int errornum);
220 friend class SocketEngine;
223 /** Provides basic file-descriptor-based I/O support.
224 * The actual socketengine class presents the
225 * same interface on all operating systems, but
226 * its private members and internal behaviour
227 * should be treated as blackboxed, and vary
228 * from system to system and upon the config
229 * settings chosen by the server admin.
231 class CoreExport SocketEngine
234 /** Socket engine statistics: count of various events, bandwidth usage
238 mutable size_t indata;
239 mutable size_t outdata;
240 mutable time_t lastempty;
242 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
244 void CheckFlush() const;
247 /** Constructor, initializes member vars except indata and outdata because those are set to 0
248 * in CheckFlush() the first time Update() or GetBandwidth() is called.
250 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
252 /** Update counters for network data received.
253 * This should be called after every read-type syscall.
254 * @param len_in Number of bytes received, or -1 for error, as typically
255 * returned by a read-style syscall.
257 void UpdateReadCounters(int len_in);
259 /** Update counters for network data sent.
260 * This should be called after every write-type syscall.
261 * @param len_out Number of bytes sent, or -1 for error, as typically
262 * returned by a read-style syscall.
264 void UpdateWriteCounters(int len_out);
266 /** Get data transfer statistics.
267 * @param kbitpersec_in Filled with incoming traffic in this second in kbit/s.
268 * @param kbitpersec_out Filled with outgoing traffic in this second in kbit/s.
269 * @param kbitpersec_total Filled with total traffic in this second in kbit/s.
271 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
273 unsigned long TotalEvents;
274 unsigned long ReadEvents;
275 unsigned long WriteEvents;
276 unsigned long ErrorEvents;
280 /** Reference table, contains all current handlers
282 static std::vector<EventHandler*> ref;
284 /** Current number of descriptors in the engine. */
285 static size_t CurrentSetSize;
287 /** The maximum number of descriptors in the engine. */
288 static size_t MaxSetSize;
290 /** List of handlers that want a trial read/write
292 static std::set<int> trials;
294 /** Socket engine statistics: count of various events, bandwidth usage
296 static Statistics stats;
298 /** Look up the fd limit using rlimit. */
299 static void LookupMaxFds();
301 /** Terminates the program when the socket engine fails to initialize. */
302 static void InitError();
304 static void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
306 /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
308 static bool AddFdRef(EventHandler* eh);
310 static void DelFdRef(EventHandler* eh);
312 template <typename T>
313 static void ResizeDouble(std::vector<T>& vect)
315 if (SocketEngine::CurrentSetSize > vect.size())
316 vect.resize(SocketEngine::CurrentSetSize * 2);
321 typedef iovec IOVector;
323 typedef WindowsIOVec IOVector;
327 * The constructor transparently initializes
328 * the socket engine which the ircd is using.
329 * Please note that if there is a catastrophic
330 * failure (for example, you try and enable
331 * epoll on a 2.4 linux kernel) then this
332 * function may bail back to the shell.
333 * @return void, but it is acceptable for this function to bail back to
334 * the shell or operating system on fatal error.
339 * The destructor transparently tidies up
340 * any resources used by the socket engine.
342 static void Deinit();
344 /** Add an EventHandler object to the engine. Use AddFd to add a file
345 * descriptor to the engine and have the socket engine monitor it. You
346 * must provide an object derived from EventHandler which implements
347 * the required OnEventHandler*() methods.
348 * @param eh An event handling object to add
349 * @param event_mask The initial event mask for the object
351 static bool AddFd(EventHandler* eh, int event_mask);
353 /** If you call this function and pass it an
354 * event handler, that event handler will
355 * receive the next available write event,
356 * even if the socket is a readable socket only.
357 * Developers should avoid constantly keeping
358 * an eventhandler in the writeable state,
359 * as this will consume large amounts of
361 * @param eh The event handler to change
362 * @param event_mask The changes to make to the wait state
364 static void ChangeEventMask(EventHandler* eh, int event_mask);
366 /** Returns the number of file descriptors reported by the system this program may use
367 * when it was started.
368 * @return If non-zero the number of file descriptors that the system reported that we
371 static size_t GetMaxFds() { return MaxSetSize; }
373 /** Returns the number of file descriptors being queried
374 * @return The set size
376 static size_t GetUsedFds() { return CurrentSetSize; }
378 /** Delete an event handler from the engine.
379 * This function call deletes an EventHandler
380 * from the engine, returning true if it succeeded
381 * and false if it failed. This does not free the
382 * EventHandler pointer using delete, if this is
383 * required you must do this yourself.
384 * @param eh The event handler object to remove
386 static void DelFd(EventHandler* eh);
388 /** Returns true if a file descriptor exists in
389 * the socket engine's list.
390 * @param fd The event handler to look for
391 * @return True if this fd has an event handler
393 static bool HasFd(int fd);
395 /** Returns the EventHandler attached to a specific fd.
396 * If the fd isnt in the socketengine, returns NULL.
397 * @param fd The event handler to look for
398 * @return A pointer to the event handler, or NULL
400 static EventHandler* GetRef(int fd);
402 /** Waits for events and dispatches them to handlers. Please note that
403 * this doesn't wait long, only a couple of milliseconds. It returns the
404 * number of events which occurred during this call. This method will
405 * dispatch events to their handlers by calling their
406 * EventHandler::OnEventHandler*() methods.
407 * @return The number of events which have occured.
409 static int DispatchEvents();
411 /** Dispatch trial reads and writes. This causes the actual socket I/O
412 * to happen when writes have been pre-buffered.
414 static void DispatchTrialWrites();
416 /** Returns true if the file descriptors in the given event handler are
417 * within sensible ranges which can be handled by the socket engine.
419 static bool BoundsCheckFd(EventHandler* eh);
421 /** Abstraction for BSD sockets accept(2).
422 * This function should emulate its namesake system call exactly.
423 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
424 * @param addr The client IP address and port
425 * @param addrlen The size of the sockaddr parameter.
426 * @return This method should return exactly the same values as the system call it emulates.
428 static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
430 /** Close the underlying fd of an event handler, remove it from the socket engine and set the fd to -1.
431 * @param eh The EventHandler to close.
432 * @return 0 on success, a negative value on error
434 static int Close(EventHandler* eh);
436 /** Abstraction for BSD sockets close(2).
437 * This function should emulate its namesake system call exactly.
438 * This function should emulate its namesake system call exactly.
439 * @return This method should return exactly the same values as the system call it emulates.
441 static int Close(int fd);
443 /** Abstraction for BSD sockets send(2).
444 * This function should emulate its namesake system call exactly.
445 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
446 * @param buf The buffer in which the data that is sent is stored.
447 * @param len The size of the buffer.
448 * @param flags A flag value that controls the sending of the data.
449 * @return This method should return exactly the same values as the system call it emulates.
451 static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
453 /** Abstraction for vector write function writev().
454 * This function should emulate its namesake system call exactly.
455 * @param fd EventHandler to send data with
456 * @param iov Array of IOVectors containing the buffers to send and their lengths in the platform's
458 * @param count Number of elements in iov.
459 * @return This method should return exactly the same values as the system call it emulates.
461 static int WriteV(EventHandler* fd, const IOVector* iov, int count);
464 /** Abstraction for vector write function writev() that accepts a POSIX format iovec.
465 * This function should emulate its namesake system call exactly.
466 * @param fd EventHandler to send data with
467 * @param iov Array of iovecs containing the buffers to send and their lengths in POSIX format.
468 * @param count Number of elements in iov.
469 * @return This method should return exactly the same values as the system call it emulates.
471 static int WriteV(EventHandler* fd, const iovec* iov, int count);
474 /** Abstraction for BSD sockets recv(2).
475 * This function should emulate its namesake system call exactly.
476 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
477 * @param buf The buffer in which the data that is read is stored.
478 * @param len The size of the buffer.
479 * @param flags A flag value that controls the reception of the data.
480 * @return This method should return exactly the same values as the system call it emulates.
482 static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
484 /** Abstraction for BSD sockets recvfrom(2).
485 * This function should emulate its namesake system call exactly.
486 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
487 * @param buf The buffer in which the data that is read is stored.
488 * @param len The size of the buffer.
489 * @param flags A flag value that controls the reception of the data.
490 * @param from The remote IP address and port.
491 * @param fromlen The size of the from parameter.
492 * @return This method should return exactly the same values as the system call it emulates.
494 static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
496 /** Abstraction for BSD sockets sendto(2).
497 * This function should emulate its namesake system call exactly.
498 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
499 * @param buf The buffer in which the data that is sent is stored.
500 * @param len The size of the buffer.
501 * @param flags A flag value that controls the sending of the data.
502 * @param address The remote IP address and port.
503 * @return This method should return exactly the same values as the system call it emulates.
505 static int SendTo(EventHandler* fd, const void* buf, size_t len, int flags, const irc::sockets::sockaddrs& address);
507 /** Abstraction for BSD sockets connect(2).
508 * This function should emulate its namesake system call exactly.
509 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
510 * @param address The server IP address and port.
511 * @return This method should return exactly the same values as the system call it emulates.
513 static int Connect(EventHandler* fd, const irc::sockets::sockaddrs& address);
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.
519 static int Blocking(int fd);
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.
525 static int NonBlocking(int fd);
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.
533 static int Shutdown(EventHandler* fd, int how);
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.
539 static int Shutdown(int fd, int how);
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.
545 static int Bind(int fd, const irc::sockets::sockaddrs& addr);
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.
551 static int Listen(int sockfd, int backlog);
553 /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
555 static void SetReuse(int sockfd);
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.
566 static void RecoverFromFork();
568 /** Get data transfer and event statistics
570 static const Statistics& GetStats() { return stats; }
572 /** Should we ignore the error in errno?
573 * Checks EAGAIN and WSAEWOULDBLOCK
575 static bool IgnoreError();
577 /** Return the last socket related error. strrerror(errno) on *nix
579 static std::string LastError();
581 /** Returns the error for the given error num, strerror(errnum) on *nix
583 static std::string GetError(int errnum);
586 inline bool SocketEngine::IgnoreError()
588 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
592 if (WSAGetLastError() == WSAEWOULDBLOCK)