]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Fix warnings from Doxygen.
[user/henk/code/inspircd.git] / include / inspsocket.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
9  *
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.
13  *
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
17  * details.
18  *
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/>.
21  */
22
23
24 #pragma once
25
26 #include "timer.h"
27
28 class IOHook;
29
30 /**
31  * States which a socket may be in
32  */
33 enum BufferedSocketState
34 {
35         /** Socket disconnected */
36         I_DISCONNECTED,
37         /** Socket connecting */
38         I_CONNECTING,
39         /** Socket fully connected */
40         I_CONNECTED,
41         /** Socket has an error */
42         I_ERROR
43 };
44
45 /**
46  * Error types which a socket may exhibit
47  */
48 enum BufferedSocketError
49 {
50         /** No error */
51         I_ERR_NONE,
52         /** Socket was closed by peer */
53         I_ERR_DISCONNECT,
54         /** Socket connect timed out */
55         I_ERR_TIMEOUT,
56         /** Socket could not be created */
57         I_ERR_SOCKET,
58         /** Socket could not connect (refused) */
59         I_ERR_CONNECT,
60         /** Socket could not bind to local port/ip */
61         I_ERR_BIND,
62         /** Socket could not write data */
63         I_ERR_WRITE,
64         /** No more file descriptors left to create socket! */
65         I_ERR_NOMOREFDS,
66         /** Some other error */
67         I_ERR_OTHER
68 };
69
70 /* Required forward declarations */
71 class BufferedSocket;
72
73 /** Used to time out socket connections
74  */
75 class CoreExport SocketTimeout : public Timer
76 {
77  private:
78         /** BufferedSocket the class is attached to
79          */
80         BufferedSocket* sock;
81
82         /** File descriptor of class this is attached to
83          */
84         int sfd;
85
86  public:
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          */
92         SocketTimeout(int fd, BufferedSocket* thesock, unsigned int secs_from_now)
93                 : Timer(secs_from_now)
94                 , sock(thesock)
95                 , sfd(fd)
96         {
97         }
98
99         /** Handle tick event
100          */
101         bool Tick(time_t now) CXX11_OVERRIDE;
102 };
103
104 /**
105  * StreamSocket is a class that wraps a TCP socket and handles send
106  * and receive queues, including passing them to IO hooks
107  */
108 class CoreExport StreamSocket : public EventHandler
109 {
110  public:
111         /** Socket send queue
112          */
113         class SendQueue
114         {
115          public:
116                 /** One element of the queue, a continuous buffer
117                  */
118                 typedef std::string Element;
119
120                 /** Sequence container of buffers in the queue
121                  */
122                 typedef std::deque<Element> Container;
123
124                 /** Container iterator
125                  */
126                 typedef Container::const_iterator const_iterator;
127
128                 SendQueue() : nbytes(0) { }
129
130                 /** Return whether the queue is empty
131                  * @return True if the queue is empty, false otherwise
132                  */
133                 bool empty() const { return (nbytes == 0); }
134
135                 /** Get the number of individual buffers in the queue
136                  * @return Number of individual buffers in the queue
137                  */
138                 Container::size_type size() const { return data.size(); }
139
140                 /** Get the number of queued bytes
141                  * @return Size in bytes of the data in the queue
142                  */
143                 size_t bytes() const { return nbytes; }
144
145                 /** Get the first buffer of the queue
146                  * @return A reference to the first buffer in the queue
147                  */
148                 const Element& front() const { return data.front(); }
149
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.
154                  */
155                 const_iterator begin() const { return data.begin(); }
156
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
159                  */
160                 const_iterator end() const { return data.end(); }
161
162                 /** Remove the first buffer in the queue
163                  */
164                 void pop_front()
165                 {
166                         nbytes -= data.front().length();
167                         data.pop_front();
168                 }
169
170                 /** Remove bytes from the beginning of the first buffer
171                  * @param n Number of bytes to remove
172                  */
173                 void erase_front(Element::size_type n)
174                 {
175                         nbytes -= n;
176                         data.front().erase(0, n);
177                 }
178
179                 /** Insert a new buffer at the beginning of the queue
180                  * @param newdata Data to add
181                  */
182                 void push_front(const Element& newdata)
183                 {
184                         data.push_front(newdata);
185                         nbytes += newdata.length();
186                 }
187
188                 /** Insert a new buffer at the end of the queue
189                  * @param newdata Data to add
190                  */
191                 void push_back(const Element& newdata)
192                 {
193                         data.push_back(newdata);
194                         nbytes += newdata.length();
195                 }
196
197                 /** Clear the queue
198                  */
199                 void clear()
200                 {
201                         data.clear();
202                         nbytes = 0;
203                 }
204
205                 void moveall(SendQueue& other)
206                 {
207                         nbytes += other.bytes();
208                         data.insert(data.end(), other.data.begin(), other.data.end());
209                         other.clear();
210                 }
211
212          private:
213                 /** Private send queue. Note that individual strings may be shared.
214                  */
215                 Container data;
216
217                 /** Length, in bytes, of the sendq
218                  */
219                 size_t nbytes;
220         };
221
222  private:
223         /** The IOHook that handles raw I/O for this socket, or NULL */
224         IOHook* iohook;
225
226         /** Send queue of the socket
227          */
228         SendQueue sendq;
229
230         /** Error - if nonempty, the socket is dead, and this is the reason. */
231         std::string error;
232
233         /** Check if the socket has an error set, if yes, call OnError
234          * @param err Error to pass to OnError()
235          */
236         void CheckError(BufferedSocketError err);
237
238         /** Read data from the socket into the recvq, if successful call OnDataReady()
239          */
240         void DoRead();
241
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
245          */
246         void FlushSendQ(SendQueue& sq);
247
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
251          */
252         int ReadToRecvQ(std::string& rq);
253
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
261          */
262         int HookChainRead(IOHook* hook, std::string& rq);
263
264  protected:
265         std::string recvq;
266  public:
267         StreamSocket() : iohook(NULL) { }
268         IOHook* GetIOHook() const;
269         void AddIOHook(IOHook* hook);
270         void DelIOHook();
271
272         /** Flush the send queue
273          */
274         void DoWrite();
275
276         /** Called by the socket engine on a read event
277          */
278         void OnEventHandlerRead() CXX11_OVERRIDE;
279
280         /** Called by the socket engine on a write event
281          */
282         void OnEventHandlerWrite() CXX11_OVERRIDE;
283
284         /** Called by the socket engine on error
285          * @param errcode Error
286          */
287         void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
288
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; }
291
292         /** Gets the error message for this socket. */
293         const std::string& getError() const { return error; }
294
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;
299
300         /** Called when the endpoint addresses are changed.
301          * @param local The new local endpoint.
302          * @param remote The new remote endpoint.
303          */
304         virtual void OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote) { }
305
306         /** Send the given data out the socket, either now or when writes unblock
307          */
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
313          */
314         bool GetNextLine(std::string& line, char delim = '\n');
315         /** Useful for implementing sendq exceeded */
316         size_t getSendQSize() const;
317
318         SendQueue& GetSendQ() { return sendq; }
319
320         /**
321          * Close the socket, remove from socket engine, etc
322          */
323         virtual void Close();
324         /** This ensures that close is called prior to destructor */
325         CullResult cull() CXX11_OVERRIDE;
326
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
330          */
331         IOHook* GetModHook(Module* mod) const;
332 };
333 /**
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.
339  *
340  * To use BufferedSocket, you must inherit a class from it.
341  */
342 class CoreExport BufferedSocket : public StreamSocket
343 {
344  public:
345         /** Timeout object or NULL
346          */
347         SocketTimeout* Timeout;
348
349         /**
350          * The state for this socket, either
351          * listening, connecting, connected
352          * or error.
353          */
354         BufferedSocketState state;
355
356         BufferedSocket();
357         /**
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.
363          */
364         BufferedSocket(int newfd);
365
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)
374          */
375         void DoConnect(const std::string& ipaddr, int aport, unsigned int maxtime, const std::string& connectbindip);
376
377         /** This method is called when an outbound connection on your socket is
378          * completed.
379          */
380         virtual void OnConnected();
381
382         /** When there is data waiting to be read on a socket, the OnDataReady()
383          * method is called.
384          */
385         void OnDataReady() CXX11_OVERRIDE = 0;
386
387         /**
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
394          * this class.
395          */
396         virtual void OnTimeout();
397
398         virtual ~BufferedSocket();
399  protected:
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);
403 };
404
405 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
406 inline void StreamSocket::DelIOHook() { iohook = NULL; }