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) 2007 Dennis Friis <peavey@inspircd.org>
7 * Copyright (C) 2006-2007 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 * States which a socket may be in
33 enum BufferedSocketState
35 /** Socket disconnected */
37 /** Socket connecting */
39 /** Socket fully connected */
41 /** Socket has an error */
46 * Error types which a socket may exhibit
48 enum BufferedSocketError
52 /** Socket was closed by peer */
54 /** Socket connect timed out */
56 /** Socket could not be created */
58 /** Socket could not connect (refused) */
60 /** Socket could not bind to local port/ip */
62 /** Socket could not write data */
64 /** No more file descriptors left to create socket! */
66 /** Some other error */
70 /* Required forward declarations */
73 /** Used to time out socket connections
75 class CoreExport SocketTimeout : public Timer
78 /** BufferedSocket the class is attached to
82 /** File descriptor of class this is attached to
87 /** Create a socket timeout class
88 * @param fd File descriptor of BufferedSocket
89 * @param thesock BufferedSocket to attach to
90 * @param secs_from_now Seconds from now to time out
92 SocketTimeout(int fd, BufferedSocket* thesock, unsigned int secs_from_now)
93 : Timer(secs_from_now)
101 bool Tick(time_t now) CXX11_OVERRIDE;
105 * StreamSocket is a class that wraps a TCP socket and handles send
106 * and receive queues, including passing them to IO hooks
108 class CoreExport StreamSocket : public EventHandler
111 /** Socket send queue
116 /** One element of the queue, a continuous buffer
118 typedef std::string Element;
120 /** Sequence container of buffers in the queue
122 typedef std::deque<Element> Container;
124 /** Container iterator
126 typedef Container::const_iterator const_iterator;
128 SendQueue() : nbytes(0) { }
130 /** Return whether the queue is empty
131 * @return True if the queue is empty, false otherwise
133 bool empty() const { return (nbytes == 0); }
135 /** Get the number of individual buffers in the queue
136 * @return Number of individual buffers in the queue
138 Container::size_type size() const { return data.size(); }
140 /** Get the number of queued bytes
141 * @return Size in bytes of the data in the queue
143 size_t bytes() const { return nbytes; }
145 /** Get the first buffer of the queue
146 * @return A reference to the first buffer in the queue
148 const Element& front() const { return data.front(); }
150 /** Get an iterator to the first buffer in the queue.
151 * The returned iterator cannot be used to make modifications to the queue,
152 * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
153 * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
155 const_iterator begin() const { return data.begin(); }
157 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
158 * @return Iterator referring to one element past the end of the container
160 const_iterator end() const { return data.end(); }
162 /** Remove the first buffer in the queue
166 nbytes -= data.front().length();
170 /** Remove bytes from the beginning of the first buffer
171 * @param n Number of bytes to remove
173 void erase_front(Element::size_type n)
176 data.front().erase(0, n);
179 /** Insert a new buffer at the beginning of the queue
180 * @param newdata Data to add
182 void push_front(const Element& newdata)
184 data.push_front(newdata);
185 nbytes += newdata.length();
188 /** Insert a new buffer at the end of the queue
189 * @param newdata Data to add
191 void push_back(const Element& newdata)
193 data.push_back(newdata);
194 nbytes += newdata.length();
205 void moveall(SendQueue& other)
207 nbytes += other.bytes();
208 data.insert(data.end(), other.data.begin(), other.data.end());
213 /** Private send queue. Note that individual strings may be shared.
217 /** Length, in bytes, of the sendq
222 /** The type of socket this IOHook represents. */
230 /** The IOHook that handles raw I/O for this socket, or NULL */
233 /** Send queue of the socket
237 /** Error - if nonempty, the socket is dead, and this is the reason. */
240 /** Check if the socket has an error set, if yes, call OnError
241 * @param err Error to pass to OnError()
243 void CheckError(BufferedSocketError err);
245 /** Read data from the socket into the recvq, if successful call OnDataReady()
249 /** Send as much data contained in a SendQueue object as possible.
250 * All data which successfully sent will be removed from the SendQueue.
251 * @param sq SendQueue to flush
253 void FlushSendQ(SendQueue& sq);
255 /** Read incoming data into a receive queue.
256 * @param rq Receive queue to put incoming data into
257 * @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
259 int ReadToRecvQ(std::string& rq);
261 /** Read data from a hook chain recursively, starting at 'hook'.
262 * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
263 * next hook in the chain.
264 * @param hook Next IOHook in the chain, can be NULL
265 * @param rq Receive queue to put incoming data into
266 * @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
267 the socket and put into the recvq
269 int HookChainRead(IOHook* hook, std::string& rq);
275 StreamSocket(Type sstype = SS_UNKNOWN)
280 IOHook* GetIOHook() const;
281 void AddIOHook(IOHook* hook);
284 /** Flush the send queue
288 /** Called by the socket engine on a read event
290 void OnEventHandlerRead() CXX11_OVERRIDE;
292 /** Called by the socket engine on a write event
294 void OnEventHandlerWrite() CXX11_OVERRIDE;
296 /** Called by the socket engine on error
297 * @param errcode Error
299 void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
301 /** Sets the error message for this socket. Once set, the socket is dead. */
302 void SetError(const std::string& err) { if (error.empty()) error = err; }
304 /** Gets the error message for this socket. */
305 const std::string& getError() const { return error; }
307 /** Called when new data is present in recvq */
308 virtual void OnDataReady() = 0;
309 /** Called when the socket gets an error from socket engine or IO hook */
310 virtual void OnError(BufferedSocketError e) = 0;
312 /** Called when the endpoint addresses are changed.
313 * @param local The new local endpoint.
314 * @param remote The new remote endpoint.
315 * @return true if the connection is still open, false if it has been closed
317 virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
319 /** Send the given data out the socket, either now or when writes unblock
321 void WriteData(const std::string& data);
322 /** Convenience function: read a line from the socket
323 * @param line The line read
324 * @param delim The line delimiter
325 * @return true if a line was read
327 bool GetNextLine(std::string& line, char delim = '\n');
328 /** Useful for implementing sendq exceeded */
329 size_t getSendQSize() const;
331 SendQueue& GetSendQ() { return sendq; }
334 * Close the socket, remove from socket engine, etc
336 virtual void Close();
337 /** This ensures that close is called prior to destructor */
338 CullResult cull() CXX11_OVERRIDE;
340 /** Get the IOHook of a module attached to this socket
341 * @param mod Module whose IOHook to return
342 * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
344 IOHook* GetModHook(Module* mod) const;
347 * BufferedSocket is an extendable socket class which modules
348 * can use for TCP socket support. It is fully integrated
349 * into InspIRCds socket loop and attaches its sockets to
350 * the core's instance of the SocketEngine class, meaning
351 * that all use is fully asynchronous.
353 * To use BufferedSocket, you must inherit a class from it.
355 class CoreExport BufferedSocket : public StreamSocket
358 /** Timeout object or NULL
360 SocketTimeout* Timeout;
363 * The state for this socket, either
364 * listening, connecting, connected
367 BufferedSocketState state;
371 * This constructor is used to associate
372 * an existing connecting with an BufferedSocket
373 * class. The given file descriptor must be
374 * valid, and when initialized, the BufferedSocket
375 * will be placed in CONNECTED state.
377 BufferedSocket(int newfd);
379 /** Begin connection to the given address
380 * This will create a socket, register with socket engine, and start the asynchronous
381 * connection process. If an error is detected at this point (such as out of file descriptors),
382 * OnError will be called; otherwise, the state will become CONNECTING.
383 * @param ipaddr Address to connect to
384 * @param aport Port to connect on
385 * @param maxtime Time to wait for connection
386 * @param connectbindip Address to bind to (if NULL, no bind will be done)
388 void DoConnect(const std::string& ipaddr, int aport, unsigned int maxtime, const std::string& connectbindip);
390 /** This method is called when an outbound connection on your socket is
393 virtual void OnConnected();
395 /** When there is data waiting to be read on a socket, the OnDataReady()
398 void OnDataReady() CXX11_OVERRIDE = 0;
401 * When an outbound connection fails, and the attempt times out, you
402 * will receive this event. The method will trigger once maxtime
403 * seconds are reached (as given in the constructor) just before the
404 * socket's descriptor is closed. A failed DNS lookup may cause this
405 * event if the DNS server is not responding, as well as a failed
406 * connect() call, because DNS lookups are nonblocking as implemented by
409 virtual void OnTimeout();
411 virtual ~BufferedSocket();
413 void OnEventHandlerWrite() CXX11_OVERRIDE;
414 BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
415 BufferedSocketError BeginConnect(const std::string& ipaddr, int aport, unsigned int maxtime, const std::string& connectbindip);
418 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
419 inline void StreamSocket::DelIOHook() { iohook = NULL; }