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
91 * @param now The current time
93 SocketTimeout(int fd, BufferedSocket* thesock, long secs_from_now) : Timer(secs_from_now), sock(thesock), sfd(fd) { }
97 virtual bool Tick(time_t now);
101 * StreamSocket is a class that wraps a TCP socket and handles send
102 * and receive queues, including passing them to IO hooks
104 class CoreExport StreamSocket : public EventHandler
107 /** Socket send queue
112 /** One element of the queue, a continuous buffer
114 typedef std::string Element;
116 /** Sequence container of buffers in the queue
118 typedef std::deque<Element> Container;
120 /** Container iterator
122 typedef Container::const_iterator const_iterator;
124 SendQueue() : nbytes(0) { }
126 /** Return whether the queue is empty
127 * @return True if the queue is empty, false otherwise
129 bool empty() const { return (nbytes == 0); }
131 /** Get the number of individual buffers in the queue
132 * @return Number of individual buffers in the queue
134 Container::size_type size() const { return data.size(); }
136 /** Get the number of queued bytes
137 * @return Size in bytes of the data in the queue
139 size_t bytes() const { return nbytes; }
141 /** Get the first buffer of the queue
142 * @return A reference to the first buffer in the queue
144 const Element& front() const { return data.front(); }
146 /** Get an iterator to the first buffer in the queue.
147 * The returned iterator cannot be used to make modifications to the queue,
148 * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
149 * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
151 const_iterator begin() const { return data.begin(); }
153 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
154 * @return Iterator referring to one element past the end of the container
156 const_iterator end() const { return data.end(); }
158 /** Remove the first buffer in the queue
162 nbytes -= data.front().length();
166 /** Remove bytes from the beginning of the first buffer
167 * @param n Number of bytes to remove
169 void erase_front(Element::size_type n)
172 data.front().erase(0, n);
175 /** Insert a new buffer at the beginning of the queue
176 * @param newdata Data to add
178 void push_front(const Element& newdata)
180 data.push_front(newdata);
181 nbytes += newdata.length();
184 /** Insert a new buffer at the end of the queue
185 * @param newdata Data to add
187 void push_back(const Element& newdata)
189 data.push_back(newdata);
190 nbytes += newdata.length();
201 void moveall(SendQueue& other)
203 nbytes += other.bytes();
204 data.insert(data.end(), other.data.begin(), other.data.end());
209 /** Private send queue. Note that individual strings may be shared.
213 /** Length, in bytes, of the sendq
219 /** The IOHook that handles raw I/O for this socket, or NULL */
222 /** Send queue of the socket
226 /** Error - if nonempty, the socket is dead, and this is the reason. */
229 /** Check if the socket has an error set, if yes, call OnError
230 * @param err Error to pass to OnError()
232 void CheckError(BufferedSocketError err);
234 /** Read data from the socket into the recvq, if successful call OnDataReady()
238 /** Send as much data contained in a SendQueue object as possible.
239 * All data which successfully sent will be removed from the SendQueue.
240 * @param sq SendQueue to flush
242 void FlushSendQ(SendQueue& sq);
244 /** Read incoming data into a receive queue.
245 * @param rq Receive queue to put incoming data into
246 * @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
248 int ReadToRecvQ(std::string& rq);
250 /** Read data from a hook chain recursively, starting at 'hook'.
251 * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
252 * next hook in the chain.
253 * @param hook Next IOHook in the chain, can be NULL
254 * @param rq Receive queue to put incoming data into
255 * @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
256 the socket and put into the recvq
258 int HookChainRead(IOHook* hook, std::string& rq);
263 StreamSocket() : iohook(NULL) { }
264 IOHook* GetIOHook() const;
265 void AddIOHook(IOHook* hook);
268 /** Flush the send queue
272 /** Called by the socket engine on a read event
274 void OnEventHandlerRead() CXX11_OVERRIDE;
276 /** Called by the socket engine on a write event
278 void OnEventHandlerWrite() CXX11_OVERRIDE;
280 /** Called by the socket engine on error
281 * @param errcode Error
283 void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
285 /** Sets the error message for this socket. Once set, the socket is dead. */
286 void SetError(const std::string& err) { if (error.empty()) error = err; }
288 /** Gets the error message for this socket. */
289 const std::string& getError() const { return error; }
291 /** Called when new data is present in recvq */
292 virtual void OnDataReady() = 0;
293 /** Called when the socket gets an error from socket engine or IO hook */
294 virtual void OnError(BufferedSocketError e) = 0;
296 /** Send the given data out the socket, either now or when writes unblock
298 void WriteData(const std::string& data);
299 /** Convenience function: read a line from the socket
300 * @param line The line read
301 * @param delim The line delimiter
302 * @return true if a line was read
304 bool GetNextLine(std::string& line, char delim = '\n');
305 /** Useful for implementing sendq exceeded */
306 size_t getSendQSize() const;
308 SendQueue& GetSendQ() { return sendq; }
311 * Close the socket, remove from socket engine, etc
313 virtual void Close();
314 /** This ensures that close is called prior to destructor */
315 virtual CullResult cull();
317 /** Get the IOHook of a module attached to this socket
318 * @param mod Module whose IOHook to return
319 * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
321 IOHook* GetModHook(Module* mod) const;
324 * BufferedSocket is an extendable socket class which modules
325 * can use for TCP socket support. It is fully integrated
326 * into InspIRCds socket loop and attaches its sockets to
327 * the core's instance of the SocketEngine class, meaning
328 * that all use is fully asynchronous.
330 * To use BufferedSocket, you must inherit a class from it.
332 class CoreExport BufferedSocket : public StreamSocket
335 /** Timeout object or NULL
337 SocketTimeout* Timeout;
340 * The state for this socket, either
341 * listening, connecting, connected
344 BufferedSocketState state;
348 * This constructor is used to associate
349 * an existing connecting with an BufferedSocket
350 * class. The given file descriptor must be
351 * valid, and when initialized, the BufferedSocket
352 * will be placed in CONNECTED state.
354 BufferedSocket(int newfd);
356 /** Begin connection to the given address
357 * This will create a socket, register with socket engine, and start the asynchronous
358 * connection process. If an error is detected at this point (such as out of file descriptors),
359 * OnError will be called; otherwise, the state will become CONNECTING.
360 * @param ipaddr Address to connect to
361 * @param aport Port to connect on
362 * @param maxtime Time to wait for connection
363 * @param connectbindip Address to bind to (if NULL, no bind will be done)
365 void DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip);
367 /** This method is called when an outbound connection on your socket is
370 virtual void OnConnected();
372 /** When there is data waiting to be read on a socket, the OnDataReady()
375 virtual void OnDataReady() = 0;
378 * When an outbound connection fails, and the attempt times out, you
379 * will receive this event. The method will trigger once maxtime
380 * seconds are reached (as given in the constructor) just before the
381 * socket's descriptor is closed. A failed DNS lookup may cause this
382 * event if the DNS server is not responding, as well as a failed
383 * connect() call, because DNS lookups are nonblocking as implemented by
386 virtual void OnTimeout();
388 virtual ~BufferedSocket();
390 void OnEventHandlerWrite() CXX11_OVERRIDE;
391 BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout);
392 BufferedSocketError BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip);
395 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
396 inline void StreamSocket::DelIOHook() { iohook = NULL; }