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