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 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>
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/>.
36 * States which a socket may be in
38 enum BufferedSocketState
40 /** Socket disconnected */
42 /** Socket connecting */
44 /** Socket fully connected */
46 /** Socket has an error */
51 * Error types which a socket may exhibit
53 enum BufferedSocketError
57 /** Socket was closed by peer */
59 /** Socket connect timed out */
61 /** Socket could not be created */
63 /** Socket could not connect (refused) */
65 /** Socket could not bind to local port/ip */
67 /** Socket could not write data */
69 /** No more file descriptors left to create socket! */
71 /** Some other error */
75 /* Required forward declarations */
78 /** Used to time out socket connections
80 class CoreExport SocketTimeout : public Timer
83 /** BufferedSocket the class is attached to
87 /** File descriptor of class this is attached to
92 /** Create a socket timeout class
93 * @param fd File descriptor of BufferedSocket
94 * @param thesock BufferedSocket to attach to
95 * @param secs_from_now Seconds from now to time out
97 SocketTimeout(int fd, BufferedSocket* thesock, unsigned int secs_from_now)
98 : Timer(secs_from_now)
104 /** Handle tick event
106 bool Tick(time_t now) CXX11_OVERRIDE;
110 * StreamSocket is a class that wraps a TCP socket and handles send
111 * and receive queues, including passing them to IO hooks
113 class CoreExport StreamSocket : public EventHandler
116 /** Socket send queue
121 /** One element of the queue, a continuous buffer
123 typedef std::string Element;
125 /** Sequence container of buffers in the queue
127 typedef std::deque<Element> Container;
129 /** Container iterator
131 typedef Container::const_iterator const_iterator;
133 SendQueue() : nbytes(0) { }
135 /** Return whether the queue is empty
136 * @return True if the queue is empty, false otherwise
138 bool empty() const { return (nbytes == 0); }
140 /** Get the number of individual buffers in the queue
141 * @return Number of individual buffers in the queue
143 Container::size_type size() const { return data.size(); }
145 /** Get the number of queued bytes
146 * @return Size in bytes of the data in the queue
148 size_t bytes() const { return nbytes; }
150 /** Get the first buffer of the queue
151 * @return A reference to the first buffer in the queue
153 const Element& front() const { return data.front(); }
155 /** Get an iterator to the first buffer in the queue.
156 * The returned iterator cannot be used to make modifications to the queue,
157 * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
158 * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
160 const_iterator begin() const { return data.begin(); }
162 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
163 * @return Iterator referring to one element past the end of the container
165 const_iterator end() const { return data.end(); }
167 /** Remove the first buffer in the queue
171 nbytes -= data.front().length();
175 /** Remove bytes from the beginning of the first buffer
176 * @param n Number of bytes to remove
178 void erase_front(Element::size_type n)
181 data.front().erase(0, n);
184 /** Insert a new buffer at the beginning of the queue
185 * @param newdata Data to add
187 void push_front(const Element& newdata)
189 data.push_front(newdata);
190 nbytes += newdata.length();
193 /** Insert a new buffer at the end of the queue
194 * @param newdata Data to add
196 void push_back(const Element& newdata)
198 data.push_back(newdata);
199 nbytes += newdata.length();
210 void moveall(SendQueue& other)
212 nbytes += other.bytes();
213 data.insert(data.end(), other.data.begin(), other.data.end());
218 /** Private send queue. Note that individual strings may be shared.
222 /** Length, in bytes, of the sendq
227 /** The type of socket this IOHook represents. */
235 /** Whether this socket should close once its sendq is empty */
238 /** Whether the socket is currently closing or not, used to avoid repeatedly closing a closed socket */
241 /** The IOHook that handles raw I/O for this socket, or NULL */
244 /** Send queue of the socket
248 /** Error - if nonempty, the socket is dead, and this is the reason. */
251 /** Check if the socket has an error set, if yes, call OnError
252 * @param err Error to pass to OnError()
254 void CheckError(BufferedSocketError err);
256 /** Read data from the socket into the recvq, if successful call OnDataReady()
260 /** Send as much data contained in a SendQueue object as possible.
261 * All data which successfully sent will be removed from the SendQueue.
262 * @param sq SendQueue to flush
264 void FlushSendQ(SendQueue& sq);
266 /** Read incoming data into a receive queue.
267 * @param rq Receive queue to put incoming data into
268 * @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
270 int ReadToRecvQ(std::string& rq);
272 /** Read data from a hook chain recursively, starting at 'hook'.
273 * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
274 * next hook in the chain.
275 * @param hook Next IOHook in the chain, can be NULL
276 * @param rq Receive queue to put incoming data into
277 * @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
278 the socket and put into the recvq
280 int HookChainRead(IOHook* hook, std::string& rq);
283 /** The data which has been received from the socket. */
286 /** Swaps the internals of this StreamSocket with another one.
287 * @param other A StreamSocket to swap internals with.
289 void SwapInternals(StreamSocket& other);
293 StreamSocket(Type sstype = SS_UNKNOWN)
294 : closeonempty(false)
300 IOHook* GetIOHook() const;
301 void AddIOHook(IOHook* hook);
304 /** Flush the send queue
308 /** Called by the socket engine on a read event
310 void OnEventHandlerRead() CXX11_OVERRIDE;
312 /** Called by the socket engine on a write event
314 void OnEventHandlerWrite() CXX11_OVERRIDE;
316 /** Called by the socket engine on error
317 * @param errcode Error
319 void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
321 /** Sets the error message for this socket. Once set, the socket is dead. */
322 void SetError(const std::string& err) { if (error.empty()) error = err; }
324 /** Gets the error message for this socket. */
325 const std::string& getError() const { return error; }
327 /** Called when new data is present in recvq */
328 virtual void OnDataReady() = 0;
329 /** Called when the socket gets an error from socket engine or IO hook */
330 virtual void OnError(BufferedSocketError e) = 0;
332 /** Called when the endpoint addresses are changed.
333 * @param local The new local endpoint.
334 * @param remote The new remote endpoint.
335 * @return true if the connection is still open, false if it has been closed
337 virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
339 /** Send the given data out the socket, either now or when writes unblock
341 void WriteData(const std::string& data);
342 /** Convenience function: read a line from the socket
343 * @param line The line read
344 * @param delim The line delimiter
345 * @return true if a line was read
347 bool GetNextLine(std::string& line, char delim = '\n');
348 /** Useful for implementing sendq exceeded */
349 size_t getSendQSize() const;
351 SendQueue& GetSendQ() { return sendq; }
354 * Close the socket, remove from socket engine, etc
356 virtual void Close();
358 /** If writeblock is true then only close the socket if all data has been sent. Otherwise, close immediately. */
359 void Close(bool writeblock);
361 /** This ensures that close is called prior to destructor */
362 CullResult cull() CXX11_OVERRIDE;
364 /** Get the IOHook of a module attached to this socket
365 * @param mod Module whose IOHook to return
366 * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
368 IOHook* GetModHook(Module* mod) const;
370 /** Get the last IOHook attached to this socket
371 * @return The last IOHook attached to this socket or NULL if no IOHooks are attached
373 IOHook* GetLastHook() const;
376 * BufferedSocket is an extendable socket class which modules
377 * can use for TCP socket support. It is fully integrated
378 * into InspIRCds socket loop and attaches its sockets to
379 * the core's instance of the SocketEngine class, meaning
380 * that all use is fully asynchronous.
382 * To use BufferedSocket, you must inherit a class from it.
384 class CoreExport BufferedSocket : public StreamSocket
387 /** Timeout object or NULL
389 SocketTimeout* Timeout;
392 * The state for this socket, either
393 * listening, connecting, connected
396 BufferedSocketState state;
400 * This constructor is used to associate
401 * an existing connecting with an BufferedSocket
402 * class. The given file descriptor must be
403 * valid, and when initialized, the BufferedSocket
404 * will be placed in CONNECTED state.
406 BufferedSocket(int newfd);
408 /** Begin connection to the given address
409 * This will create a socket, register with socket engine, and start the asynchronous
410 * connection process. If an error is detected at this point (such as out of file descriptors),
411 * OnError will be called; otherwise, the state will become CONNECTING.
412 * @param dest Remote endpoint to connect to.
413 * @param bind Local endpoint to connect from.
414 * @param maxtime Time to wait for connection
416 void DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime);
418 /** This method is called when an outbound connection on your socket is
421 virtual void OnConnected();
423 /** When there is data waiting to be read on a socket, the OnDataReady()
426 void OnDataReady() CXX11_OVERRIDE = 0;
429 * When an outbound connection fails, and the attempt times out, you
430 * will receive this event. The method will trigger once maxtime
431 * seconds are reached (as given in the constructor) just before the
432 * socket's descriptor is closed. A failed DNS lookup may cause this
433 * event if the DNS server is not responding, as well as a failed
434 * connect() call, because DNS lookups are nonblocking as implemented by
437 virtual void OnTimeout();
439 virtual ~BufferedSocket();
441 void OnEventHandlerWrite() CXX11_OVERRIDE;
442 BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
445 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
446 inline void StreamSocket::DelIOHook() { iohook = NULL; }