]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Minor style tidyup.
[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
73         /** Server instance creating the timeout class
74          */
75         InspIRCd* ServerInstance;
76
77         /** File descriptor of class this is attached to
78          */
79         int sfd;
80
81  public:
82         /** Create a socket timeout class
83          * @param fd File descriptor of BufferedSocket
84          * @pram Instance server instance to attach to
85          * @param thesock BufferedSocket to attach to
86          * @param secs_from_now Seconds from now to time out
87          * @param now The current time
88          */
89         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) { };
90
91         /** Handle tick event
92          */
93         virtual void Tick(time_t now);
94 };
95
96 /**
97  * BufferedSocket is an extendable socket class which modules
98  * can use for TCP socket support. It is fully integrated
99  * into InspIRCds socket loop and attaches its sockets to
100  * the core's instance of the SocketEngine class, meaning
101  * that all use is fully asynchronous.
102  *
103  * To use BufferedSocket, you must inherit a class from it.
104  */
105 class CoreExport BufferedSocket : public EventHandler
106 {
107  public:
108
109         /** Bind IP
110          */
111         std::string cbindip;
112
113         /** Instance we were created by
114          */
115         InspIRCd* Instance;
116
117         /** Timeout class or NULL
118          */
119         SocketTimeout* Timeout;
120
121         /** Socket output buffer (binary safe)
122          */
123         std::deque<std::string> outbuffer;
124
125         /** The hostname connected to
126          */
127         char host[MAXBUF];
128
129         /** The port connected to
130          */
131         int port;
132
133         /**
134          * The state for this socket, either
135          * listening, connecting, connected
136          * or error.
137          */
138         BufferedSocketState state;
139
140         /**
141          * The IP address being connected
142          * to stored in string form for
143          * easy retrieval by accessors.
144          */
145         char IP[MAXBUF];
146
147         /**
148          * Used by accept() to indicate the
149          * sizes of the sockaddr_in structures
150          */
151         socklen_t length;
152
153         /** Flushes the write buffer
154          * @returns true if the writing failed, false if it was successful
155          */
156         bool FlushWriteBuffer();
157
158         /** Set the queue sizes
159          * This private method sets the operating system queue
160          * sizes for this socket to 65535 so that it can queue
161          * more information without application-level queueing
162          * which was required in older software.
163          */
164         void SetQueues();
165
166         /** When the socket has been marked as closing, this flag
167          * will be set to true, then the next time the socket is
168          * examined, the socket is deleted and closed.
169          */
170         bool ClosePending;
171
172         /**
173          * Bind to an address
174          * @param ip IP to bind to
175          * @return True is the binding succeeded
176          */
177         bool BindAddr(const std::string &ip);
178
179         /**
180          * The default constructor does nothing
181          * and should not be used.
182          */
183         BufferedSocket(InspIRCd* SI);
184
185         /**
186          * This constructor is used to associate
187          * an existing connecting with an BufferedSocket
188          * class. The given file descriptor must be
189          * valid, and when initialized, the BufferedSocket
190          * will be set with the given IP address
191          * and placed in CONNECTED state.
192          */
193         BufferedSocket(InspIRCd* SI, int newfd, const char* ip);
194
195         /**
196          * This constructor is used to create a new 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 BufferedSocket. 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
202          * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated
203          * @param connectbindip When creating an outbound connection, the IP to bind the connection to. If not defined, the port is not bound.
204          * @return On exit, GetState() returns I_ERROR if an error occured, and errno can be used to read the socket error.
205          */
206         BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int port, unsigned long maxtime, const std::string &connectbindip = "");
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(BufferedSocketError 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 BufferedSocket::Close() and deletes it.
239          * @return false to close the socket
240          */
241         virtual bool OnDataReady();
242
243         /**
244          * When it is ok to write to the socket, and a 
245          * write event was requested, this method is
246          * triggered.
247          *
248          * Within this method you should call
249          * write() or send() etc, to send data to the
250          * other end of the socket.
251          *
252          * Further write events will not be triggered
253          * unless you call SocketEngine::WantWrite().
254          *
255          * The default behaviour of this method is to
256          * flush the write buffer, respecting the IO
257          * hooking modules.
258          *
259          * XXX: this used to be virtual, ask us if you need it to be so.
260          * @return false to close the socket
261          */
262         bool OnWriteReady();
263
264         /**
265          * When an outbound connection fails, and the
266          * attempt times out, you will receive this event.
267          * The method will trigger once maxtime seconds are
268          * reached (as given in the constructor) just
269          * before the socket's descriptor is closed.
270          * A failed DNS lookup may cause this event if
271          * the DNS server is not responding, as well as
272          * a failed connect() call, because DNS lookups are
273          * nonblocking as implemented by this class.
274          */
275         virtual void OnTimeout();
276
277         /**
278          * Whenever close() is called, OnClose() will be
279          * called first. Please note that this means
280          * OnClose will be called alongside OnError(),
281          * OnTimeout(), and Close().
282          */
283         virtual void OnClose();
284
285         /**
286          * Reads all pending bytes from the socket
287          * into a char* array which can be up to
288          * 16 kilobytes in length.
289          */
290         virtual const char* Read();
291
292         /**
293          * Returns the IP address associated with
294          * this connection, or an empty string if
295          * no IP address exists.
296          */
297         std::string GetIP();
298
299         /**
300          * Writes a std::string to the socket. No carriage
301          * returns or linefeeds are appended to the string.
302          * @param data The data to send
303          */
304         virtual void Write(const std::string &data);
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(BufferedSocketState s);
312
313         /**
314          * Returns the current socket state.
315          */
316         BufferedSocketState GetState();
317
318         /** Mark a socket as being connected and call appropriate events.
319          */
320         bool InternalMarkConnected();
321
322         /**
323          * This method causes the socket to close, and may
324          * also be triggered by other methods such as OnTimeout
325          * and OnError.
326          */
327         virtual void Close();
328
329         /**
330          * The destructor may implicitly call OnClose(), and
331          * will close() and shutdown() the file descriptor
332          * used for this socket.
333          */
334         virtual ~BufferedSocket();
335
336         /**
337          * This method attempts to connect to a hostname.
338          * This method is asyncronous.
339          * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated
340          */
341         virtual bool DoConnect(unsigned long maxtime);
342
343         /** Handle event from EventHandler parent class
344          */
345         void HandleEvent(EventType et, int errornum = 0);
346
347         /** Returns true if this socket is readable
348          */
349         bool Readable();
350 };
351
352 #endif
353