]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspsocket.h
Merge insp20
[user/henk/code/inspircd.git] / include / inspsocket.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
7  *   Copyright (C) 2006-2007 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #pragma once
25
26 #include "timer.h"
27
28 class IOHook;
29
30 /**
31  * States which a socket may be in
32  */
33 enum BufferedSocketState
34 {
35         /** Socket disconnected */
36         I_DISCONNECTED,
37         /** Socket connecting */
38         I_CONNECTING,
39         /** Socket fully connected */
40         I_CONNECTED,
41         /** Socket has an error */
42         I_ERROR
43 };
44
45 /**
46  * Error types which a socket may exhibit
47  */
48 enum BufferedSocketError
49 {
50         /** No error */
51         I_ERR_NONE,
52         /** Socket was closed by peer */
53         I_ERR_DISCONNECT,
54         /** Socket connect timed out */
55         I_ERR_TIMEOUT,
56         /** Socket could not be created */
57         I_ERR_SOCKET,
58         /** Socket could not connect (refused) */
59         I_ERR_CONNECT,
60         /** Socket could not bind to local port/ip */
61         I_ERR_BIND,
62         /** Socket could not write data */
63         I_ERR_WRITE,
64         /** No more file descriptors left to create socket! */
65         I_ERR_NOMOREFDS,
66         /** Some other error */
67         I_ERR_OTHER
68 };
69
70 /* Required forward declarations */
71 class BufferedSocket;
72
73 /** Used to time out socket connections
74  */
75 class CoreExport SocketTimeout : public Timer
76 {
77  private:
78         /** BufferedSocket the class is attached to
79          */
80         BufferedSocket* sock;
81
82         /** File descriptor of class this is attached to
83          */
84         int sfd;
85
86  public:
87         /** Create a socket timeout class
88          * @param fd File descriptor of BufferedSocket
89          * @param thesock BufferedSocket to attach to
90          * @param secs_from_now Seconds from now to time out
91          * @param now The current time
92          */
93         SocketTimeout(int fd, BufferedSocket* thesock, long secs_from_now, time_t now) : Timer(secs_from_now, now), sock(thesock), sfd(fd) { }
94
95         /** Handle tick event
96          */
97         virtual bool Tick(time_t now);
98 };
99
100 /**
101  * StreamSocket is a class that wraps a TCP socket and handles send
102  * and receive queues, including passing them to IO hooks
103  */
104 class CoreExport StreamSocket : public EventHandler
105 {
106         /** The IOHook that handles raw I/O for this socket, or NULL */
107         IOHook* iohook;
108
109         /** Private send queue. Note that individual strings may be shared
110          */
111         std::deque<std::string> sendq;
112         /** Length, in bytes, of the sendq */
113         size_t sendq_len;
114         /** Error - if nonempty, the socket is dead, and this is the reason. */
115         std::string error;
116  protected:
117         std::string recvq;
118  public:
119         StreamSocket() : iohook(NULL), sendq_len(0) {}
120         IOHook* GetIOHook() const;
121         void AddIOHook(IOHook* hook);
122         void DelIOHook();
123         /** Handle event from socket engine.
124          * This will call OnDataReady if there is *new* data in recvq
125          */
126         virtual void HandleEvent(EventType et, int errornum = 0);
127         /** Dispatched from HandleEvent */
128         virtual void DoRead();
129         /** Dispatched from HandleEvent */
130         virtual void DoWrite();
131
132         /** Sets the error message for this socket. Once set, the socket is dead. */
133         void SetError(const std::string& err) { if (error.empty()) error = err; }
134
135         /** Gets the error message for this socket. */
136         const std::string& getError() const { return error; }
137
138         /** Called when new data is present in recvq */
139         virtual void OnDataReady() = 0;
140         /** Called when the socket gets an error from socket engine or IO hook */
141         virtual void OnError(BufferedSocketError e) = 0;
142
143         /** Send the given data out the socket, either now or when writes unblock
144          */
145         void WriteData(const std::string& data);
146         /** Convenience function: read a line from the socket
147          * @param line The line read
148          * @param delim The line delimiter
149          * @return true if a line was read
150          */
151         bool GetNextLine(std::string& line, char delim = '\n');
152         /** Useful for implementing sendq exceeded */
153         inline size_t getSendQSize() const { return sendq_len; }
154
155         /**
156          * Close the socket, remove from socket engine, etc
157          */
158         virtual void Close();
159         /** This ensures that close is called prior to destructor */
160         virtual CullResult cull();
161 };
162 /**
163  * BufferedSocket is an extendable socket class which modules
164  * can use for TCP socket support. It is fully integrated
165  * into InspIRCds socket loop and attaches its sockets to
166  * the core's instance of the SocketEngine class, meaning
167  * that all use is fully asynchronous.
168  *
169  * To use BufferedSocket, you must inherit a class from it.
170  */
171 class CoreExport BufferedSocket : public StreamSocket
172 {
173  public:
174         /** Timeout object or NULL
175          */
176         SocketTimeout* Timeout;
177
178         /**
179          * The state for this socket, either
180          * listening, connecting, connected
181          * or error.
182          */
183         BufferedSocketState state;
184
185         BufferedSocket();
186         /**
187          * This constructor is used to associate
188          * an existing connecting with an BufferedSocket
189          * class. The given file descriptor must be
190          * valid, and when initialized, the BufferedSocket
191          * will be placed in CONNECTED state.
192          */
193         BufferedSocket(int newfd);
194
195         /** Begin connection to the given address
196          * This will create a socket, register with socket engine, and start the asynchronous
197          * connection process. If an error is detected at this point (such as out of file descriptors),
198          * OnError will be called; otherwise, the state will become CONNECTING.
199          * @param ipaddr Address to connect to
200          * @param aport Port to connect on
201          * @param maxtime Time to wait for connection
202          * @param connectbindip Address to bind to (if NULL, no bind will be done)
203          */
204         void DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip);
205
206         /** This method is called when an outbound connection on your socket is
207          * completed.
208          */
209         virtual void OnConnected();
210
211         /** When there is data waiting to be read on a socket, the OnDataReady()
212          * method is called.
213          */
214         virtual void OnDataReady() = 0;
215
216         /**
217          * When an outbound connection fails, and the attempt times out, you
218          * will receive this event.  The method will trigger once maxtime
219          * seconds are reached (as given in the constructor) just before the
220          * socket's descriptor is closed.  A failed DNS lookup may cause this
221          * event if the DNS server is not responding, as well as a failed
222          * connect() call, because DNS lookups are nonblocking as implemented by
223          * this class.
224          */
225         virtual void OnTimeout();
226
227         virtual ~BufferedSocket();
228  protected:
229         virtual void DoWrite();
230         BufferedSocketError BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout);
231         BufferedSocketError BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip);
232 };
233
234 inline IOHook* StreamSocket::GetIOHook() const { return iohook; }
235 inline void StreamSocket::AddIOHook(IOHook* hook) { iohook = hook; }
236 inline void StreamSocket::DelIOHook() { iohook = NULL; }