]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
f9cc87b1daf679473cd0b88d03d85bf8601e40dd
[user/henk/code/inspircd.git] / include / inspsocket.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6  *   Copyright (C) 2013, 2015-2016 Attila Molnar <attilamolnar@hush.com>
7  *   Copyright (C) 2012-2013, 2017-2019 Sadie Powell <sadie@witchery.services>
8  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
10  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
11  *   Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
12  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13  *   Copyright (C) 2006, 2010 Craig Edwards <brain@inspircd.org>
14  *   Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
15  *
16  * This file is part of InspIRCd.  InspIRCd is free software: you can
17  * redistribute it and/or modify it under the terms of the GNU General Public
18  * License as published by the Free Software Foundation, version 2.
19  *
20  * This program is distributed in the hope that it will be useful, but WITHOUT
21  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27  */
28
29
30 #pragma once
31
32 #include "timer.h"
33
34 class IOHook;
35
36 /**
37  * States which a socket may be in
38  */
39 enum BufferedSocketState
40 {
41         /** Socket disconnected */
42         I_DISCONNECTED,
43         /** Socket connecting */
44         I_CONNECTING,
45         /** Socket fully connected */
46         I_CONNECTED,
47         /** Socket has an error */
48         I_ERROR
49 };
50
51 /**
52  * Error types which a socket may exhibit
53  */
54 enum BufferedSocketError
55 {
56         /** No error */
57         I_ERR_NONE,
58         /** Socket was closed by peer */
59         I_ERR_DISCONNECT,
60         /** Socket connect timed out */
61         I_ERR_TIMEOUT,
62         /** Socket could not be created */
63         I_ERR_SOCKET,
64         /** Socket could not connect (refused) */
65         I_ERR_CONNECT,
66         /** Socket could not bind to local port/ip */
67         I_ERR_BIND,
68         /** Socket could not write data */
69         I_ERR_WRITE,
70         /** No more file descriptors left to create socket! */
71         I_ERR_NOMOREFDS,
72         /** Some other error */
73         I_ERR_OTHER
74 };
75
76 /* Required forward declarations */
77 class BufferedSocket;
78
79 /** Used to time out socket connections
80  */
81 class CoreExport SocketTimeout : public Timer
82 {
83  private:
84         /** BufferedSocket the class is attached to
85          */
86         BufferedSocket* sock;
87
88         /** File descriptor of class this is attached to
89          */
90         int sfd;
91
92  public:
93         /** Create a socket timeout class
94          * @param fd File descriptor of BufferedSocket
95          * @param thesock BufferedSocket to attach to
96          * @param secs_from_now Seconds from now to time out
97          */
98         SocketTimeout(int fd, BufferedSocket* thesock, unsigned int secs_from_now)
99                 : Timer(secs_from_now)
100                 , sock(thesock)
101                 , sfd(fd)
102         {
103         }
104
105         /** Handle tick event
106          */
107         bool Tick(time_t now) CXX11_OVERRIDE;
108 };
109
110 /**
111  * StreamSocket is a class that wraps a TCP socket and handles send
112  * and receive queues, including passing them to IO hooks
113  */
114 class CoreExport StreamSocket : public EventHandler
115 {
116  public:
117         /** Socket send queue
118          */
119         class SendQueue
120         {
121          public:
122                 /** One element of the queue, a continuous buffer
123                  */
124                 typedef std::string Element;
125
126                 /** Sequence container of buffers in the queue
127                  */
128                 typedef std::deque<Element> Container;
129
130                 /** Container iterator
131                  */
132                 typedef Container::const_iterator const_iterator;
133
134                 SendQueue() : nbytes(0) { }
135
136                 /** Return whether the queue is empty
137                  * @return True if the queue is empty, false otherwise
138                  */
139                 bool empty() const { return (nbytes == 0); }
140
141                 /** Get the number of individual buffers in the queue
142                  * @return Number of individual buffers in the queue
143                  */
144                 Container::size_type size() const { return data.size(); }
145
146                 /** Get the number of queued bytes
147                  * @return Size in bytes of the data in the queue
148                  */
149                 size_t bytes() const { return nbytes; }
150
151                 /** Get the first buffer of the queue
152                  * @return A reference to the first buffer in the queue
153                  */
154                 const Element& front() const { return data.front(); }
155
156                 /** Get an iterator to the first buffer in the queue.
157                  * The returned iterator cannot be used to make modifications to the queue,
158                  * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
159                  * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
160                  */
161                 const_iterator begin() const { return data.begin(); }
162
163                 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
164                  * @return Iterator referring to one element past the end of the container
165                  */
166                 const_iterator end() const { return data.end(); }
167
168                 /** Remove the first buffer in the queue
169                  */
170                 void pop_front()
171                 {
172                         nbytes -= data.front().length();
173                         data.pop_front();
174                 }
175
176                 /** Remove bytes from the beginning of the first buffer
177                  * @param n Number of bytes to remove
178                  */
179                 void erase_front(Element::size_type n)
180                 {
181                         nbytes -= n;
182                         data.front().erase(0, n);
183                 }
184
185                 /** Insert a new buffer at the beginning of the queue
186                  * @param newdata Data to add
187                  */
188                 void push_front(const Element& newdata)
189                 {
190                         data.push_front(newdata);
191                         nbytes += newdata.length();
192                 }
193
194                 /** Insert a new buffer at the end of the queue
195                  * @param newdata Data to add
196                  */
197                 void push_back(const Element& newdata)
198                 {
199                         data.push_back(newdata);
200                         nbytes += newdata.length();
201                 }
202
203                 /** Clear the queue
204                  */
205                 void clear()
206                 {
207                         data.clear();
208                         nbytes = 0;
209                 }
210
211                 void moveall(SendQueue& other)
212                 {
213                         nbytes += other.bytes();
214                         data.insert(data.end(), other.data.begin(), other.data.end());
215                         other.clear();
216                 }
217
218          private:
219                 /** Private send queue. Note that individual strings may be shared.
220                  */
221                 Container data;
222
223                 /** Length, in bytes, of the sendq
224                  */
225                 size_t nbytes;
226         };
227
228         /** The type of socket this IOHook represents. */
229         enum Type
230         {
231                 SS_UNKNOWN,
232                 SS_USER
233         };
234
235  private:
236         /** Whether this socket should close once its sendq is empty */
237         bool closeonempty;
238
239         /** Whether the socket is currently closing or not, used to avoid repeatedly closing a closed socket */
240         bool closing;
241
242         /** The IOHook that handles raw I/O for this socket, or NULL */
243         IOHook* iohook;
244
245         /** Send queue of the socket
246          */
247         SendQueue sendq;
248
249         /** Error - if nonempty, the socket is dead, and this is the reason. */
250         std::string error;
251
252         /** Check if the socket has an error set, if yes, call OnError
253          * @param err Error to pass to OnError()
254          */
255         void CheckError(BufferedSocketError err);
256
257         /** Read data from the socket into the recvq, if successful call OnDataReady()
258          */
259         void DoRead();
260
261         /** Send as much data contained in a SendQueue object as possible.
262          * All data which successfully sent will be removed from the SendQueue.
263          * @param sq SendQueue to flush
264          */
265         void FlushSendQ(SendQueue& sq);
266
267         /** Read incoming data into a receive queue.
268          * @param rq Receive queue to put incoming data into
269          * @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
270          */
271         int ReadToRecvQ(std::string& rq);
272
273         /** Read data from a hook chain recursively, starting at 'hook'.
274          * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
275          * next hook in the chain.
276          * @param hook Next IOHook in the chain, can be NULL
277          * @param rq Receive queue to put incoming data into
278          * @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
279          the socket and put into the recvq
280          */
281         int HookChainRead(IOHook* hook, std::string& rq);
282
283  protected:
284         /** The data which has been received from the socket. */
285         std::string recvq;
286
287         /** Swaps the internals of this StreamSocket with another one.
288          * @param other A StreamSocket to swap internals with.
289          */
290         void SwapInternals(StreamSocket& other);
291
292  public:
293         const Type type;
294         StreamSocket(Type sstype = SS_UNKNOWN)
295                 : closeonempty(false)
296                 , closing(false)
297                 , iohook(NULL)
298                 , type(sstype)
299         {
300         }
301         IOHook* GetIOHook() const;
302         void AddIOHook(IOHook* hook);
303         void DelIOHook();
304
305         /** Flush the send queue
306          */
307         void DoWrite();
308
309         /** Called by the socket engine on a read event
310          */
311         void OnEventHandlerRead() CXX11_OVERRIDE;
312
313         /** Called by the socket engine on a write event
314          */
315         void OnEventHandlerWrite() CXX11_OVERRIDE;
316
317         /** Called by the socket engine on error
318          * @param errcode Error
319          */
320         void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
321
322         /** Sets the error message for this socket. Once set, the socket is dead. */
323         void SetError(const std::string& err) { if (error.empty()) error = err; }
324
325         /** Gets the error message for this socket. */
326         const std::string& getError() const { return error; }
327
328         /** Called when new data is present in recvq */
329         virtual void OnDataReady() = 0;
330         /** Called when the socket gets an error from socket engine or IO hook */
331         virtual void OnError(BufferedSocketError e) = 0;
332
333         /** Called when the endpoint addresses are changed.
334          * @param local The new local endpoint.
335          * @param remote The new remote endpoint.
336          * @return true if the connection is still open, false if it has been closed
337          */
338         virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
339
340         /** Send the given data out the socket, either now or when writes unblock
341          */
342         void WriteData(const std::string& data);
343         /** Convenience function: read a line from the socket
344          * @param line The line read
345          * @param delim The line delimiter
346          * @return true if a line was read
347          */
348         bool GetNextLine(std::string& line, char delim = '\n');
349         /** Useful for implementing sendq exceeded */
350         size_t getSendQSize() const;
351
352         SendQueue& GetSendQ() { return sendq; }
353
354         /**
355          * Close the socket, remove from socket engine, etc
356          */
357         virtual void Close();
358
359         /** If writeblock is true then only close the socket if all data has been sent. Otherwise, close immediately. */
360         void Close(bool writeblock);
361
362         /** This ensures that close is called prior to destructor */
363         CullResult cull() CXX11_OVERRIDE;
364
365         /** Get the IOHook of a module attached to this socket
366          * @param mod Module whose IOHook to return
367          * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
368          */
369         IOHook* GetModHook(Module* mod) const;
370
371         /** Get the last IOHook attached to this socket
372          * @return The last IOHook attached to this socket or NULL if no IOHooks are attached
373          */
374         IOHook* GetLastHook() const;
375 };
376 /**
377  * BufferedSocket is an extendable socket class which modules
378  * can use for TCP socket support. It is fully integrated
379  * into InspIRCds socket loop and attaches its sockets to
380  * the core's instance of the SocketEngine class, meaning
381  * that all use is fully asynchronous.
382  *
383  * To use BufferedSocket, you must inherit a class from it.
384  */
385 class CoreExport BufferedSocket : public StreamSocket
386 {
387  public:
388         /** Timeout object or NULL
389          */
390         SocketTimeout* Timeout;
391
392         /**
393          * The state for this socket, either
394          * listening, connecting, connected
395          * or error.
396          */
397         BufferedSocketState state;
398
399         BufferedSocket();
400         /**
401          * This constructor is used to associate
402          * an existing connecting with an BufferedSocket
403          * class. The given file descriptor must be
404          * valid, and when initialized, the BufferedSocket
405          * will be placed in CONNECTED state.
406          */
407         BufferedSocket(int newfd);
408
409         /** Begin connection to the given address
410          * This will create a socket, register with socket engine, and start the asynchronous
411          * connection process. If an error is detected at this point (such as out of file descriptors),
412          * OnError will be called; otherwise, the state will become CONNECTING.
413          * @param dest Remote endpoint to connect to.
414          * @param bind Local endpoint to connect from.
415          * @param maxtime Time to wait for connection
416          */
417         void DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime);
418
419         /** This method is called when an outbound connection on your socket is
420          * completed.
421          */
422         virtual void OnConnected();
423
424         /** When there is data waiting to be read on a socket, the OnDataReady()
425          * method is called.
426          */
427         void OnDataReady() CXX11_OVERRIDE = 0;
428
429         /**
430          * When an outbound connection fails, and the attempt times out, you
431          * will receive this event.  The method will trigger once maxtime
432          * seconds are reached (as given in the constructor) just before the
433          * socket's descriptor is closed.  A failed DNS lookup may cause this
434          * event if the DNS server is not responding, as well as a failed
435          * connect() call, because DNS lookups are nonblocking as implemented by
436          * this class.
437          */
438         virtual void OnTimeout();
439
440         virtual ~BufferedSocket();
441  protected:
442         void OnEventHandlerWrite() CXX11_OVERRIDE;
443         BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
444 };
445
446 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
447 inline void StreamSocket::DelIOHook() { iohook = NULL; }