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