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