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