]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket.h
4438b473d3298a316bfb146eb89b7816cfdd6679
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 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 __TREESOCKET_H__
15 #define __TREESOCKET_H__
16
17 #include "socket.h"
18 #include "inspircd.h"
19 #include "xline.h"
20
21 #include "utils.h"
22
23 /*
24  * The server list in InspIRCd is maintained as two structures
25  * which hold the data in different ways. Most of the time, we
26  * want to very quicky obtain three pieces of information:
27  *
28  * (1) The information on a server
29  * (2) The information on the server we must send data through
30  *     to actually REACH the server we're after
31  * (3) Potentially, the child/parent objects of this server
32  *
33  * The InspIRCd spanning protocol provides easy access to these
34  * by storing the data firstly in a recursive structure, where
35  * each item references its parent item, and a dynamic list
36  * of child items, and another structure which stores the items
37  * hashed, linearly. This means that if we want to find a server
38  * by name quickly, we can look it up in the hash, avoiding
39  * any O(n) lookups. If however, during a split or sync, we want
40  * to apply an operation to a server, and any of its child objects
41  * we can resort to recursion to walk the tree structure.
42  * Any socket can have one of five states at any one time.
43  *
44  * CONNECTING:  indicates an outbound socket which is
45  *                                                      waiting to be writeable.
46  * WAIT_AUTH_1: indicates the socket is outbound and
47  *                                                      has successfully connected, but has not
48  *                                                      yet sent and received SERVER strings.
49  * WAIT_AUTH_2: indicates that the socket is inbound
50  *                                                      but has not yet sent and received
51  *                                                      SERVER strings.
52  * CONNECTED:   represents a fully authorized, fully
53  *                                                      connected server.
54  * DYING:       represents a server that has had an error.
55  */
56 enum ServerState { CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED, DYING };
57
58 struct CapabData
59 {
60         std::string ModuleList;                 /* Required module list of other server from CAPAB */
61         std::string OptModuleList;              /* Optional module list of other server from CAPAB */
62         std::string ChanModes;
63         std::string UserModes;
64         std::map<std::string,std::string> CapKeys;      /* CAPAB keys from other server */
65         std::string ourchallenge;               /* Challenge sent for challenge/response */
66         std::string theirchallenge;             /* Challenge recv for challenge/response */
67         std::string OutboundPass;               /* Outbound password */
68         int capab_phase;                        /* Have sent CAPAB already */
69         bool auth_fingerprint;                  /* Did we auth using SSL fingerprint */
70         bool auth_challenge;                    /* Did we auth using challenge/response */
71 };
72
73 /** Every SERVER connection inbound or outbound is represented by
74  * an object of type TreeSocket.
75  * TreeSockets, being inherited from BufferedSocket, can be tied into
76  * the core socket engine, and we cn therefore receive activity events
77  * for them, just like activex objects on speed. (yes really, that
78  * is a technical term!) Each of these which relates to a locally
79  * connected server is assocated with it, by hooking it onto a
80  * TreeSocket class using its constructor. In this way, we can
81  * maintain a list of servers, some of which are directly connected,
82  * some of which are not.
83  */
84 class TreeSocket : public BufferedSocket
85 {
86         SpanningTreeUtilities* Utils;           /* Utility class */
87         std::string myhost;                     /* Canonical hostname */
88         ServerState LinkState;                  /* Link state */
89         std::string InboundServerName;          /* Server name sent to us by other side */
90         std::string InboundDescription;         /* Server description (GECOS) sent to us by the other side */
91         std::string InboundSID;                 /* Server ID sent to us by the other side */
92         std::string IP;
93         CapabData* capab;
94         int num_lost_users;                     /* Users lost in split */
95         int num_lost_servers;                   /* Servers lost in split */
96         time_t NextPing;                        /* Time when we are due to ping this server */
97         bool LastPingWasGood;                   /* Responded to last ping we sent? */
98         int proto_version;                      /* Remote protocol version */
99  public:
100         reference<Autoconnect> myautoconnect;           /* Autoconnect used to cause this connection, if any */
101         time_t age;
102
103         /** Because most of the I/O gubbins are encapsulated within
104          * BufferedSocket, we just call the superclass constructor for
105          * most of the action, and append a few of our own values
106          * to it.
107          */
108         TreeSocket(SpanningTreeUtilities* Util, const std::string& host, int port, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Autoconnect* myac, const std::string& Hook);
109
110         /** When a listening socket gives us a new file descriptor,
111          * we must associate it with a socket without creating a new
112          * connection. This constructor is used for this purpose.
113          */
114         TreeSocket(SpanningTreeUtilities* Util, int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server);
115
116         /** Get link state
117          */
118         ServerState GetLinkState();
119
120         /** Get challenge set in our CAPAB for challenge/response
121          */
122         const std::string& GetOurChallenge();
123
124         /** Get challenge set in our CAPAB for challenge/response
125          */
126         void SetOurChallenge(const std::string &c);
127
128         /** Get challenge set in their CAPAB for challenge/response
129          */
130         const std::string& GetTheirChallenge();
131
132         /** Get challenge set in their CAPAB for challenge/response
133          */
134         void SetTheirChallenge(const std::string &c);
135
136         /** Compare two passwords based on authentication scheme
137          */
138         bool ComparePass(const Link& link, const std::string &theirs);
139
140         /** Clean up information used only during server negotiation
141          */
142         void CleanNegotiationInfo();
143
144         CullResult cull();
145         /** Destructor
146          */
147         ~TreeSocket();
148
149         /** Generate random string used for challenge-response auth
150          */
151         std::string RandString(unsigned int length);
152
153         /** Construct a password, optionally hashed with the other side's
154          * challenge string
155          */
156         std::string MakePass(const std::string &password, const std::string &challenge);
157
158         /** When an outbound connection finishes connecting, we receive
159          * this event, and must send our SERVER string to the other
160          * side. If the other side is happy, as outlined in the server
161          * to server docs on the inspircd.org site, the other side
162          * will then send back its own server string.
163          */
164         virtual void OnConnected();
165
166         /** Handle socket error event
167          */
168         virtual void OnError(BufferedSocketError e);
169
170         /** Sends an error to the remote server, and displays it locally to show
171          * that it was sent.
172          */
173         void SendError(const std::string &errormessage);
174
175         /** Recursively send the server tree with distances as hops.
176          * This is used during network burst to inform the other server
177          * (and any of ITS servers too) of what servers we know about.
178          * If at any point any of these servers already exist on the other
179          * end, our connection may be terminated. The hopcounts given
180          * by this function are relative, this doesn't matter so long as
181          * they are all >1, as all the remote servers re-calculate them
182          * to be relative too, with themselves as hop 0.
183          */
184         void SendServers(TreeServer* Current, TreeServer* s, int hops);
185
186         /** Returns module list as a string, filtered by filter
187          * @param filter a module version bitmask, such as VF_COMMON or VF_OPTCOMMON
188          */
189         std::string MyModules(int filter);
190
191         /** Send my capabilities to the remote side
192          */
193         void SendCapabilities(int phase);
194
195         /** Add modules to VF_COMMON list for backwards compatability */
196         void CompatAddModules(std::vector<std::string>& modlist);
197
198         /* Isolate and return the elements that are different between two lists */
199         void ListDifference(const std::string &one, const std::string &two, char sep,
200                 std::string& mleft, std::string& mright);
201
202         bool Capab(const parameterlist &params);
203
204         /** This function forces this server to quit, removing this server
205          * and any users on it (and servers and users below that, etc etc).
206          * It's very slow and pretty clunky, but luckily unless your network
207          * is having a REAL bad hair day, this function shouldnt be called
208          * too many times a month ;-)
209          */
210         void SquitServer(std::string &from, TreeServer* Current);
211
212         /** This is a wrapper function for SquitServer above, which
213          * does some validation first and passes on the SQUIT to all
214          * other remaining servers.
215          */
216         void Squit(TreeServer* Current, const std::string &reason);
217
218         /* Used on nick collision ... XXX ugly function HACK */
219         int DoCollision(User *u, time_t remotets, const std::string &remoteident, const std::string &remoteip, const std::string &remoteuid);
220
221         /** Send one or more FJOINs for a channel of users.
222          * If the length of a single line is more than 480-NICKMAX
223          * in length, it is split over multiple lines.
224          */
225         void SendFJoins(TreeServer* Current, Channel* c);
226
227         /** Send G, Q, Z and E lines */
228         void SendXLines(TreeServer* Current);
229
230         /** Send channel modes and topics */
231         void SendChannelModes(TreeServer* Current);
232
233         /** send all users and their oper state/modes */
234         void SendUsers(TreeServer* Current);
235
236         /** This function is called when we want to send a netburst to a local
237          * server. There is a set order we must do this, because for example
238          * users require their servers to exist, and channels require their
239          * users to exist. You get the idea.
240          */
241         void DoBurst(TreeServer* s);
242
243         /** This function is called when we receive data from a remote
244          * server.
245          */
246         void OnDataReady();
247
248         /** Send one or more complete lines down the socket
249          */
250         void WriteLine(std::string line);
251
252         /** Handle ERROR command */
253         void Error(parameterlist &params);
254
255         /** Remote AWAY */
256         bool Away(const std::string &prefix, parameterlist &params);
257
258         /** SAVE to resolve nick collisions without killing */
259         bool ForceNick(const std::string &prefix, parameterlist &params);
260
261         /** ENCAP command
262          */
263         void Encap(User* who, parameterlist &params);
264
265         /** OPERQUIT command
266          */
267         bool OperQuit(const std::string &prefix, parameterlist &params);
268
269         /** KILL
270          */
271         bool RemoteKill(const std::string &prefix, parameterlist &params);
272
273         /** PONG
274          */
275         bool LocalPong(const std::string &prefix, parameterlist &params);
276
277         /** VERSION
278          */
279         bool ServerVersion(const std::string &prefix, parameterlist &params);
280
281         /** ADDLINE
282          */
283         bool AddLine(const std::string &prefix, parameterlist &params);
284
285         /** DELLINE
286          */
287         bool DelLine(const std::string &prefix, parameterlist &params);
288
289         /** WHOIS
290          */
291         bool Whois(const std::string &prefix, parameterlist &params);
292
293         /** PUSH
294          */
295         bool Push(const std::string &prefix, parameterlist &params);
296
297         /** PING
298          */
299         bool LocalPing(const std::string &prefix, parameterlist &params);
300
301         /** <- (remote) <- SERVER
302          */
303         bool RemoteServer(const std::string &prefix, parameterlist &params);
304
305         /** (local) -> SERVER
306          */
307         bool Outbound_Reply_Server(parameterlist &params);
308
309         /** (local) <- SERVER
310          */
311         bool Inbound_Server(parameterlist &params);
312
313         /** Handle IRC line split
314          */
315         void Split(const std::string &line, std::string& prefix, std::string& command, parameterlist &params);
316
317         /** Process complete line from buffer
318          */
319         void ProcessLine(std::string &line);
320
321         void ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params);
322
323         /** Get this server's name
324          */
325         virtual std::string GetName();
326
327         /** Handle socket timeout from connect()
328          */
329         virtual void OnTimeout();
330         /** Handle server quit on close
331          */
332         virtual void Close();
333 };
334
335 /* Used to validate the value lengths of multiple parameters for a command */
336 struct cmd_validation
337 {
338         const char* item;
339         size_t param;
340         size_t length;
341 };
342
343 /* Used to validate the length values in CAPAB CAPABILITIES */
344 struct cap_validation
345 {
346         const char* reason;
347         const char* key;
348         size_t size;
349 };
350
351 #endif
352