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