2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6 * Copyright (C) 2013, 2015-2016 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2012-2013, 2017-2019, 2021 Sadie Powell <sadie@witchery.services>
8 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
9 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
10 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
11 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
12 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13 * Copyright (C) 2006, 2010 Craig Edwards <brain@inspircd.org>
14 * Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
16 * This file is part of InspIRCd. InspIRCd is free software: you can
17 * redistribute it and/or modify it under the terms of the GNU General Public
18 * License as published by the Free Software Foundation, version 2.
20 * This program is distributed in the hope that it will be useful, but WITHOUT
21 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 * States which a socket may be in
39 enum BufferedSocketState
41 /** Socket disconnected */
43 /** Socket connecting */
45 /** Socket fully connected */
47 /** Socket has an error */
52 * Error types which a socket may exhibit
54 enum BufferedSocketError
58 /** Socket was closed by peer */
60 /** Socket connect timed out */
62 /** Socket could not be created */
64 /** Socket could not connect (refused) */
66 /** Socket could not bind to local port/ip */
68 /** Socket could not write data */
70 /** No more file descriptors left to create socket! */
72 /** Some other error */
76 /* Required forward declarations */
79 /** Used to time out socket connections
81 class CoreExport SocketTimeout : public Timer
84 /** BufferedSocket the class is attached to
88 /** File descriptor of class this is attached to
93 /** Create a socket timeout class
94 * @param fd File descriptor of BufferedSocket
95 * @param thesock BufferedSocket to attach to
96 * @param secs_from_now Seconds from now to time out
98 SocketTimeout(int fd, BufferedSocket* thesock, unsigned int secs_from_now)
99 : Timer(secs_from_now)
105 /** Handle tick event
107 bool Tick(time_t now) CXX11_OVERRIDE;
111 * StreamSocket is a class that wraps a TCP socket and handles send
112 * and receive queues, including passing them to IO hooks
114 class CoreExport StreamSocket : public EventHandler
117 /** Socket send queue
122 /** One element of the queue, a continuous buffer
124 typedef std::string Element;
126 /** Sequence container of buffers in the queue
128 typedef std::deque<Element> Container;
130 /** Container iterator
132 typedef Container::const_iterator const_iterator;
134 SendQueue() : nbytes(0) { }
136 /** Return whether the queue is empty
137 * @return True if the queue is empty, false otherwise
139 bool empty() const { return (nbytes == 0); }
141 /** Get the number of individual buffers in the queue
142 * @return Number of individual buffers in the queue
144 Container::size_type size() const { return data.size(); }
146 /** Get the number of queued bytes
147 * @return Size in bytes of the data in the queue
149 size_t bytes() const { return nbytes; }
151 /** Get the first buffer of the queue
152 * @return A reference to the first buffer in the queue
154 const Element& front() const { return data.front(); }
156 /** Get an iterator to the first buffer in the queue.
157 * The returned iterator cannot be used to make modifications to the queue,
158 * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
159 * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
161 const_iterator begin() const { return data.begin(); }
163 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
164 * @return Iterator referring to one element past the end of the container
166 const_iterator end() const { return data.end(); }
168 /** Remove the first buffer in the queue
172 nbytes -= data.front().length();
176 /** Remove bytes from the beginning of the first buffer
177 * @param n Number of bytes to remove
179 void erase_front(Element::size_type n)
182 data.front().erase(0, n);
185 /** Insert a new buffer at the beginning of the queue
186 * @param newdata Data to add
188 void push_front(const Element& newdata)
190 data.push_front(newdata);
191 nbytes += newdata.length();
194 /** Insert a new buffer at the end of the queue
195 * @param newdata Data to add
197 void push_back(const Element& newdata)
199 data.push_back(newdata);
200 nbytes += newdata.length();
211 void moveall(SendQueue& other)
213 nbytes += other.bytes();
214 data.insert(data.end(), other.data.begin(), other.data.end());
219 /** Private send queue. Note that individual strings may be shared.
223 /** Length, in bytes, of the sendq
228 /** The type of socket this IOHook represents. */
236 /** Whether this socket should close once its sendq is empty */
239 /** Whether the socket is currently closing or not, used to avoid repeatedly closing a closed socket */
242 /** The IOHook that handles raw I/O for this socket, or NULL */
245 /** Send queue of the socket
249 /** Error - if nonempty, the socket is dead, and this is the reason. */
252 /** Check if the socket has an error set, if yes, call OnError
253 * @param err Error to pass to OnError()
255 void CheckError(BufferedSocketError err);
257 /** Read data from the socket into the recvq, if successful call OnDataReady()
261 /** Send as much data contained in a SendQueue object as possible.
262 * All data which successfully sent will be removed from the SendQueue.
263 * @param sq SendQueue to flush
265 void FlushSendQ(SendQueue& sq);
267 /** Read incoming data into a receive queue.
268 * @param rq Receive queue to put incoming data into
269 * @return < 0 on error or close, 0 if no new data is ready (but the socket is still connected), > 0 if data was read from the socket and put into the recvq
271 int ReadToRecvQ(std::string& rq);
273 /** Read data from a hook chain recursively, starting at 'hook'.
274 * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
275 * next hook in the chain.
276 * @param hook Next IOHook in the chain, can be NULL
277 * @param rq Receive queue to put incoming data into
278 * @return < 0 on error or close, 0 if no new data is ready (but the socket is still connected), > 0 if data was read from
279 * the socket and put into the recvq
281 int HookChainRead(IOHook* hook, std::string& rq);
284 /** The data which has been received from the socket. */
287 /** Swaps the internals of this StreamSocket with another one.
288 * @param other A StreamSocket to swap internals with.
290 void SwapInternals(StreamSocket& other);
294 StreamSocket(Type sstype = SS_UNKNOWN)
295 : closeonempty(false)
301 IOHook* GetIOHook() const;
302 void AddIOHook(IOHook* hook);
305 /** Flush the send queue
309 /** Called by the socket engine on a read event
311 void OnEventHandlerRead() CXX11_OVERRIDE;
313 /** Called by the socket engine on a write event
315 void OnEventHandlerWrite() CXX11_OVERRIDE;
317 /** Called by the socket engine on error
318 * @param errcode Error
320 void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
322 /** Sets the error message for this socket. Once set, the socket is dead. */
323 void SetError(const std::string& err) { if (error.empty()) error = err; }
325 /** Gets the error message for this socket. */
326 const std::string& getError() const { return error; }
328 /** Called when new data is present in recvq */
329 virtual void OnDataReady() = 0;
330 /** Called when the socket gets an error from socket engine or IO hook */
331 virtual void OnError(BufferedSocketError e) = 0;
333 /** Called when the endpoint addresses are changed.
334 * @param local The new local endpoint.
335 * @param remote The new remote endpoint.
336 * @return true if the connection is still open, false if it has been closed
338 virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
340 /** Send the given data out the socket, either now or when writes unblock
342 void WriteData(const std::string& data);
343 /** Convenience function: read a line from the socket
344 * @param line The line read
345 * @param delim The line delimiter
346 * @return true if a line was read
348 bool GetNextLine(std::string& line, char delim = '\n');
349 /** Useful for implementing sendq exceeded */
350 size_t getSendQSize() const;
352 SendQueue& GetSendQ() { return sendq; }
355 * Close the socket, remove from socket engine, etc
357 virtual void Close();
359 /** If writeblock is true then only close the socket if all data has been sent. Otherwise, close immediately. */
360 void Close(bool writeblock);
362 /** This ensures that close is called prior to destructor */
363 CullResult cull() CXX11_OVERRIDE;
365 /** Get the IOHook of a module attached to this socket
366 * @param mod Module whose IOHook to return
367 * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
369 IOHook* GetModHook(Module* mod) const;
371 /** Get the last IOHook attached to this socket
372 * @return The last IOHook attached to this socket or NULL if no IOHooks are attached
374 IOHook* GetLastHook() const;
377 * BufferedSocket is an extendable socket class which modules
378 * can use for TCP socket support. It is fully integrated
379 * into InspIRCds socket loop and attaches its sockets to
380 * the core's instance of the SocketEngine class, meaning
381 * that all use is fully asynchronous.
383 * To use BufferedSocket, you must inherit a class from it.
385 class CoreExport BufferedSocket : public StreamSocket
388 /** Timeout object or NULL
390 SocketTimeout* Timeout;
393 * The state for this socket, either
394 * listening, connecting, connected
397 BufferedSocketState state;
401 * This constructor is used to associate
402 * an existing connecting with an BufferedSocket
403 * class. The given file descriptor must be
404 * valid, and when initialized, the BufferedSocket
405 * will be placed in CONNECTED state.
407 BufferedSocket(int newfd);
409 /** Begin connection to the given address
410 * This will create a socket, register with socket engine, and start the asynchronous
411 * connection process. If an error is detected at this point (such as out of file descriptors),
412 * OnError will be called; otherwise, the state will become CONNECTING.
413 * @param dest Remote endpoint to connect to.
414 * @param bind Local endpoint to connect from.
415 * @param maxtime Time to wait for connection
417 void DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime);
419 /** This method is called when an outbound connection on your socket is
422 virtual void OnConnected();
424 /** When there is data waiting to be read on a socket, the OnDataReady()
427 void OnDataReady() CXX11_OVERRIDE = 0;
430 * When an outbound connection fails, and the attempt times out, you
431 * will receive this event. The method will trigger once maxtime
432 * seconds are reached (as given in the constructor) just before the
433 * socket's descriptor is closed. A failed DNS lookup may cause this
434 * event if the DNS server is not responding, as well as a failed
435 * connect() call, because DNS lookups are nonblocking as implemented by
438 virtual void OnTimeout();
440 virtual ~BufferedSocket();
442 void OnEventHandlerWrite() CXX11_OVERRIDE;
443 BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
446 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
447 inline void StreamSocket::DelIOHook() { iohook = NULL; }