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