]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Removed threaded dns (it might make a comeback some day, but as it stands its incompa...
[user/henk/code/inspircd.git] / include / inspsocket.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #ifndef __INSP_SOCKET_H__
18 #define __INSP_SOCKET_H__
19
20 #include <sstream>
21 #include <string>
22 #include <deque>
23 #include "dns.h"
24 #include "inspircd_config.h"
25 #include "socket.h"
26
27 /**
28  * States which a socket may be in
29  */
30 enum InspSocketState { I_DISCONNECTED, I_RESOLVING, I_CONNECTING, I_CONNECTED, I_LISTENING, I_ERROR };
31
32 /**
33  * Error types which a socket may exhibit
34  */
35 enum InspSocketError { I_ERR_TIMEOUT, I_ERR_SOCKET, I_ERR_CONNECT, I_ERR_BIND, I_ERR_RESOLVE, I_ERR_WRITE };
36
37 /**
38  * InspSocket is an extendable socket class which modules
39  * can use for TCP socket support. It is fully integrated
40  * into InspIRCds socket loop and attaches its sockets to
41  * the core's instance of the SocketEngine class, meaning
42  * that any sockets you create have the same power and
43  * abilities as a socket created by the core itself.
44  * To use InspSocket, you must inherit a class from it,
45  * and use the InspSocket constructors to establish connections
46  * and bindings.
47  */
48 class InspSocket : public Extensible
49 {
50 protected:
51
52         std::deque<std::string> outbuffer;
53
54         /**
55          * The file descriptor of this socket
56          */
57         int fd;
58
59         /**
60          * The resolver for this socket
61          */
62
63         /**
64          * The hostname connected to
65          */
66         char host[MAXBUF];
67
68         /**
69          * The port connected to, or the port
70          * this socket is listening on
71          */
72         int port;
73
74         /**
75          * The state for this socket, either
76          * listening, connecting, connected
77          * or error.
78          */
79         InspSocketState state;
80
81         /**
82          * The host being connected to,
83          * in sockaddr form
84          */
85         insp_sockaddr addr;
86
87         /** 
88          * The host being connected to,
89          * in in_addr form
90          */
91         insp_inaddr addy;
92
93         /**
94          * When this time is reached,
95          * the socket times out if it is
96          * in the CONNECTING state
97          */
98         time_t timeout_end;
99
100         /**
101          * This value is true if the
102          * socket has timed out.
103          */
104         bool timeout;
105         
106         /**
107          * Socket input buffer, used by read(). The class which
108          * extends InspSocket is expected to implement an extendable
109          * buffer which can grow much larger than 64k,
110          * this buffer is just designed to be temporary storage.
111          * space.
112          */
113         char ibuf[65535];
114
115         /**
116          * The IP address being connected
117          * to stored in string form for
118          * easy retrieval by accessors.
119          */
120         char IP[MAXBUF];
121
122         /**
123          * Client sockaddr structure used
124          * by accept()
125          */
126         insp_sockaddr client;
127
128         /**
129          * Server sockaddr structure used
130          * by accept()
131          */
132         insp_sockaddr server;
133
134         /**
135          * Used by accept() to indicate the
136          * sizes of the sockaddr_in structures
137          */
138         socklen_t length;
139
140         /** Flushes the write buffer
141          */
142         bool FlushWriteBuffer();
143
144         /** Set the queue sizes
145          * This private method sets the operating system queue
146          * sizes for this socket to 65535 so that it can queue
147          * more information without application-level queueing
148          * which was required in older software.
149          */
150         void SetQueues(int nfd);
151
152         /** When the socket has been marked as closing, this flag
153          * will be set to true, then the next time the socket is
154          * examined, the socket is deleted and closed.
155          */
156         bool ClosePending;
157
158         /** Set to true when we're waiting for a write event.
159          * If this is true and a write event comes in, we
160          * call the write instead of the read method.
161          */
162         bool WaitingForWriteEvent;
163
164         bool BindAddr();
165
166 public:
167
168         /**
169          * The default constructor does nothing
170          * and should not be used.
171          */
172         InspSocket();
173
174         /**
175          * This constructor is used to associate
176          * an existing connecting with an InspSocket
177          * class. The given file descriptor must be
178          * valid, and when initialized, the InspSocket
179          * will be set with the given IP address
180          * and placed in CONNECTED state.
181          */
182         InspSocket(int newfd, const char* ip);
183
184         /**
185          * This constructor is used to create a new
186          * socket, either listening for connections, or an outbound connection to another host.
187          * Note that if you specify a hostname in the 'host' parameter, then there will be an extra
188          * step involved (a nonblocking DNS lookup) which will cause your connection to be established
189          * slower than if it was an IP. Therefore, use an IP address where it is available instead.
190          * @param host The hostname to connect to, or bind to
191          * @param port The port number to connect to, or bind to
192          * @param listening true to listen on the given host:port pair, or false to connect to them
193          * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated
194          */
195         InspSocket(const std::string &host, int port, bool listening, unsigned long maxtime);
196
197         /**
198          * This method is called when an outbound
199          * connection on your socket is completed.
200          * @return false to abort the connection, true to continue
201          */
202         virtual bool OnConnected();
203
204         /**
205          * This method is called when an error occurs.
206          * A closed socket in itself is not an error,
207          * however errors also generate close events.
208          * @param e The error type which occured
209          */
210         virtual void OnError(InspSocketError e);
211
212         /**
213          * When an established connection is terminated,
214          * the OnDisconnect method is triggered.
215          */
216         virtual int OnDisconnect();
217
218         /**
219          * When there is data waiting to be read on a
220          * socket, the OnDataReady() method is called.
221          * Within this method, you *MUST* call the Read()
222          * method to read any pending data. At its lowest
223          * level, this event is signalled by the core via
224          * the socket engine. If you return false from this
225          * function, the core removes your socket from its
226          * list and erases it from the socket engine, then
227          * calls InspSocket::Close() and deletes it.
228          * @return false to close the socket
229          */
230         virtual bool OnDataReady();
231
232         virtual bool OnWriteReady();
233
234         /**
235          * When an outbound connection fails, and the
236          * attempt times out, you will receive this event.
237          * The method will trigger once maxtime seconds are
238          * reached (as given in the constructor) just
239          * before the socket's descriptor is closed.
240          * A failed DNS lookup may cause this event if
241          * the DNS server is not responding, as well as
242          * a failed connect() call, because DNS lookups are
243          * nonblocking as implemented by this class.
244          */
245         virtual void OnTimeout();
246
247         /**
248          * Whenever close() is called, OnClose() will be
249          * called first. Please note that this means
250          * OnClose will be called alongside OnError(),
251          * OnTimeout(), and Close(), and also when
252          * cancelling a listening socket by calling
253          * the destructor indirectly.
254          */
255         virtual void OnClose();
256
257         /**
258          * Reads all pending bytes from the socket
259          * into a char* array which can be up to
260          * 16 kilobytes in length.
261          */
262         virtual char* Read();
263
264         /**
265          * Returns the IP address associated with
266          * this connection, or an empty string if
267          * no IP address exists.
268          */
269         std::string GetIP();
270
271         /**
272          * This function checks if the socket has
273          * timed out yet, given the current time
274          * in the parameter.
275          * @return true if timed out, false if not timed out
276          */
277         bool Timeout(time_t current);
278
279         /**
280          * Writes a std::string to the socket. No carriage
281          * returns or linefeeds are appended to the string.
282          * @param data The data to send
283          */
284         virtual int Write(const std::string &data);
285
286         /**
287          * If your socket is a listening socket, when a new
288          * connection comes in on the socket this method will
289          * be called. Given the new file descriptor in the
290          * parameters, and the IP, it is recommended you copy
291          * them to a new instance of your socket class,
292          * e.g.:
293          *
294          * MySocket* newsocket = new MySocket(newfd,ip);
295          *
296          * Once you have done this, you can then associate the
297          * new socket with the core using Server::AddSocket().
298          */
299         virtual int OnIncomingConnection(int newfd, char* ip);
300
301         /**
302          * Changes the socket's state. The core uses this
303          * to change socket states, and you should not call
304          * it directly.
305          */
306         void SetState(InspSocketState s);
307
308         /**
309          * Call this to receive the next write event
310          * that comes along for this fd to the OnWriteReady
311          * method.
312          */
313         void WantWrite();
314
315         /**
316          * Returns the current socket state.
317          */
318         InspSocketState GetState();
319
320         /**
321          * Only the core should call this function.
322          * When called, it is assumed the socket is ready
323          * to read data, and the method call routes the
324          * event to the various methods of InspSocket
325          * for you to handle. This can also cause the
326          * socket's state to change.
327          */
328         bool Poll();
329
330         /**
331          * This method returns the socket's file descriptor
332          * as assigned by the operating system, or -1
333          * if no descriptor has been assigned.
334          */
335         int GetFd();
336
337         /**
338          * This method causes the socket to close, and may
339          * also be triggered by other methods such as OnTimeout
340          * and OnError.
341          */
342         virtual void Close();
343
344         /**
345          * The destructor may implicitly call OnClose(), and
346          * will close() and shutdown() the file descriptor
347          * used for this socket.
348          */
349         virtual ~InspSocket();
350
351         /**
352          * This method attempts to resolve the hostname,
353          * if a hostname is given and not an IP,
354          * before a connection can occur. This method is
355          * asyncronous.
356          */
357         virtual bool DoResolve();
358
359         /**
360          * This method attempts to connect to a hostname.
361          * This only occurs on a non-listening socket. This
362          * method is asyncronous.
363          */
364         virtual bool DoConnect();
365
366         /**
367          * This method marks the socket closed.
368          * The next time the core examines a socket marked
369          * as closed, the socket will be closed and the 
370          * memory reclaimed.
371          */
372         void MarkAsClosed();
373 };
374
375 #endif