]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Back out change, as this doesn't work properly with channel bans.. Prioritise before...
[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 any sockets you create have the same power and
98  * abilities as a socket created by the core itself.
99  * To use BufferedSocket, you must inherit a class from it,
100  * and use the BufferedSocket constructors to establish connections
101  * and bindings.
102  */
103 class CoreExport BufferedSocket : public EventHandler
104 {
105  public:
106
107         /** Bind IP
108          */
109         std::string cbindip;
110
111         /** Instance we were created by
112          */
113         InspIRCd* Instance;
114
115         /** Timeout class or NULL
116          */
117         SocketTimeout* Timeout;
118
119         /** Timeout length
120          */
121         unsigned long timeout_val;
122
123         /** Socket output buffer (binary safe)
124          */
125         std::deque<std::string> outbuffer;
126
127         /** The hostname connected to
128          */
129         char host[MAXBUF];
130
131         /** The port connected to
132          */
133         int port;
134
135         /**
136          * The state for this socket, either
137          * listening, connecting, connected
138          * or error.
139          */
140         BufferedSocketState state;
141
142         /**
143          * This value is true if the
144          * socket has timed out.
145          */
146         bool timeout;
147
148         /**
149          * The IP address being connected
150          * to stored in string form for
151          * easy retrieval by accessors.
152          */
153         char IP[MAXBUF];
154
155         /**
156          * Used by accept() to indicate the
157          * sizes of the sockaddr_in structures
158          */
159         socklen_t length;
160
161         /** Flushes the write buffer
162          */
163         bool FlushWriteBuffer();
164
165         /** Set the queue sizes
166          * This private method sets the operating system queue
167          * sizes for this socket to 65535 so that it can queue
168          * more information without application-level queueing
169          * which was required in older software.
170          */
171         void SetQueues(int nfd);
172
173         /** When the socket has been marked as closing, this flag
174          * will be set to true, then the next time the socket is
175          * examined, the socket is deleted and closed.
176          */
177         bool ClosePending;
178
179         /** Set to true when we're waiting for a write event.
180          * If this is true and a write event comes in, we
181          * call the write instead of the read method.
182          */
183         bool WaitingForWriteEvent;
184
185         /**
186          * Bind to an address
187          * @param ip IP to bind to
188          * @return True is the binding succeeded
189          */
190         bool BindAddr(const std::string &ip);
191
192         /**
193          * The default constructor does nothing
194          * and should not be used.
195          */
196         BufferedSocket(InspIRCd* SI);
197
198         /**
199          * This constructor is used to associate
200          * an existing connecting with an BufferedSocket
201          * class. The given file descriptor must be
202          * valid, and when initialized, the BufferedSocket
203          * will be set with the given IP address
204          * and placed in CONNECTED state.
205          */
206         BufferedSocket(InspIRCd* SI, int newfd, const char* ip);
207
208         /**
209          * This constructor is used to create a new outbound connection to another host.
210          * Note that if you specify a hostname in the 'ipaddr' parameter, this class will not
211          * connect. You must resolve your hostnames before passing them to BufferedSocket. To do so,
212          * you should use the nonblocking class 'Resolver'.
213          * @param ipaddr The IP to connect to, or bind to
214          * @param port The port number to connect to
215          * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated
216          * @param connectbindip When creating an outbound connection, the IP to bind the connection to. If not defined, the port is not bound.
217          * @return On exit, GetState() returns I_ERROR if an error occured, and errno can be used to read the socket error.
218          */
219         BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int port, unsigned long maxtime, const std::string &connectbindip = "");
220
221         /**
222          * This method is called when an outbound
223          * connection on your socket is completed.
224          * @return false to abort the connection, true to continue
225          */
226         virtual bool OnConnected();
227
228         /**
229          * This method is called when an error occurs.
230          * A closed socket in itself is not an error,
231          * however errors also generate close events.
232          * @param e The error type which occured
233          */
234         virtual void OnError(BufferedSocketError e);
235
236         /**
237          * When an established connection is terminated,
238          * the OnDisconnect method is triggered.
239          */
240         virtual int OnDisconnect();
241
242         /**
243          * When there is data waiting to be read on a
244          * socket, the OnDataReady() method is called.
245          * Within this method, you *MUST* call the Read()
246          * method to read any pending data. At its lowest
247          * level, this event is signalled by the core via
248          * the socket engine. If you return false from this
249          * function, the core removes your socket from its
250          * list and erases it from the socket engine, then
251          * calls BufferedSocket::Close() and deletes it.
252          * @return false to close the socket
253          */
254         virtual bool OnDataReady();
255
256         /**
257          * When it is ok to write to the socket, and a 
258          * write event was requested, this method is
259          * triggered. Within this method you should call
260          * write() or send() etc, to send data to the
261          * other end of the socket. Further write events
262          * will not be triggered unless you call WantWrite().
263          * @return false to close the socket
264          */
265         virtual bool OnWriteReady();
266
267         /**
268          * When an outbound connection fails, and the
269          * attempt times out, you will receive this event.
270          * The method will trigger once maxtime seconds are
271          * reached (as given in the constructor) just
272          * before the socket's descriptor is closed.
273          * A failed DNS lookup may cause this event if
274          * the DNS server is not responding, as well as
275          * a failed connect() call, because DNS lookups are
276          * nonblocking as implemented by this class.
277          */
278         virtual void OnTimeout();
279
280         /**
281          * Whenever close() is called, OnClose() will be
282          * called first. Please note that this means
283          * OnClose will be called alongside OnError(),
284          * OnTimeout(), and Close().
285          */
286         virtual void OnClose();
287
288         /**
289          * Reads all pending bytes from the socket
290          * into a char* array which can be up to
291          * 16 kilobytes in length.
292          */
293         virtual const char* Read();
294
295         /**
296          * Returns the IP address associated with
297          * this connection, or an empty string if
298          * no IP address exists.
299          */
300         std::string GetIP();
301
302         /**
303          * Writes a std::string to the socket. No carriage
304          * returns or linefeeds are appended to the string.
305          * @param data The data to send
306          */
307         virtual void Write(const std::string &data);
308
309         /**
310          * Changes the socket's state. The core uses this
311          * to change socket states, and you should not call
312          * it directly.
313          */
314         void SetState(BufferedSocketState s);
315
316         /**
317          * Call this to receive the next write event
318          * that comes along for this fd to the OnWriteReady
319          * method.
320          */
321         void WantWrite();
322
323         /**
324          * Returns the current socket state.
325          */
326         BufferedSocketState GetState();
327
328         /**
329          * Only the core should call this function.
330          * When called, it is assumed the socket is ready
331          * to read data, and the method call routes the
332          * event to the various methods of BufferedSocket
333          * for you to handle. This can also cause the
334          * socket's state to change.
335          */
336         bool Poll();
337
338         /**
339          * This method causes the socket to close, and may
340          * also be triggered by other methods such as OnTimeout
341          * and OnError.
342          */
343         virtual void Close();
344
345         /**
346          * The destructor may implicitly call OnClose(), and
347          * will close() and shutdown() the file descriptor
348          * used for this socket.
349          */
350         virtual ~BufferedSocket();
351
352         /**
353          * This method attempts to connect to a hostname.
354          * This method is asyncronous.
355          */
356         virtual bool DoConnect();
357
358         /** Handle event from EventHandler parent class
359          */
360         void HandleEvent(EventType et, int errornum = 0);
361
362         /** Returns true if this socket is readable
363          */
364         bool Readable();
365 };
366
367 #endif
368