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/>.
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.
58 * Event mask for SocketEngine events
62 /** Do not test this socket for readability
64 FD_WANT_NO_READ = 0x1,
65 /** Give a read event at all times when reads will not block.
67 FD_WANT_POLL_READ = 0x2,
68 /** Give a read event when there is new data to read.
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.
74 FD_WANT_FAST_READ = 0x4,
75 /** Give an optional read event when reads begin to unblock
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
81 FD_WANT_EDGE_READ = 0x8,
83 /** Mask for all read events */
84 FD_WANT_READ_MASK = 0x0F,
86 /** Do not test this socket for writeability
88 FD_WANT_NO_WRITE = 0x10,
89 /** Give a write event at all times when writes will not block.
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.
96 FD_WANT_POLL_WRITE = 0x20,
97 /** Give a write event when writes don't block any more
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
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
110 FD_WANT_FAST_WRITE = 0x40,
111 /** Give an optional write event on edge-triggered write unblock.
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.
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.
120 FD_WANT_SINGLE_WRITE = 0x100,
122 /** Mask for all write events */
123 FD_WANT_WRITE_MASK = 0x1F0,
125 /** Add a trial read. During the next DispatchEvents invocation, this
126 * will call HandleEvent with EVENT_READ unless reads are known to be
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
133 FD_READ_WILL_BLOCK = 0x2000,
135 /** Add a trial write. During the next DispatchEvents invocation, this
136 * will call HandleEvent with EVENT_WRITE unless writes are known to be
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.
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
147 FD_WRITE_WILL_BLOCK = 0x8000,
149 /** Mask for trial read/trial write */
150 FD_TRIAL_NOTE_MASK = 0x5000
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.
171 class CoreExport EventHandler : public classbase
174 /** Private state maintained by socket engine */
177 void SetEventMask(int mask) { event_mask = mask; }
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
188 /** Get the current file descriptor
189 * @return The file descriptor of this handler
191 inline int GetFd() const { return fd; }
193 inline int GetEventMask() const { return event_mask; }
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.
208 virtual ~EventHandler() {}
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
217 * @param errornum The error code which goes with an EVENT_ERROR.
219 virtual void HandleEvent(EventType et, int errornum = 0) = 0;
221 friend class SocketEngine;
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.
242 class CoreExport SocketEngine
245 /** Socket engine statistics: count of various events, bandwidth usage
249 mutable size_t indata;
250 mutable size_t outdata;
251 mutable time_t lastempty;
253 /** Reset the byte counters and lastempty if there wasn't a reset in this second.
255 void CheckFlush() const;
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.
261 Statistics() : lastempty(0), TotalEvents(0), ReadEvents(0), WriteEvents(0), ErrorEvents(0) { }
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.
267 void Update(size_t len_in, size_t len_out);
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.
274 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
276 unsigned long TotalEvents;
277 unsigned long ReadEvents;
278 unsigned long WriteEvents;
279 unsigned long ErrorEvents;
283 /** Reference table, contains all current handlers
285 static std::vector<EventHandler*> ref;
288 /** Current number of descriptors in the engine
290 static size_t CurrentSetSize;
291 /** List of handlers that want a trial read/write
293 static std::set<int> trials;
295 static int MAX_DESCRIPTORS;
297 /** Socket engine statistics: count of various events, bandwidth usage
299 static Statistics stats;
301 static void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
303 /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
305 static bool AddFdRef(EventHandler* eh);
307 static void DelFdRef(EventHandler* eh);
309 template <typename T>
310 static void ResizeDouble(std::vector<T>& vect)
312 if (SocketEngine::CurrentSetSize > vect.size())
313 vect.resize(vect.size() * 2);
318 typedef iovec IOVector;
320 typedef WindowsIOVec IOVector;
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.
336 * The destructor transparently tidies up
337 * any resources used by the socket engine.
339 static void Deinit();
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
345 * @param eh An event handling object to add
346 * @param event_mask The initial event mask for the object
348 static bool AddFd(EventHandler* eh, int event_mask);
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
358 * @param eh The event handler to change
359 * @param event_mask The changes to make to the wait state
361 static void ChangeEventMask(EventHandler* eh, int event_mask);
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.
368 static int GetMaxFds() { return MAX_DESCRIPTORS; }
370 /** Returns the number of file descriptors being queried
371 * @return The set size
373 static size_t GetUsedFds() { return CurrentSetSize; }
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
383 static void DelFd(EventHandler* eh);
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
390 static bool HasFd(int fd);
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
397 static EventHandler* GetRef(int fd);
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
405 * @return The number of events which have occured.
407 static int DispatchEvents();
409 /** Dispatch trial reads and writes. This causes the actual socket I/O
410 * to happen when writes have been pre-buffered.
412 static void DispatchTrialWrites();
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.
417 static bool BoundsCheckFd(EventHandler* eh);
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.
426 static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
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
432 static int Close(EventHandler* eh);
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.
439 static int Close(int fd);
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.
449 static int Send(EventHandler* fd, const void *buf, size_t len, int flags);
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
456 * @param count Number of elements in iov.
457 * @return This method should return exactly the same values as the system call it emulates.
459 static int WriteV(EventHandler* fd, const IOVector* iov, int count);
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.
469 static int WriteV(EventHandler* fd, const iovec* iov, int count);
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.
480 static int Recv(EventHandler* fd, void *buf, size_t len, int flags);
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.
492 static int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
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.
504 static int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
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.
513 static int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
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)