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