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