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