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