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
223 /** The IOHook that handles raw I/O for this socket, or NULL */
226 /** Send queue of the socket
230 /** Error - if nonempty, the socket is dead, and this is the reason. */
233 /** Check if the socket has an error set, if yes, call OnError
234 * @param err Error to pass to OnError()
236 void CheckError(BufferedSocketError err);
238 /** Read data from the socket into the recvq, if successful call OnDataReady()
242 /** Send as much data contained in a SendQueue object as possible.
243 * All data which successfully sent will be removed from the SendQueue.
244 * @param sq SendQueue to flush
246 void FlushSendQ(SendQueue& sq);
248 /** Read incoming data into a receive queue.
249 * @param rq Receive queue to put incoming data into
250 * @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
252 int ReadToRecvQ(std::string& rq);
254 /** Read data from a hook chain recursively, starting at 'hook'.
255 * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
256 * next hook in the chain.
257 * @param hook Next IOHook in the chain, can be NULL
258 * @param rq Receive queue to put incoming data into
259 * @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
260 the socket and put into the recvq
262 int HookChainRead(IOHook* hook, std::string& rq);
267 StreamSocket() : iohook(NULL) { }
268 IOHook* GetIOHook() const;
269 void AddIOHook(IOHook* hook);
272 /** Flush the send queue
276 /** Called by the socket engine on a read event
278 void OnEventHandlerRead() CXX11_OVERRIDE;
280 /** Called by the socket engine on a write event
282 void OnEventHandlerWrite() CXX11_OVERRIDE;
284 /** Called by the socket engine on error
285 * @param errcode Error
287 void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
289 /** Sets the error message for this socket. Once set, the socket is dead. */
290 void SetError(const std::string& err) { if (error.empty()) error = err; }
292 /** Gets the error message for this socket. */
293 const std::string& getError() const { return error; }
295 /** Called when new data is present in recvq */
296 virtual void OnDataReady() = 0;
297 /** Called when the socket gets an error from socket engine or IO hook */
298 virtual void OnError(BufferedSocketError e) = 0;
300 /** Called when the endpoint addresses are changed.
301 * @param local The new local endpoint.
302 * @param remote The new remote endpoint.
304 virtual void OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote) { }
306 /** Send the given data out the socket, either now or when writes unblock
308 void WriteData(const std::string& data);
309 /** Convenience function: read a line from the socket
310 * @param line The line read
311 * @param delim The line delimiter
312 * @return true if a line was read
314 bool GetNextLine(std::string& line, char delim = '\n');
315 /** Useful for implementing sendq exceeded */
316 size_t getSendQSize() const;
318 SendQueue& GetSendQ() { return sendq; }
321 * Close the socket, remove from socket engine, etc
323 virtual void Close();
324 /** This ensures that close is called prior to destructor */
325 CullResult cull() CXX11_OVERRIDE;
327 /** Get the IOHook of a module attached to this socket
328 * @param mod Module whose IOHook to return
329 * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
331 IOHook* GetModHook(Module* mod) const;
334 * BufferedSocket is an extendable socket class which modules
335 * can use for TCP socket support. It is fully integrated
336 * into InspIRCds socket loop and attaches its sockets to
337 * the core's instance of the SocketEngine class, meaning
338 * that all use is fully asynchronous.
340 * To use BufferedSocket, you must inherit a class from it.
342 class CoreExport BufferedSocket : public StreamSocket
345 /** Timeout object or NULL
347 SocketTimeout* Timeout;
350 * The state for this socket, either
351 * listening, connecting, connected
354 BufferedSocketState state;
358 * This constructor is used to associate
359 * an existing connecting with an BufferedSocket
360 * class. The given file descriptor must be
361 * valid, and when initialized, the BufferedSocket
362 * will be placed in CONNECTED state.
364 BufferedSocket(int newfd);
366 /** Begin connection to the given address
367 * This will create a socket, register with socket engine, and start the asynchronous
368 * connection process. If an error is detected at this point (such as out of file descriptors),
369 * OnError will be called; otherwise, the state will become CONNECTING.
370 * @param ipaddr Address to connect to
371 * @param aport Port to connect on
372 * @param maxtime Time to wait for connection
373 * @param connectbindip Address to bind to (if NULL, no bind will be done)
375 void DoConnect(const std::string& ipaddr, int aport, unsigned int maxtime, const std::string& connectbindip);
377 /** This method is called when an outbound connection on your socket is
380 virtual void OnConnected();
382 /** When there is data waiting to be read on a socket, the OnDataReady()
385 void OnDataReady() CXX11_OVERRIDE = 0;
388 * When an outbound connection fails, and the attempt times out, you
389 * will receive this event. The method will trigger once maxtime
390 * seconds are reached (as given in the constructor) just before the
391 * socket's descriptor is closed. A failed DNS lookup may cause this
392 * event if the DNS server is not responding, as well as a failed
393 * connect() call, because DNS lookups are nonblocking as implemented by
396 virtual void OnTimeout();
398 virtual ~BufferedSocket();
400 void OnEventHandlerWrite() CXX11_OVERRIDE;
401 BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
402 BufferedSocketError BeginConnect(const std::string& ipaddr, int aport, unsigned int maxtime, const std::string& connectbindip);
405 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
406 inline void StreamSocket::DelIOHook() { iohook = NULL; }