]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
m_spanningtree Remove duplicate code for sending channel messages from RouteCommand()
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2007-2008, 2012 Robin Burchell <robin+git@viroteck.net>
5  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "inspircd.h"
26
27 #include "main.h"
28 #include "utils.h"
29 #include "treeserver.h"
30 #include "treesocket.h"
31 #include "resolvers.h"
32
33 /* Handle ERROR command */
34 void TreeSocket::Error(parameterlist &params)
35 {
36         std::string msg = params.size() ? params[0] : "";
37         SetError("received ERROR " + msg);
38 }
39
40 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
41 {
42         irc::tokenstream tokens(line);
43
44         if (!tokens.GetToken(prefix))
45                 return;
46
47         if (prefix[0] == ':')
48         {
49                 prefix = prefix.substr(1);
50
51                 if (prefix.empty())
52                 {
53                         this->SendError("BUG (?) Empty prefix received: " + line);
54                         return;
55                 }
56                 if (!tokens.GetToken(command))
57                 {
58                         this->SendError("BUG (?) Empty command received: " + line);
59                         return;
60                 }
61         }
62         else
63         {
64                 command = prefix;
65                 prefix.clear();
66         }
67         if (command.empty())
68                 this->SendError("BUG (?) Empty command received: " + line);
69
70         std::string param;
71         while (tokens.GetToken(param))
72         {
73                 params.push_back(param);
74         }
75 }
76
77 void TreeSocket::ProcessLine(std::string &line)
78 {
79         std::string prefix;
80         std::string command;
81         parameterlist params;
82
83         ServerInstance->Logs->Log(MODNAME, LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
84
85         Split(line, prefix, command, params);
86
87         if (command.empty())
88                 return;
89
90         switch (this->LinkState)
91         {
92                 case WAIT_AUTH_1:
93                         /*
94                          * State WAIT_AUTH_1:
95                          *  Waiting for SERVER command from remote server. Server initiating
96                          *  the connection sends the first SERVER command, listening server
97                          *  replies with theirs if its happy, then if the initiator is happy,
98                          *  it starts to send its net sync, which starts the merge, otherwise
99                          *  it sends an ERROR.
100                          */
101                         if (command == "PASS")
102                         {
103                                 /*
104                                  * Ignore this silently. Some services packages insist on sending PASS, even
105                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
106                                  * as it's an unknown command (effectively), it will cause the connection to be
107                                  * closed, which probably isn't what people want. -- w00t
108                                  */
109                         }
110                         else if (command == "SERVER")
111                         {
112                                 this->Inbound_Server(params);
113                         }
114                         else if (command == "ERROR")
115                         {
116                                 this->Error(params);
117                         }
118                         else if (command == "USER")
119                         {
120                                 this->SendError("Client connections to this port are prohibited.");
121                         }
122                         else if (command == "CAPAB")
123                         {
124                                 this->Capab(params);
125                         }
126                         else
127                         {
128                                 this->SendError("Invalid command in negotiation phase: " + command);
129                         }
130                 break;
131                 case WAIT_AUTH_2:
132                         /*
133                          * State WAIT_AUTH_2:
134                          *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
135                          *  The other option at this stage of things, of course, is for them to close our connection thanks
136                          *  to invalid credentials.. -- w
137                          */
138                         if (command == "SERVER")
139                         {
140                                 /*
141                                  * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
142                                  * Both of these aren't allowable, so block them here. -- w
143                                  */
144                                 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
145                         }
146                         else if (command == "BURST")
147                         {
148                                 if (params.size())
149                                 {
150                                         time_t them = ConvToInt(params[0]);
151                                         time_t delta = them - ServerInstance->Time();
152                                         if ((delta < -600) || (delta > 600))
153                                         {
154                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs((long)delta));
155                                                 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
156                                                 return;
157                                         }
158                                         else if ((delta < -30) || (delta > 30))
159                                         {
160                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
161                                         }
162                                 }
163
164                                 // Check for duplicate server name/sid again, it's possible that a new
165                                 // server was introduced while we were waiting for them to send BURST.
166                                 // (we do not reserve their server name/sid when they send SERVER, we do it now)
167                                 if (!CheckDuplicate(capab->name, capab->sid))
168                                         return;
169
170                                 this->LinkState = CONNECTED;
171                                 Utils->timeoutlist.erase(this);
172
173                                 linkID = capab->name;
174
175                                 MyRoot = new TreeServer(capab->name, capab->description, capab->sid, Utils->TreeRoot, this, capab->hidden);
176                                 Utils->TreeRoot->AddChild(MyRoot);
177
178                                 MyRoot->bursting = true;
179                                 this->DoBurst(MyRoot);
180
181                                 parameterlist sparams;
182                                 sparams.push_back(MyRoot->GetName());
183                                 sparams.push_back("*");
184                                 sparams.push_back("0");
185                                 sparams.push_back(MyRoot->GetID());
186                                 sparams.push_back(":" + MyRoot->GetDesc());
187                                 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(), "SERVER", sparams, MyRoot);
188                                 Utils->DoOneToAllButSender(MyRoot->GetID(), "BURST", params, MyRoot);
189                         }
190                         else if (command == "ERROR")
191                         {
192                                 this->Error(params);
193                         }
194                         else if (command == "CAPAB")
195                         {
196                                 this->Capab(params);
197                         }
198
199                 break;
200                 case CONNECTING:
201                         /*
202                          * State CONNECTING:
203                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
204                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
205                          *  + our netburst, which will put them into CONNECTED state. -- w
206                          */
207                         if (command == "SERVER")
208                         {
209                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
210                                 this->Outbound_Reply_Server(params);
211                         }
212                         else if (command == "ERROR")
213                         {
214                                 this->Error(params);
215                         }
216                         else if (command == "CAPAB")
217                         {
218                                 this->Capab(params);
219                         }
220                 break;
221                 case CONNECTED:
222                         /*
223                          * State CONNECTED:
224                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
225                          *  Anything from here on should be accepted a little more reasonably.
226                          */
227                         this->ProcessConnectedLine(prefix, command, params);
228                 break;
229                 case DYING:
230                 break;
231         }
232 }
233
234 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
235 {
236         User* who = ServerInstance->FindUUID(prefix);
237         std::string direction;
238
239         if (!who)
240         {
241                 TreeServer* ServerSource = Utils->FindServer(prefix);
242                 if (prefix.empty())
243                         ServerSource = MyRoot;
244
245                 if (ServerSource)
246                 {
247                         who = ServerSource->ServerUser;
248                 }
249                 else
250                 {
251                         /* It is important that we don't close the link here, unknown prefix can occur
252                          * due to various race conditions such as the KILL message for a user somehow
253                          * crossing the users QUIT further upstream from the server. Thanks jilles!
254                          */
255
256                         if ((prefix.length() == UIDGenerator::UUID_LENGTH) && (isdigit(prefix[0])) &&
257                                 ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE")))
258                         {
259                                 /* Special case, we cannot drop these commands as they've been committed already on a
260                                  * part of the network by the time we receive them, so in this scenario pretend the
261                                  * command came from a server to avoid desync.
262                                  */
263
264                                 who = ServerInstance->FindUUID(prefix.substr(0, 3));
265                                 if (!who)
266                                         who = this->MyRoot->ServerUser;
267                         }
268                         else
269                         {
270                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
271                                         command.c_str(), prefix.c_str());
272                                 return;
273                         }
274                 }
275         }
276
277         // Make sure prefix is still good
278         direction = who->server;
279         prefix = who->uuid;
280
281         /*
282          * Check for fake direction here, and drop any instances that are found.
283          * What is fake direction? Imagine the following server setup:
284          *    0AA <-> 0AB <-> 0AC
285          * Fake direction would be 0AC sending a message to 0AB claiming to be from
286          * 0AA, or something similar. Basically, a message taking a path that *cannot*
287          * be correct.
288          *
289          * When would this be seen?
290          * Well, hopefully never. It could be caused by race conditions, bugs, or
291          * "miscreant" servers, though, so let's check anyway. -- w
292          *
293          * We also check here for totally invalid prefixes (prefixes that are neither
294          * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
295          * to the higher level functions. -- B
296          */
297         TreeServer* route_back_again = Utils->BestRouteTo(direction);
298         if ((!route_back_again) || (route_back_again->GetSocket() != this))
299         {
300                 if (route_back_again)
301                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Protocol violation: Fake direction '%s' from connection '%s'",
302                                 prefix.c_str(),linkID.c_str());
303                 return;
304         }
305
306         // Translate commands coming from servers using an older protocol
307         if (proto_version < ProtocolVersion)
308         {
309                 if (!PreProcessOldProtocolMessage(who, command, params))
310                         return;
311         }
312
313         ServerCommand* scmd = Utils->Creator->CmdManager.GetHandler(command);
314         CommandBase* cmdbase = scmd;
315         Command* cmd;
316         if (!scmd)
317         {
318                 // Not a special server-to-server command
319                 cmd = ServerInstance->Parser->GetHandler(command);
320                 if (!cmd)
321                 {
322                         irc::stringjoiner pmlist(params);
323                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Unrecognised S2S command :%s %s %s",
324                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
325                         SendError("Unrecognised command '" + command + "' -- possibly loaded mismatched modules");
326                         return;
327                 }
328                 cmdbase = cmd;
329         }
330
331         if (params.size() < cmdbase->min_params)
332         {
333                 irc::stringjoiner pmlist(params);
334                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Insufficient parameters for S2S command :%s %s %s",
335                         who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
336                 SendError("Insufficient parameters for command '" + command + "'");
337                 return;
338         }
339
340         if ((!params.empty()) && (params.back().empty()) && (!cmdbase->allow_empty_last_param))
341         {
342                 // the last param is empty and the command handler doesn't allow that, check if there will be enough params if we drop the last
343                 if (params.size()-1 < cmdbase->min_params)
344                         return;
345                 params.pop_back();
346         }
347
348         CmdResult res;
349         if (scmd)
350                 res = scmd->Handle(who, params);
351         else
352                 res = cmd->Handle(params, who);
353
354         if (res == CMD_INVALID)
355         {
356                 irc::stringjoiner pmlist(params);
357                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error handling S2S command :%s %s %s",
358                         who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
359                 SendError("Error handling '" + command + "' -- possibly loaded mismatched modules");
360         }
361         else if (res == CMD_SUCCESS)
362                 Utils->RouteCommand(route_back_again, cmdbase, params, who);
363 }
364
365 void TreeSocket::OnTimeout()
366 {
367         ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
368 }
369
370 void TreeSocket::Close()
371 {
372         if (fd != -1)
373                 ServerInstance->GlobalCulls.AddItem(this);
374         this->BufferedSocket::Close();
375         SetError("Remote host closed connection");
376
377         // Connection closed.
378         // If the connection is fully up (state CONNECTED)
379         // then propogate a netsplit to all peers.
380         if (MyRoot)
381                 Squit(MyRoot,getError());
382
383         if (!ConnectionFailureShown)
384         {
385                 ConnectionFailureShown = true;
386                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
387
388                 time_t server_uptime = ServerInstance->Time() - this->age;
389                 if (server_uptime)
390                 {
391                         std::string timestr = ModuleSpanningTree::TimeToStr(server_uptime);
392                         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str());
393                 }
394         }
395 }