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