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/>.
32 /** Types of event an EventHandler may receive.
33 * EVENT_READ is a readable file descriptor,
34 * and EVENT_WRITE is a writeable file descriptor.
35 * EVENT_ERROR can always occur, and indicates
36 * a write error or read error on the socket,
37 * e.g. EOF condition or broken pipe.
50 * Event mask for SocketEngine events
54 /** Do not test this socket for readability
56 FD_WANT_NO_READ = 0x1,
57 /** Give a read event at all times when reads will not block.
59 FD_WANT_POLL_READ = 0x2,
60 /** Give a read event when there is new data to read.
62 * An event MUST be sent if there is new data to be read, and the most
63 * recent read/recv() on this FD returned EAGAIN. An event MAY be sent
64 * at any time there is data to be read on the socket.
66 FD_WANT_FAST_READ = 0x4,
67 /** Give an optional read event when reads begin to unblock
69 * This state is useful if you want to leave data in the OS receive
70 * queue but not get continuous event notifications about it, because
71 * it may not require a system call to transition from FD_WANT_FAST_READ
73 FD_WANT_EDGE_READ = 0x8,
75 /** Mask for all read events */
76 FD_WANT_READ_MASK = 0x0F,
78 /** Do not test this socket for writeability
80 FD_WANT_NO_WRITE = 0x10,
81 /** Give a write event at all times when writes will not block.
83 * You probably shouldn't use this state; if it's likely that the write
84 * will not block, try it first, then use FD_WANT_FAST_WRITE if it
85 * fails. If it's likely to block (or you are using polling-style reads)
86 * then use FD_WANT_SINGLE_WRITE.
88 FD_WANT_POLL_WRITE = 0x20,
89 /** Give a write event when writes don't block any more
91 * An event MUST be sent if writes will not block, and the most recent
92 * write/send() on this FD returned EAGAIN, or connect() returned
93 * EINPROGRESS. An event MAY be sent at any time that writes will not
96 * Before calling HandleEvent, a socket engine MAY change the state of
97 * the FD back to FD_WANT_EDGE_WRITE if it is simpler (for example, if a
98 * one-shot notification was registered). If further writes are needed,
99 * it is the responsibility of the event handler to change the state to
100 * one that will generate the required notifications
102 FD_WANT_FAST_WRITE = 0x40,
103 /** Give an optional write event on edge-triggered write unblock.
105 * This state is useful to avoid system calls when moving to/from
106 * FD_WANT_FAST_WRITE when writing data to a mostly-unblocked socket.
108 FD_WANT_EDGE_WRITE = 0x80,
109 /** Request a one-shot poll-style write notification. The socket will
110 * return to the FD_WANT_NO_WRITE state before HandleEvent is called.
112 FD_WANT_SINGLE_WRITE = 0x100,
114 /** Mask for all write events */
115 FD_WANT_WRITE_MASK = 0x1F0,
117 /** Add a trial read. During the next DispatchEvents invocation, this
118 * will call HandleEvent with EVENT_READ unless reads are known to be
121 FD_ADD_TRIAL_READ = 0x1000,
122 /** Assert that reads are known to block. This cancels FD_ADD_TRIAL_READ.
123 * Reset by SE before running EVENT_READ
125 FD_READ_WILL_BLOCK = 0x2000,
127 /** Add a trial write. During the next DispatchEvents invocation, this
128 * will call HandleEvent with EVENT_WRITE unless writes are known to be
131 * This could be used to group several writes together into a single
132 * send() syscall, or to ensure that writes are blocking when attempting
133 * to use FD_WANT_FAST_WRITE.
135 FD_ADD_TRIAL_WRITE = 0x4000,
136 /** Assert that writes are known to block. This cancels FD_ADD_TRIAL_WRITE.
137 * Reset by SE before running EVENT_WRITE
139 FD_WRITE_WILL_BLOCK = 0x8000,
141 /** Mask for trial read/trial write */
142 FD_TRIAL_NOTE_MASK = 0x5000
145 /** This class is a basic I/O handler class.
146 * Any object which wishes to receive basic I/O events
147 * from the socketengine must derive from this class and
148 * implement the HandleEvent() method. The derived class
149 * must then be added to SocketEngine using the method
150 * SocketEngine::AddFd(), after which point the derived
151 * class will receive events to its HandleEvent() method.
152 * The derived class should also implement one of Readable()
153 * and Writeable(). In the current implementation, only
154 * Readable() is used. If this returns true, the socketengine
155 * inserts a readable socket. If it is false, the socketengine
156 * inserts a writeable socket. The derived class should never
157 * change the value this function returns without first
158 * deleting the socket from the socket engine. The only
159 * requirement beyond this for an event handler is that it
160 * must have a file descriptor. What this file descriptor
161 * is actually attached to is completely up to you.
163 class CoreExport EventHandler : public classbase
166 /** Private state maintained by socket engine */
170 * All events which can be handled must have a file descriptor. This
171 * allows you to add events for sockets, fifo's, pipes, and various
172 * other forms of IPC. Do not change this while the object is
173 * registered with the SocketEngine
177 /** Get the current file descriptor
178 * @return The file descriptor of this handler
180 inline int GetFd() const { return fd; }
182 inline int GetEventMask() const { return event_mask; }
184 /** Set a new file desciptor
185 * @param FD The new file descriptor. Do not call this method without
186 * first deleting the object from the SocketEngine if you have
187 * added it to a SocketEngine instance.
197 virtual ~EventHandler() {}
199 /** Process an I/O event.
200 * You MUST implement this function in your derived
201 * class, and it will be called whenever read or write
202 * events are received.
203 * @param et either one of EVENT_READ for read events,
204 * EVENT_WRITE for write events and EVENT_ERROR for
206 * @param errornum The error code which goes with an EVENT_ERROR.
208 virtual void HandleEvent(EventType et, int errornum = 0) = 0;
210 friend class SocketEngine;
213 /** Provides basic file-descriptor-based I/O support.
214 * The actual socketengine class presents the
215 * same interface on all operating systems, but
216 * its private members and internal behaviour
217 * should be treated as blackboxed, and vary
218 * from system to system and upon the config
219 * settings chosen by the server admin. The current
220 * version supports select, epoll and kqueue.
221 * The configure script will enable a socket engine
222 * based upon what OS is detected, and will derive
223 * a class from SocketEngine based upon what it finds.
224 * The derived classes file will also implement a
225 * classfactory, SocketEngineFactory, which will
226 * create a derived instance of SocketEngine using
227 * polymorphism so that the core and modules do not
228 * have to be aware of which SocketEngine derived
229 * class they are using.
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 /** Increase the counters for bytes sent/received in this second.
253 * @param len_in Bytes received, 0 if updating number of bytes written.
254 * @param len_out Bytes sent, 0 if updating number of bytes read.
256 void Update(size_t len_in, size_t len_out);
258 /** Get data transfer statistics.
259 * @param kbitspersec_in Filled with incoming traffic in this second in kbit/s.
260 * @param kbitspersec_out Filled with outgoing traffic in this second in kbit/s.
261 * @param kbitspersec_total Filled with total traffic in this second in kbit/s.
263 void CoreExport GetBandwidth(float& kbitpersec_in, float& kbitpersec_out, float& kbitpersec_total) const;
265 unsigned long TotalEvents;
266 unsigned long ReadEvents;
267 unsigned long WriteEvents;
268 unsigned long ErrorEvents;
272 /** Reference table, contains all current handlers
274 std::vector<EventHandler*> ref;
277 /** Current number of descriptors in the engine
279 size_t CurrentSetSize;
280 /** List of handlers that want a trial read/write
282 std::set<int> trials;
286 /** Socket engine statistics: count of various events, bandwidth usage
290 virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask) = 0;
291 void SetEventMask(EventHandler* eh, int value);
293 /** Add an event handler to the base socket engine. AddFd(EventHandler*, int) should call this.
295 bool AddFdRef(EventHandler* eh);
297 void DelFdRef(EventHandler* eh);
299 template <typename T>
300 void ResizeDouble(std::vector<T>& vect)
302 if (CurrentSetSize > vect.size())
303 vect.resize(vect.size() * 2);
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.
318 * The destructor transparently tidies up
319 * any resources used by the socket engine.
321 virtual ~SocketEngine();
323 /** Add an EventHandler object to the engine. Use AddFd to add a file
324 * descriptor to the engine and have the socket engine monitor it. You
325 * must provide an object derived from EventHandler which implements
327 * @param eh An event handling object to add
328 * @param event_mask The initial event mask for the object
330 virtual bool AddFd(EventHandler* eh, int event_mask) = 0;
332 /** If you call this function and pass it an
333 * event handler, that event handler will
334 * receive the next available write event,
335 * even if the socket is a readable socket only.
336 * Developers should avoid constantly keeping
337 * an eventhandler in the writeable state,
338 * as this will consume large amounts of
340 * @param eh The event handler to change
341 * @param event_mask The changes to make to the wait state
343 void ChangeEventMask(EventHandler* eh, int event_mask);
345 /** Returns the highest file descriptor you may store in the socket engine
346 * @return The maximum fd value
348 inline int GetMaxFds() const { return MAX_DESCRIPTORS; }
350 /** Returns the number of file descriptors being queried
351 * @return The set size
353 inline size_t GetUsedFds() const { return CurrentSetSize; }
355 /** Delete an event handler from the engine.
356 * This function call deletes an EventHandler
357 * from the engine, returning true if it succeeded
358 * and false if it failed. This does not free the
359 * EventHandler pointer using delete, if this is
360 * required you must do this yourself.
361 * @param eh The event handler object to remove
363 virtual void DelFd(EventHandler* eh) = 0;
365 /** Returns true if a file descriptor exists in
366 * the socket engine's list.
367 * @param fd The event handler to look for
368 * @return True if this fd has an event handler
370 virtual bool HasFd(int fd);
372 /** Returns the EventHandler attached to a specific fd.
373 * If the fd isnt in the socketengine, returns NULL.
374 * @param fd The event handler to look for
375 * @return A pointer to the event handler, or NULL
377 virtual EventHandler* GetRef(int fd);
379 /** Waits for events and dispatches them to handlers. Please note that
380 * this doesn't wait long, only a couple of milliseconds. It returns the
381 * number of events which occurred during this call. This method will
382 * dispatch events to their handlers by calling their
383 * EventHandler::HandleEvent() methods with the necessary EventType
385 * @return The number of events which have occured.
387 virtual int DispatchEvents() = 0;
389 /** Dispatch trial reads and writes. This causes the actual socket I/O
390 * to happen when writes have been pre-buffered.
392 virtual void DispatchTrialWrites();
394 /** Returns true if the file descriptors in the given event handler are
395 * within sensible ranges which can be handled by the socket engine.
397 virtual bool BoundsCheckFd(EventHandler* eh);
399 /** Abstraction for BSD sockets accept(2).
400 * This function should emulate its namesake system call exactly.
401 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
402 * @param addr The client IP address and port
403 * @param addrlen The size of the sockaddr parameter.
404 * @return This method should return exactly the same values as the system call it emulates.
406 static int Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen);
408 /** Abstraction for BSD sockets close(2).
409 * This function should emulate its namesake system call exactly.
410 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
411 * @return This method should return exactly the same values as the system call it emulates.
413 static int Close(EventHandler* fd);
415 /** Abstraction for BSD sockets close(2).
416 * This function should emulate its namesake system call exactly.
417 * This function should emulate its namesake system call exactly.
418 * @return This method should return exactly the same values as the system call it emulates.
420 static int Close(int fd);
422 /** Abstraction for BSD sockets send(2).
423 * This function should emulate its namesake system call exactly.
424 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
425 * @param buf The buffer in which the data that is sent is stored.
426 * @param len The size of the buffer.
427 * @param flags A flag value that controls the sending of the data.
428 * @return This method should return exactly the same values as the system call it emulates.
430 int Send(EventHandler* fd, const void *buf, size_t len, int flags);
432 /** Abstraction for BSD sockets recv(2).
433 * This function should emulate its namesake system call exactly.
434 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
435 * @param buf The buffer in which the data that is read is stored.
436 * @param len The size of the buffer.
437 * @param flags A flag value that controls the reception of the data.
438 * @return This method should return exactly the same values as the system call it emulates.
440 int Recv(EventHandler* fd, void *buf, size_t len, int flags);
442 /** Abstraction for BSD sockets recvfrom(2).
443 * This function should emulate its namesake system call exactly.
444 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
445 * @param buf The buffer in which the data that is read is stored.
446 * @param len The size of the buffer.
447 * @param flags A flag value that controls the reception of the data.
448 * @param from The remote IP address and port.
449 * @param fromlen The size of the from parameter.
450 * @return This method should return exactly the same values as the system call it emulates.
452 int RecvFrom(EventHandler* fd, void *buf, size_t len, int flags, sockaddr *from, socklen_t *fromlen);
454 /** Abstraction for BSD sockets sendto(2).
455 * This function should emulate its namesake system call exactly.
456 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
457 * @param buf The buffer in which the data that is sent is stored.
458 * @param len The size of the buffer.
459 * @param flags A flag value that controls the sending of the data.
460 * @param to The remote IP address and port.
461 * @param tolen The size of the to parameter.
462 * @return This method should return exactly the same values as the system call it emulates.
464 int SendTo(EventHandler* fd, const void *buf, size_t len, int flags, const sockaddr *to, socklen_t tolen);
466 /** Abstraction for BSD sockets connect(2).
467 * This function should emulate its namesake system call exactly.
468 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
469 * @param serv_addr The server IP address and port.
470 * @param addrlen The size of the sockaddr parameter.
471 * @return This method should return exactly the same values as the system call it emulates.
473 static int Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen);
475 /** Make a file descriptor blocking.
476 * @param fd a file descriptor to set to blocking mode
477 * @return 0 on success, -1 on failure, errno is set appropriately.
479 static int Blocking(int fd);
481 /** Make a file descriptor nonblocking.
482 * @param fd A file descriptor to set to nonblocking mode
483 * @return 0 on success, -1 on failure, errno is set appropriately.
485 static int NonBlocking(int fd);
487 /** Abstraction for BSD sockets shutdown(2).
488 * This function should emulate its namesake system call exactly.
489 * @param fd This version of the call takes an EventHandler instead of a bare file descriptor.
490 * @param how What part of the socket to shut down
491 * @return This method should return exactly the same values as the system call it emulates.
493 static int Shutdown(EventHandler* fd, int how);
495 /** Abstraction for BSD sockets shutdown(2).
496 * This function should emulate its namesake system call exactly.
497 * @return This method should return exactly the same values as the system call it emulates.
499 static int Shutdown(int fd, int how);
501 /** Abstraction for BSD sockets bind(2).
502 * This function should emulate its namesake system call exactly.
503 * @return This method should return exactly the same values as the system call it emulates.
505 static int Bind(int fd, const irc::sockets::sockaddrs& addr);
507 /** Abstraction for BSD sockets listen(2).
508 * This function should emulate its namesake system call exactly.
509 * @return This method should return exactly the same values as the system call it emulates.
511 static int Listen(int sockfd, int backlog);
513 /** Set SO_REUSEADDR and SO_LINGER on this file descriptor
515 static void SetReuse(int sockfd);
517 /** This function is called immediately after fork().
518 * Some socket engines (notably kqueue) cannot have their
519 * handles inherited by forked processes. This method
520 * allows for the socket engine to re-create its handle
521 * after the daemon forks as the socket engine is created
522 * long BEFORE the daemon forks.
523 * @return void, but it is acceptable for this function to bail back to
524 * the shell or operating system on fatal error.
526 virtual void RecoverFromFork();
528 /** Get data transfer and event statistics
530 const Statistics& GetStats() const { return stats; }
532 /** Should we ignore the error in errno?
533 * Checks EAGAIN and WSAEWOULDBLOCK
535 static bool IgnoreError();
537 /** Return the last socket related error. strrerror(errno) on *nix
539 static std::string LastError();
541 /** Returns the error for the given error num, strerror(errnum) on *nix
543 static std::string GetError(int errnum);
546 inline bool SocketEngine::IgnoreError()
548 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
552 if (WSAGetLastError() == WSAEWOULDBLOCK)
559 SocketEngine* CreateSocketEngine();