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