]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
There is absolutely no need to cache connect timeout.
[user/henk/code/inspircd.git] / include / inspsocket.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef __INSP_SOCKET_H__
15 #define __INSP_SOCKET_H__
16
17 #include "timer.h"
18
19 /**
20  * States which a socket may be in
21  */
22 enum BufferedSocketState
23 {
24         /** Socket disconnected */
25         I_DISCONNECTED,
26         /** Socket connecting */
27         I_CONNECTING,
28         /** Socket fully connected */
29         I_CONNECTED,
30         /** Socket has an error */
31         I_ERROR
32 };
33
34 /**
35  * Error types which a socket may exhibit
36  */
37 enum BufferedSocketError
38 {
39         /** Socket connect timed out */
40         I_ERR_TIMEOUT,
41         /** Socket could not be created */
42         I_ERR_SOCKET,
43         /** Socket could not connect (refused) */
44         I_ERR_CONNECT,
45         /** Socket could not bind to local port/ip */
46         I_ERR_BIND,
47         /** Socket could not reslve host (depreciated) */
48         I_ERR_RESOLVE,
49         /** Socket could not write data */
50         I_ERR_WRITE,
51         /** No more file descriptors left to create socket! */
52         I_ERR_NOMOREFDS
53 };
54
55 /* Required forward declarations */
56 class BufferedSocket;
57 class InspIRCd;
58
59 using irc::sockets::insp_sockaddr;
60 using irc::sockets::insp_inaddr;
61 using irc::sockets::insp_ntoa;
62 using irc::sockets::insp_aton;
63
64 /** Used to time out socket connections
65  */
66 class CoreExport SocketTimeout : public Timer
67 {
68  private:
69         /** BufferedSocket the class is attached to
70          */
71         BufferedSocket* sock;
72         /** Server instance creating the timeout class
73          */
74         InspIRCd* ServerInstance;
75         /** File descriptor of class this is attached to
76          */
77         int sfd;
78  public:
79         /** Create a socket timeout class
80          * @param fd File descriptor of BufferedSocket
81          * @pram Instance server instance to attach to
82          * @param thesock BufferedSocket to attach to
83          * @param secs_from_now Seconds from now to time out
84          * @param now The current time
85          */
86         SocketTimeout(int fd, InspIRCd* Instance, BufferedSocket* thesock, long secs_from_now, time_t now) : Timer(secs_from_now, now), sock(thesock), ServerInstance(Instance), sfd(fd) { };
87         /** Handle tick event
88          */
89         virtual void Tick(time_t now);
90 };
91
92 /**
93  * BufferedSocket is an extendable socket class which modules
94  * can use for TCP socket support. It is fully integrated
95  * into InspIRCds socket loop and attaches its sockets to
96  * the core's instance of the SocketEngine class, meaning
97  * that any sockets you create have the same power and
98  * abilities as a socket created by the core itself.
99  * To use BufferedSocket, you must inherit a class from it,
100  * and use the BufferedSocket constructors to establish connections
101  * and bindings.
102  */
103 class CoreExport BufferedSocket : public EventHandler
104 {
105  public:
106
107         /** Bind IP
108          */
109         std::string cbindip;
110
111         /** Instance we were created by
112          */
113         InspIRCd* Instance;
114
115         /** Timeout class or NULL
116          */
117         SocketTimeout* Timeout;
118
119         /** Socket output buffer (binary safe)
120          */
121         std::deque<std::string> outbuffer;
122
123         /** The hostname connected to
124          */
125         char host[MAXBUF];
126
127         /** The port connected to
128          */
129         int port;
130
131         /**
132          * The state for this socket, either
133          * listening, connecting, connected
134          * or error.
135          */
136         BufferedSocketState state;
137
138         /**
139          * The IP address being connected
140          * to stored in string form for
141          * easy retrieval by accessors.
142          */
143         char IP[MAXBUF];
144
145         /**
146          * Used by accept() to indicate the
147          * sizes of the sockaddr_in structures
148          */
149         socklen_t length;
150
151         /** Flushes the write buffer
152          * @returns true if the writing failed, false if it was successful
153          */
154         bool FlushWriteBuffer();
155
156         /** Set the queue sizes
157          * This private method sets the operating system queue
158          * sizes for this socket to 65535 so that it can queue
159          * more information without application-level queueing
160          * which was required in older software.
161          */
162         void SetQueues(int nfd);
163
164         /** When the socket has been marked as closing, this flag
165          * will be set to true, then the next time the socket is
166          * examined, the socket is deleted and closed.
167          */
168         bool ClosePending;
169
170         /**
171          * Bind to an address
172          * @param ip IP to bind to
173          * @return True is the binding succeeded
174          */
175         bool BindAddr(const std::string &ip);
176
177         /**
178          * The default constructor does nothing
179          * and should not be used.
180          */
181         BufferedSocket(InspIRCd* SI);
182
183         /**
184          * This constructor is used to associate
185          * an existing connecting with an BufferedSocket
186          * class. The given file descriptor must be
187          * valid, and when initialized, the BufferedSocket
188          * will be set with the given IP address
189          * and placed in CONNECTED state.
190          */
191         BufferedSocket(InspIRCd* SI, int newfd, const char* ip);
192
193         /**
194          * This constructor is used to create a new outbound connection to another host.
195          * Note that if you specify a hostname in the 'ipaddr' parameter, this class will not
196          * connect. You must resolve your hostnames before passing them to BufferedSocket. To do so,
197          * you should use the nonblocking class 'Resolver'.
198          * @param ipaddr The IP to connect to, or bind to
199          * @param port The port number to connect to
200          * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated
201          * @param connectbindip When creating an outbound connection, the IP to bind the connection to. If not defined, the port is not bound.
202          * @return On exit, GetState() returns I_ERROR if an error occured, and errno can be used to read the socket error.
203          */
204         BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int port, unsigned long maxtime, const std::string &connectbindip = "");
205
206         /**
207          * This method is called when an outbound
208          * connection on your socket is completed.
209          * @return false to abort the connection, true to continue
210          */
211         virtual bool OnConnected();
212
213         /**
214          * This method is called when an error occurs.
215          * A closed socket in itself is not an error,
216          * however errors also generate close events.
217          * @param e The error type which occured
218          */
219         virtual void OnError(BufferedSocketError e);
220
221         /**
222          * When an established connection is terminated,
223          * the OnDisconnect method is triggered.
224          */
225         virtual int OnDisconnect();
226
227         /**
228          * When there is data waiting to be read on a
229          * socket, the OnDataReady() method is called.
230          * Within this method, you *MUST* call the Read()
231          * method to read any pending data. At its lowest
232          * level, this event is signalled by the core via
233          * the socket engine. If you return false from this
234          * function, the core removes your socket from its
235          * list and erases it from the socket engine, then
236          * calls BufferedSocket::Close() and deletes it.
237          * @return false to close the socket
238          */
239         virtual bool OnDataReady();
240
241         /**
242          * When it is ok to write to the socket, and a 
243          * write event was requested, this method is
244          * triggered.
245          *
246          * Within this method you should call
247          * write() or send() etc, to send data to the
248          * other end of the socket.
249          *
250          * Further write events will not be triggered
251          * unless you call WantWrite().
252          *
253          * The default behaviour of this method is to
254          * flush the write buffer, respecting the IO
255          * hooking modules.
256          *
257          * XXX: this used to be virtual, ask us if you need it to be so.
258          * @return false to close the socket
259          */
260         bool OnWriteReady();
261
262         /**
263          * When an outbound connection fails, and the
264          * attempt times out, you will receive this event.
265          * The method will trigger once maxtime seconds are
266          * reached (as given in the constructor) just
267          * before the socket's descriptor is closed.
268          * A failed DNS lookup may cause this event if
269          * the DNS server is not responding, as well as
270          * a failed connect() call, because DNS lookups are
271          * nonblocking as implemented by this class.
272          */
273         virtual void OnTimeout();
274
275         /**
276          * Whenever close() is called, OnClose() will be
277          * called first. Please note that this means
278          * OnClose will be called alongside OnError(),
279          * OnTimeout(), and Close().
280          */
281         virtual void OnClose();
282
283         /**
284          * Reads all pending bytes from the socket
285          * into a char* array which can be up to
286          * 16 kilobytes in length.
287          */
288         virtual const char* Read();
289
290         /**
291          * Returns the IP address associated with
292          * this connection, or an empty string if
293          * no IP address exists.
294          */
295         std::string GetIP();
296
297         /**
298          * Writes a std::string to the socket. No carriage
299          * returns or linefeeds are appended to the string.
300          * @param data The data to send
301          */
302         virtual void Write(const std::string &data);
303
304         /**
305          * Changes the socket's state. The core uses this
306          * to change socket states, and you should not call
307          * it directly.
308          */
309         void SetState(BufferedSocketState s);
310
311         /**
312          * Call this to receive the next write event
313          * that comes along for this fd to the OnWriteReady
314          * method.
315          */
316         void WantWrite();
317
318         /**
319          * Returns the current socket state.
320          */
321         BufferedSocketState GetState();
322
323         /**
324          * Only the core should call this function.
325          * When called, it is assumed the socket is ready
326          * to read data, and the method call routes the
327          * event to the various methods of BufferedSocket
328          * for you to handle. This can also cause the
329          * socket's state to change.
330          */
331         bool Poll();
332
333         /**
334          * This method causes the socket to close, and may
335          * also be triggered by other methods such as OnTimeout
336          * and OnError.
337          */
338         virtual void Close();
339
340         /**
341          * The destructor may implicitly call OnClose(), and
342          * will close() and shutdown() the file descriptor
343          * used for this socket.
344          */
345         virtual ~BufferedSocket();
346
347         /**
348          * This method attempts to connect to a hostname.
349          * This method is asyncronous.
350          * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated
351          */
352         virtual bool DoConnect(unsigned long maxtime);
353
354         /** Handle event from EventHandler parent class
355          */
356         void HandleEvent(EventType et, int errornum = 0);
357
358         /** Returns true if this socket is readable
359          */
360         bool Readable();
361 };
362
363 #endif
364