]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Add ModeParser::IsModeChar to standardise mode validation.
[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, long secs_from_now) : Timer(secs_from_now), sock(thesock), sfd(fd) { }
93
94         /** Handle tick event
95          */
96         virtual bool Tick(time_t now);
97 };
98
99 /**
100  * StreamSocket is a class that wraps a TCP socket and handles send
101  * and receive queues, including passing them to IO hooks
102  */
103 class CoreExport StreamSocket : public EventHandler
104 {
105  public:
106         /** Socket send queue
107          */
108         class SendQueue
109         {
110          public:
111                 /** One element of the queue, a continuous buffer
112                  */
113                 typedef std::string Element;
114
115                 /** Sequence container of buffers in the queue
116                  */
117                 typedef std::deque<Element> Container;
118
119                 /** Container iterator
120                  */
121                 typedef Container::const_iterator const_iterator;
122
123                 SendQueue() : nbytes(0) { }
124
125                 /** Return whether the queue is empty
126                  * @return True if the queue is empty, false otherwise
127                  */
128                 bool empty() const { return (nbytes == 0); }
129
130                 /** Get the number of individual buffers in the queue
131                  * @return Number of individual buffers in the queue
132                  */
133                 Container::size_type size() const { return data.size(); }
134
135                 /** Get the number of queued bytes
136                  * @return Size in bytes of the data in the queue
137                  */
138                 size_t bytes() const { return nbytes; }
139
140                 /** Get the first buffer of the queue
141                  * @return A reference to the first buffer in the queue
142                  */
143                 const Element& front() const { return data.front(); }
144
145                 /** Get an iterator to the first buffer in the queue.
146                  * The returned iterator cannot be used to make modifications to the queue,
147                  * for that purpose the member functions push_*(), pop_front(), erase_front() and clear() can be used.
148                  * @return Iterator referring to the first buffer in the queue, or end() if there are no elements.
149                  */
150                 const_iterator begin() const { return data.begin(); }
151
152                 /** Get an iterator to the (theoretical) buffer one past the end of the queue.
153                  * @return Iterator referring to one element past the end of the container
154                  */
155                 const_iterator end() const { return data.end(); }
156
157                 /** Remove the first buffer in the queue
158                  */
159                 void pop_front()
160                 {
161                         nbytes -= data.front().length();
162                         data.pop_front();
163                 }
164
165                 /** Remove bytes from the beginning of the first buffer
166                  * @param n Number of bytes to remove
167                  */
168                 void erase_front(Element::size_type n)
169                 {
170                         nbytes -= n;
171                         data.front().erase(0, n);
172                 }
173
174                 /** Insert a new buffer at the beginning of the queue
175                  * @param newdata Data to add
176                  */
177                 void push_front(const Element& newdata)
178                 {
179                         data.push_front(newdata);
180                         nbytes += newdata.length();
181                 }
182
183                 /** Insert a new buffer at the end of the queue
184                  * @param newdata Data to add
185                  */
186                 void push_back(const Element& newdata)
187                 {
188                         data.push_back(newdata);
189                         nbytes += newdata.length();
190                 }
191
192                 /** Clear the queue
193                  */
194                 void clear()
195                 {
196                         data.clear();
197                         nbytes = 0;
198                 }
199
200                 void moveall(SendQueue& other)
201                 {
202                         nbytes += other.bytes();
203                         data.insert(data.end(), other.data.begin(), other.data.end());
204                         other.clear();
205                 }
206
207          private:
208                 /** Private send queue. Note that individual strings may be shared.
209                  */
210                 Container data;
211
212                 /** Length, in bytes, of the sendq
213                  */
214                 size_t nbytes;
215         };
216
217  private:
218         /** The IOHook that handles raw I/O for this socket, or NULL */
219         IOHook* iohook;
220
221         /** Send queue of the socket
222          */
223         SendQueue sendq;
224
225         /** Error - if nonempty, the socket is dead, and this is the reason. */
226         std::string error;
227
228         /** Check if the socket has an error set, if yes, call OnError
229          * @param err Error to pass to OnError()
230          */
231         void CheckError(BufferedSocketError err);
232
233         /** Read data from the socket into the recvq, if successful call OnDataReady()
234          */
235         void DoRead();
236
237         /** Send as much data contained in a SendQueue object as possible.
238          * All data which successfully sent will be removed from the SendQueue.
239          * @param sq SendQueue to flush
240          */
241         void FlushSendQ(SendQueue& sq);
242
243         /** Read incoming data into a receive queue.
244          * @param rq Receive queue to put incoming data into
245          * @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
246          */
247         int ReadToRecvQ(std::string& rq);
248
249         /** Read data from a hook chain recursively, starting at 'hook'.
250          * If 'hook' is NULL, the recvq is filled with data from SocketEngine::Recv(), otherwise it is filled with data from the
251          * next hook in the chain.
252          * @param hook Next IOHook in the chain, can be NULL
253          * @param rq Receive queue to put incoming data into
254          * @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
255          the socket and put into the recvq
256          */
257         int HookChainRead(IOHook* hook, std::string& rq);
258
259  protected:
260         std::string recvq;
261  public:
262         StreamSocket() : iohook(NULL) { }
263         IOHook* GetIOHook() const;
264         void AddIOHook(IOHook* hook);
265         void DelIOHook();
266
267         /** Flush the send queue
268          */
269         void DoWrite();
270
271         /** Called by the socket engine on a read event
272          */
273         void OnEventHandlerRead() CXX11_OVERRIDE;
274
275         /** Called by the socket engine on a write event
276          */
277         void OnEventHandlerWrite() CXX11_OVERRIDE;
278
279         /** Called by the socket engine on error
280          * @param errcode Error
281          */
282         void OnEventHandlerError(int errcode) CXX11_OVERRIDE;
283
284         /** Sets the error message for this socket. Once set, the socket is dead. */
285         void SetError(const std::string& err) { if (error.empty()) error = err; }
286
287         /** Gets the error message for this socket. */
288         const std::string& getError() const { return error; }
289
290         /** Called when new data is present in recvq */
291         virtual void OnDataReady() = 0;
292         /** Called when the socket gets an error from socket engine or IO hook */
293         virtual void OnError(BufferedSocketError e) = 0;
294
295         /** Send the given data out the socket, either now or when writes unblock
296          */
297         void WriteData(const std::string& data);
298         /** Convenience function: read a line from the socket
299          * @param line The line read
300          * @param delim The line delimiter
301          * @return true if a line was read
302          */
303         bool GetNextLine(std::string& line, char delim = '\n');
304         /** Useful for implementing sendq exceeded */
305         size_t getSendQSize() const;
306
307         SendQueue& GetSendQ() { return sendq; }
308
309         /**
310          * Close the socket, remove from socket engine, etc
311          */
312         virtual void Close();
313         /** This ensures that close is called prior to destructor */
314         virtual CullResult cull() CXX11_OVERRIDE;
315
316         /** Get the IOHook of a module attached to this socket
317          * @param mod Module whose IOHook to return
318          * @return IOHook belonging to the module or NULL if the module haven't attached an IOHook to this socket
319          */
320         IOHook* GetModHook(Module* mod) const;
321 };
322 /**
323  * BufferedSocket is an extendable socket class which modules
324  * can use for TCP socket support. It is fully integrated
325  * into InspIRCds socket loop and attaches its sockets to
326  * the core's instance of the SocketEngine class, meaning
327  * that all use is fully asynchronous.
328  *
329  * To use BufferedSocket, you must inherit a class from it.
330  */
331 class CoreExport BufferedSocket : public StreamSocket
332 {
333  public:
334         /** Timeout object or NULL
335          */
336         SocketTimeout* Timeout;
337
338         /**
339          * The state for this socket, either
340          * listening, connecting, connected
341          * or error.
342          */
343         BufferedSocketState state;
344
345         BufferedSocket();
346         /**
347          * This constructor is used to associate
348          * an existing connecting with an BufferedSocket
349          * class. The given file descriptor must be
350          * valid, and when initialized, the BufferedSocket
351          * will be placed in CONNECTED state.
352          */
353         BufferedSocket(int newfd);
354
355         /** Begin connection to the given address
356          * This will create a socket, register with socket engine, and start the asynchronous
357          * connection process. If an error is detected at this point (such as out of file descriptors),
358          * OnError will be called; otherwise, the state will become CONNECTING.
359          * @param ipaddr Address to connect to
360          * @param aport Port to connect on
361          * @param maxtime Time to wait for connection
362          * @param connectbindip Address to bind to (if NULL, no bind will be done)
363          */
364         void DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip);
365
366         /** This method is called when an outbound connection on your socket is
367          * completed.
368          */
369         virtual void OnConnected();
370
371         /** When there is data waiting to be read on a socket, the OnDataReady()
372          * method is called.
373          */
374         virtual void OnDataReady() CXX11_OVERRIDE = 0;
375
376         /**
377          * When an outbound connection fails, and the attempt times out, you
378          * will receive this event.  The method will trigger once maxtime
379          * seconds are reached (as given in the constructor) just before the
380          * socket's descriptor is closed.  A failed DNS lookup may cause this
381          * event if the DNS server is not responding, as well as a failed
382          * connect() call, because DNS lookups are nonblocking as implemented by
383          * this class.
384          */
385         virtual void OnTimeout();
386
387         virtual ~BufferedSocket();
388  protected:
389         void OnEventHandlerWrite() CXX11_OVERRIDE;
390         BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout);
391         BufferedSocketError BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip);
392 };
393
394 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
395 inline void StreamSocket::DelIOHook() { iohook = NULL; }