]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Move the <disabled> tag out of the core to a new module.
[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         /** The type of socket this IOHook represents. */
223         enum Type
224         {
225                 SS_UNKNOWN,
226                 SS_USER
227         };
228
229  private:
230         /** The IOHook that handles raw I/O for this socket, or NULL */
231         IOHook* iohook;
232
233         /** Send queue of the socket
234          */
235         SendQueue sendq;
236
237         /** Error - if nonempty, the socket is dead, and this is the reason. */
238         std::string error;
239
240         /** Check if the socket has an error set, if yes, call OnError
241          * @param err Error to pass to OnError()
242          */
243         void CheckError(BufferedSocketError err);
244
245         /** Read data from the socket into the recvq, if successful call OnDataReady()
246          */
247         void DoRead();
248
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
252          */
253         void FlushSendQ(SendQueue& sq);
254
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
258          */
259         int ReadToRecvQ(std::string& rq);
260
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
268          */
269         int HookChainRead(IOHook* hook, std::string& rq);
270
271  protected:
272         std::string recvq;
273  public:
274         const Type type;
275         StreamSocket(Type sstype = SS_UNKNOWN)
276                 : iohook(NULL)
277                 , type(sstype)
278         {
279         }
280         IOHook* GetIOHook() const;
281         void AddIOHook(IOHook* hook);
282         void DelIOHook();
283
284         /** Flush the send queue
285          */
286         void DoWrite();
287
288         /** Called by the socket engine on a read event
289          */
290         void OnEventHandlerRead() CXX11_OVERRIDE;
291
292         /** Called by the socket engine on a write event
293          */
294         void OnEventHandlerWrite() CXX11_OVERRIDE;
295
296         /** Called by the socket engine on error
297          * @param errcode Error
298          */
299         void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
300
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; }
303
304         /** Gets the error message for this socket. */
305         const std::string& getError() const { return error; }
306
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;
311
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
316          */
317         virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
318
319         /** Send the given data out the socket, either now or when writes unblock
320          */
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
326          */
327         bool GetNextLine(std::string& line, char delim = '\n');
328         /** Useful for implementing sendq exceeded */
329         size_t getSendQSize() const;
330
331         SendQueue& GetSendQ() { return sendq; }
332
333         /**
334          * Close the socket, remove from socket engine, etc
335          */
336         virtual void Close();
337         /** This ensures that close is called prior to destructor */
338         CullResult cull() CXX11_OVERRIDE;
339
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
343          */
344         IOHook* GetModHook(Module* mod) const;
345 };
346 /**
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.
352  *
353  * To use BufferedSocket, you must inherit a class from it.
354  */
355 class CoreExport BufferedSocket : public StreamSocket
356 {
357  public:
358         /** Timeout object or NULL
359          */
360         SocketTimeout* Timeout;
361
362         /**
363          * The state for this socket, either
364          * listening, connecting, connected
365          * or error.
366          */
367         BufferedSocketState state;
368
369         BufferedSocket();
370         /**
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.
376          */
377         BufferedSocket(int newfd);
378
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)
387          */
388         void DoConnect(const std::string& ipaddr, int aport, unsigned int maxtime, const std::string& connectbindip);
389
390         /** This method is called when an outbound connection on your socket is
391          * completed.
392          */
393         virtual void OnConnected();
394
395         /** When there is data waiting to be read on a socket, the OnDataReady()
396          * method is called.
397          */
398         void OnDataReady() CXX11_OVERRIDE = 0;
399
400         /**
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
407          * this class.
408          */
409         virtual void OnTimeout();
410
411         virtual ~BufferedSocket();
412  protected:
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);
416 };
417
418 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
419 inline void StreamSocket::DelIOHook() { iohook = NULL; }