]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Improve behaviour when running as root.
[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         /** Whether this socket should close once its sendq is empty */
231         bool closeonempty;
232
233         /** Whether the socket is currently closing or not, used to avoid repeatedly closing a closed socket */
234         bool closing;
235
236         /** The IOHook that handles raw I/O for this socket, or NULL */
237         IOHook* iohook;
238
239         /** Send queue of the socket
240          */
241         SendQueue sendq;
242
243         /** Error - if nonempty, the socket is dead, and this is the reason. */
244         std::string error;
245
246         /** Check if the socket has an error set, if yes, call OnError
247          * @param err Error to pass to OnError()
248          */
249         void CheckError(BufferedSocketError err);
250
251         /** Read data from the socket into the recvq, if successful call OnDataReady()
252          */
253         void DoRead();
254
255         /** Send as much data contained in a SendQueue object as possible.
256          * All data which successfully sent will be removed from the SendQueue.
257          * @param sq SendQueue to flush
258          */
259         void FlushSendQ(SendQueue& sq);
260
261         /** Read incoming data into a receive queue.
262          * @param rq Receive queue to put incoming data into
263          * @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
264          */
265         int ReadToRecvQ(std::string& rq);
266
267         /** Read data from a hook chain recursively, starting at 'hook'.
268          * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
269          * next hook in the chain.
270          * @param hook Next IOHook in the chain, can be NULL
271          * @param rq Receive queue to put incoming data into
272          * @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
273          the socket and put into the recvq
274          */
275         int HookChainRead(IOHook* hook, std::string& rq);
276
277  protected:
278         /** The data which has been received from the socket. */
279         std::string recvq;
280
281         /** Swaps the internals of this StreamSocket with another one.
282          * @param other A StreamSocket to swap internals with.
283          */
284         void SwapInternals(StreamSocket& other);
285
286  public:
287         const Type type;
288         StreamSocket(Type sstype = SS_UNKNOWN)
289                 : closeonempty(false)
290                 , closing(false)
291                 , iohook(NULL)
292                 , type(sstype)
293         {
294         }
295         IOHook* GetIOHook() const;
296         void AddIOHook(IOHook* hook);
297         void DelIOHook();
298
299         /** Flush the send queue
300          */
301         void DoWrite();
302
303         /** Called by the socket engine on a read event
304          */
305         void OnEventHandlerRead() CXX11_OVERRIDE;
306
307         /** Called by the socket engine on a write event
308          */
309         void OnEventHandlerWrite() CXX11_OVERRIDE;
310
311         /** Called by the socket engine on error
312          * @param errcode Error
313          */
314         void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
315
316         /** Sets the error message for this socket. Once set, the socket is dead. */
317         void SetError(const std::string& err) { if (error.empty()) error = err; }
318
319         /** Gets the error message for this socket. */
320         const std::string& getError() const { return error; }
321
322         /** Called when new data is present in recvq */
323         virtual void OnDataReady() = 0;
324         /** Called when the socket gets an error from socket engine or IO hook */
325         virtual void OnError(BufferedSocketError e) = 0;
326
327         /** Called when the endpoint addresses are changed.
328          * @param local The new local endpoint.
329          * @param remote The new remote endpoint.
330          * @return true if the connection is still open, false if it has been closed
331          */
332         virtual bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote);
333
334         /** Send the given data out the socket, either now or when writes unblock
335          */
336         void WriteData(const std::string& data);
337         /** Convenience function: read a line from the socket
338          * @param line The line read
339          * @param delim The line delimiter
340          * @return true if a line was read
341          */
342         bool GetNextLine(std::string& line, char delim = '\n');
343         /** Useful for implementing sendq exceeded */
344         size_t getSendQSize() const;
345
346         SendQueue& GetSendQ() { return sendq; }
347
348         /**
349          * Close the socket, remove from socket engine, etc
350          */
351         virtual void Close();
352
353         /** If writeblock is true then only close the socket if all data has been sent. Otherwise, close immediately. */
354         void Close(bool writeblock);
355
356         /** This ensures that close is called prior to destructor */
357         CullResult cull() CXX11_OVERRIDE;
358
359         /** Get the IOHook of a module attached to this socket
360          * @param mod Module whose IOHook to return
361          * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
362          */
363         IOHook* GetModHook(Module* mod) const;
364 };
365 /**
366  * BufferedSocket is an extendable socket class which modules
367  * can use for TCP socket support. It is fully integrated
368  * into InspIRCds socket loop and attaches its sockets to
369  * the core's instance of the SocketEngine class, meaning
370  * that all use is fully asynchronous.
371  *
372  * To use BufferedSocket, you must inherit a class from it.
373  */
374 class CoreExport BufferedSocket : public StreamSocket
375 {
376  public:
377         /** Timeout object or NULL
378          */
379         SocketTimeout* Timeout;
380
381         /**
382          * The state for this socket, either
383          * listening, connecting, connected
384          * or error.
385          */
386         BufferedSocketState state;
387
388         BufferedSocket();
389         /**
390          * This constructor is used to associate
391          * an existing connecting with an BufferedSocket
392          * class. The given file descriptor must be
393          * valid, and when initialized, the BufferedSocket
394          * will be placed in CONNECTED state.
395          */
396         BufferedSocket(int newfd);
397
398         /** Begin connection to the given address
399          * This will create a socket, register with socket engine, and start the asynchronous
400          * connection process. If an error is detected at this point (such as out of file descriptors),
401          * OnError will be called; otherwise, the state will become CONNECTING.
402          * @param dest Remote endpoint to connect to.
403          * @param bind Local endpoint to connect from.
404          * @param maxtime Time to wait for connection
405          */
406         void DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime);
407
408         /** This method is called when an outbound connection on your socket is
409          * completed.
410          */
411         virtual void OnConnected();
412
413         /** When there is data waiting to be read on a socket, the OnDataReady()
414          * method is called.
415          */
416         void OnDataReady() CXX11_OVERRIDE = 0;
417
418         /**
419          * When an outbound connection fails, and the attempt times out, you
420          * will receive this event.  The method will trigger once maxtime
421          * seconds are reached (as given in the constructor) just before the
422          * socket's descriptor is closed.  A failed DNS lookup may cause this
423          * event if the DNS server is not responding, as well as a failed
424          * connect() call, because DNS lookups are nonblocking as implemented by
425          * this class.
426          */
427         virtual void OnTimeout();
428
429         virtual ~BufferedSocket();
430  protected:
431         void OnEventHandlerWrite() CXX11_OVERRIDE;
432         BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout);
433 };
434
435 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
436 inline void StreamSocket::DelIOHook() { iohook = NULL; }