2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2013, 2015-2016 Attila Molnar <attilamolnar@hush.com>
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-2009 Robin Burchell <robin+git@viroteck.net>
11 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
12 * Copyright (C) 2006, 2010 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/>.
35 * States which a socket may be in
37 enum BufferedSocketState
39 /** Socket disconnected */
41 /** Socket connecting */
43 /** Socket fully connected */
45 /** Socket has an error */
50 * Error types which a socket may exhibit
52 enum BufferedSocketError
56 /** Socket was closed by peer */
58 /** Socket connect timed out */
60 /** Socket could not be created */
62 /** Socket could not connect (refused) */
64 /** Socket could not bind to local port/ip */
66 /** Socket could not write data */
68 /** No more file descriptors left to create socket! */
70 /** Some other error */
74 /* Required forward declarations */
77 /** Used to time out socket connections
79 class CoreExport SocketTimeout : public Timer
82 /** BufferedSocket the class is attached to
86 /** File descriptor of class this is attached to
91 /** Create a socket timeout class
92 * @param fd File descriptor of BufferedSocket
93 * @param thesock BufferedSocket to attach to
94 * @param secs_from_now Seconds from now to time out
96 SocketTimeout(int fd, BufferedSocket* thesock, unsigned int secs_from_now)
97 : Timer(secs_from_now)
103 /** Handle tick event
105 bool Tick(time_t now) CXX11_OVERRIDE;
109 * StreamSocket is a class that wraps a TCP socket and handles send
110 * and receive queues, including passing them to IO hooks
112 class CoreExport StreamSocket : public EventHandler
115 /** Socket send queue
120 /** One element of the queue, a continuous buffer
122 typedef std::string Element;
124 /** Sequence container of buffers in the queue
126 typedef std::deque<Element> Container;
128 /** Container iterator
130 typedef Container::const_iterator const_iterator;
132 SendQueue() : nbytes(0) { }
134 /** Return whether the queue is empty
135 * @return True if the queue is empty, false otherwise
137 bool empty() const { return (nbytes == 0); }
139 /** Get the number of individual buffers in the queue
140 * @return Number of individual buffers in the queue
142 Container::size_type size() const { return data.size(); }
144 /** Get the number of queued bytes
145 * @return Size in bytes of the data in the queue
147 size_t bytes() const { return nbytes; }
149 /** Get the first buffer of the queue
150 * @return A reference to the first buffer in the queue
152 const Element& front() const { return data.front(); }
154 /** Get an iterator to the first buffer in the queue.
155 * The returned iterator cannot be used to make modifications to the queue,
156 * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
157 * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
159 const_iterator begin() const { return data.begin(); }
161 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
162 * @return Iterator referring to one element past the end of the container
164 const_iterator end() const { return data.end(); }
166 /** Remove the first buffer in the queue
170 nbytes -= data.front().length();
174 /** Remove bytes from the beginning of the first buffer
175 * @param n Number of bytes to remove
177 void erase_front(Element::size_type n)
180 data.front().erase(0, n);
183 /** Insert a new buffer at the beginning of the queue
184 * @param newdata Data to add
186 void push_front(const Element& newdata)
188 data.push_front(newdata);
189 nbytes += newdata.length();
192 /** Insert a new buffer at the end of the queue
193 * @param newdata Data to add
195 void push_back(const Element& newdata)
197 data.push_back(newdata);
198 nbytes += newdata.length();
209 void moveall(SendQueue& other)
211 nbytes += other.bytes();
212 data.insert(data.end(), other.data.begin(), other.data.end());
217 /** Private send queue. Note that individual strings may be shared.
221 /** Length, in bytes, of the sendq
226 /** The type of socket this IOHook represents. */
234 /** Whether this socket should close once its sendq is empty */
237 /** Whether the socket is currently closing or not, used to avoid repeatedly closing a closed socket */
240 /** The IOHook that handles raw I/O for this socket, or NULL */
243 /** Send queue of the socket
247 /** Error - if nonempty, the socket is dead, and this is the reason. */
250 /** Check if the socket has an error set, if yes, call OnError
251 * @param err Error to pass to OnError()
253 void CheckError(BufferedSocketError err);
255 /** Read data from the socket into the recvq, if successful call OnDataReady()
259 /** Send as much data contained in a SendQueue object as possible.
260 * All data which successfully sent will be removed from the SendQueue.
261 * @param sq SendQueue to flush
263 void FlushSendQ(SendQueue& sq);
265 /** Read incoming data into a receive queue.
266 * @param rq Receive queue to put incoming data into
267 * @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
269 int ReadToRecvQ(std::string& rq);
271 /** Read data from a hook chain recursively, starting at 'hook'.
272 * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
273 * next hook in the chain.
274 * @param hook Next IOHook in the chain, can be NULL
275 * @param rq Receive queue to put incoming data into
276 * @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
277 the socket and put into the recvq
279 int HookChainRead(IOHook* hook, std::string& rq);
282 /** The data which has been received from the socket. */
285 /** Swaps the internals of this StreamSocket with another one.
286 * @param other A StreamSocket to swap internals with.
288 void SwapInternals(StreamSocket& other);
292 StreamSocket(Type sstype = SS_UNKNOWN)
293 : closeonempty(false)
299 IOHook* GetIOHook() const;
300 void AddIOHook(IOHook* hook);
303 /** Flush the send queue
307 /** Called by the socket engine on a read event
309 void OnEventHandlerRead() CXX11_OVERRIDE;
311 /** Called by the socket engine on a write event
313 void OnEventHandlerWrite() CXX11_OVERRIDE;
315 /** Called by the socket engine on error
316 * @param errcode Error
318 void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
320 /** Sets the error message for this socket. Once set, the socket is dead. */
321 void SetError(const std::string& err) { if (error.empty()) error = err; }
323 /** Gets the error message for this socket. */
324 const std::string& getError() const { return error; }
326 /** Called when new data is present in recvq */
327 virtual void OnDataReady() = 0;
328 /** Called when the socket gets an error from socket engine or IO hook */
329 virtual void OnError(BufferedSocketError e) = 0;
331 /** Called when the endpoint addresses are changed.
332 * @param local The new local endpoint.
333 * @param remote The new remote endpoint.
334 * @return true if the connection is still open, false if it has been closed
336 virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
338 /** Send the given data out the socket, either now or when writes unblock
340 void WriteData(const std::string& data);
341 /** Convenience function: read a line from the socket
342 * @param line The line read
343 * @param delim The line delimiter
344 * @return true if a line was read
346 bool GetNextLine(std::string& line, char delim = '\n');
347 /** Useful for implementing sendq exceeded */
348 size_t getSendQSize() const;
350 SendQueue& GetSendQ() { return sendq; }
353 * Close the socket, remove from socket engine, etc
355 virtual void Close();
357 /** If writeblock is true then only close the socket if all data has been sent. Otherwise, close immediately. */
358 void Close(bool writeblock);
360 /** This ensures that close is called prior to destructor */
361 CullResult cull() CXX11_OVERRIDE;
363 /** Get the IOHook of a module attached to this socket
364 * @param mod Module whose IOHook to return
365 * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
367 IOHook* GetModHook(Module* mod) const;
370 * BufferedSocket is an extendable socket class which modules
371 * can use for TCP socket support. It is fully integrated
372 * into InspIRCds socket loop and attaches its sockets to
373 * the core's instance of the SocketEngine class, meaning
374 * that all use is fully asynchronous.
376 * To use BufferedSocket, you must inherit a class from it.
378 class CoreExport BufferedSocket : public StreamSocket
381 /** Timeout object or NULL
383 SocketTimeout* Timeout;
386 * The state for this socket, either
387 * listening, connecting, connected
390 BufferedSocketState state;
394 * This constructor is used to associate
395 * an existing connecting with an BufferedSocket
396 * class. The given file descriptor must be
397 * valid, and when initialized, the BufferedSocket
398 * will be placed in CONNECTED state.
400 BufferedSocket(int newfd);
402 /** Begin connection to the given address
403 * This will create a socket, register with socket engine, and start the asynchronous
404 * connection process. If an error is detected at this point (such as out of file descriptors),
405 * OnError will be called; otherwise, the state will become CONNECTING.
406 * @param dest Remote endpoint to connect to.
407 * @param bind Local endpoint to connect from.
408 * @param maxtime Time to wait for connection
410 void DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime);
412 /** This method is called when an outbound connection on your socket is
415 virtual void OnConnected();
417 /** When there is data waiting to be read on a socket, the OnDataReady()
420 void OnDataReady() CXX11_OVERRIDE = 0;
423 * When an outbound connection fails, and the attempt times out, you
424 * will receive this event. The method will trigger once maxtime
425 * seconds are reached (as given in the constructor) just before the
426 * socket's descriptor is closed. A failed DNS lookup may cause this
427 * event if the DNS server is not responding, as well as a failed
428 * connect() call, because DNS lookups are nonblocking as implemented by
431 virtual void OnTimeout();
433 virtual ~BufferedSocket();
435 void OnEventHandlerWrite() CXX11_OVERRIDE;
436 BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
439 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
440 inline void StreamSocket::DelIOHook() { iohook = NULL; }