]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket.h
1eefc500e51a1055b1c0e43db935f7be3f77ce43
[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         /** Construct a password, optionally hashed with the other side's
150          * challenge string
151          */
152         std::string MakePass(const std::string &password, const std::string &challenge);
153
154         /** When an outbound connection finishes connecting, we receive
155          * this event, and must send our SERVER string to the other
156          * side. If the other side is happy, as outlined in the server
157          * to server docs on the inspircd.org site, the other side
158          * will then send back its own server string.
159          */
160         virtual void OnConnected();
161
162         /** Handle socket error event
163          */
164         virtual void OnError(BufferedSocketError e);
165
166         /** Sends an error to the remote server, and displays it locally to show
167          * that it was sent.
168          */
169         void SendError(const std::string &errormessage);
170
171         /** Recursively send the server tree with distances as hops.
172          * This is used during network burst to inform the other server
173          * (and any of ITS servers too) of what servers we know about.
174          * If at any point any of these servers already exist on the other
175          * end, our connection may be terminated. The hopcounts given
176          * by this function are relative, this doesn't matter so long as
177          * they are all >1, as all the remote servers re-calculate them
178          * to be relative too, with themselves as hop 0.
179          */
180         void SendServers(TreeServer* Current, TreeServer* s, int hops);
181
182         /** Returns module list as a string, filtered by filter
183          * @param filter a module version bitmask, such as VF_COMMON or VF_OPTCOMMON
184          */
185         std::string MyModules(int filter);
186
187         /** Send my capabilities to the remote side
188          */
189         void SendCapabilities(int phase);
190
191         /** Add modules to VF_COMMON list for backwards compatability */
192         void CompatAddModules(std::vector<std::string>& modlist);
193
194         /* Isolate and return the elements that are different between two lists */
195         void ListDifference(const std::string &one, const std::string &two, char sep,
196                 std::string& mleft, std::string& mright);
197
198         bool Capab(const parameterlist &params);
199
200         /** This function forces this server to quit, removing this server
201          * and any users on it (and servers and users below that, etc etc).
202          * It's very slow and pretty clunky, but luckily unless your network
203          * is having a REAL bad hair day, this function shouldnt be called
204          * too many times a month ;-)
205          */
206         void SquitServer(std::string &from, TreeServer* Current);
207
208         /** This is a wrapper function for SquitServer above, which
209          * does some validation first and passes on the SQUIT to all
210          * other remaining servers.
211          */
212         void Squit(TreeServer* Current, const std::string &reason);
213
214         /* Used on nick collision ... XXX ugly function HACK */
215         int DoCollision(User *u, time_t remotets, const std::string &remoteident, const std::string &remoteip, const std::string &remoteuid);
216
217         /** Send one or more FJOINs for a channel of users.
218          * If the length of a single line is more than 480-NICKMAX
219          * in length, it is split over multiple lines.
220          */
221         void SendFJoins(TreeServer* Current, Channel* c);
222
223         /** Send G, Q, Z and E lines */
224         void SendXLines(TreeServer* Current);
225
226         /** Send channel modes and topics */
227         void SendChannelModes(TreeServer* Current);
228
229         /** send all users and their oper state/modes */
230         void SendUsers(TreeServer* Current);
231
232         /** This function is called when we want to send a netburst to a local
233          * server. There is a set order we must do this, because for example
234          * users require their servers to exist, and channels require their
235          * users to exist. You get the idea.
236          */
237         void DoBurst(TreeServer* s);
238
239         /** This function is called when we receive data from a remote
240          * server.
241          */
242         void OnDataReady();
243
244         /** Send one or more complete lines down the socket
245          */
246         void WriteLine(std::string line);
247
248         /** Handle ERROR command */
249         void Error(parameterlist &params);
250
251         /** Remote AWAY */
252         bool Away(const std::string &prefix, parameterlist &params);
253
254         /** SAVE to resolve nick collisions without killing */
255         bool ForceNick(const std::string &prefix, parameterlist &params);
256
257         /** ENCAP command
258          */
259         void Encap(User* who, parameterlist &params);
260
261         /** OPERQUIT command
262          */
263         bool OperQuit(const std::string &prefix, parameterlist &params);
264
265         /** KILL
266          */
267         bool RemoteKill(const std::string &prefix, parameterlist &params);
268
269         /** PONG
270          */
271         bool LocalPong(const std::string &prefix, parameterlist &params);
272
273         /** VERSION
274          */
275         bool ServerVersion(const std::string &prefix, parameterlist &params);
276
277         /** ADDLINE
278          */
279         bool AddLine(const std::string &prefix, parameterlist &params);
280
281         /** DELLINE
282          */
283         bool DelLine(const std::string &prefix, parameterlist &params);
284
285         /** WHOIS
286          */
287         bool Whois(const std::string &prefix, parameterlist &params);
288
289         /** PUSH
290          */
291         bool Push(const std::string &prefix, parameterlist &params);
292
293         /** PING
294          */
295         bool LocalPing(const std::string &prefix, parameterlist &params);
296
297         /** <- (remote) <- SERVER
298          */
299         bool RemoteServer(const std::string &prefix, parameterlist &params);
300
301         /** (local) -> SERVER
302          */
303         bool Outbound_Reply_Server(parameterlist &params);
304
305         /** (local) <- SERVER
306          */
307         bool Inbound_Server(parameterlist &params);
308
309         /** Handle IRC line split
310          */
311         void Split(const std::string &line, std::string& prefix, std::string& command, parameterlist &params);
312
313         /** Process complete line from buffer
314          */
315         void ProcessLine(std::string &line);
316
317         void ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params);
318
319         /** Get this server's name
320          */
321         virtual std::string GetName();
322
323         /** Handle socket timeout from connect()
324          */
325         virtual void OnTimeout();
326         /** Handle server quit on close
327          */
328         virtual void Close();
329 };
330
331 /* Used to validate the value lengths of multiple parameters for a command */
332 struct cmd_validation
333 {
334         const char* item;
335         size_t param;
336         size_t length;
337 };
338
339 /* Used to validate the length values in CAPAB CAPABILITIES */
340 struct cap_validation
341 {
342         const char* reason;
343         const char* key;
344         size_t size;
345 };
346
347 #endif
348