2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
28 #include "socketengine.h"
32 #include "treeserver.h"
34 #include "treesocket.h"
35 #include "resolvers.h"
37 /* Handle ERROR command */
38 void TreeSocket::Error(parameterlist ¶ms)
40 std::string msg = params.size() ? params[0] : "";
41 SetError("received ERROR " + msg);
44 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
46 irc::tokenstream tokens(line);
48 if (!tokens.GetToken(prefix))
53 prefix = prefix.substr(1);
57 this->SendError("BUG (?) Empty prefix received: " + line);
60 if (!tokens.GetToken(command))
62 this->SendError("BUG (?) Empty command received: " + line);
72 this->SendError("BUG (?) Empty command received: " + line);
75 while (tokens.GetToken(param))
77 params.push_back(param);
81 void TreeSocket::ProcessLine(std::string &line)
87 ServerInstance->Logs->Log("m_spanningtree", LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
89 Split(line, prefix, command, params);
94 switch (this->LinkState)
99 * Waiting for SERVER command from remote server. Server initiating
100 * the connection sends the first SERVER command, listening server
101 * replies with theirs if its happy, then if the initiator is happy,
102 * it starts to send its net sync, which starts the merge, otherwise
105 if (command == "PASS")
108 * Ignore this silently. Some services packages insist on sending PASS, even
109 * when it is not required (i.e. by us). We have to ignore this here, otherwise
110 * as it's an unknown command (effectively), it will cause the connection to be
111 * closed, which probably isn't what people want. -- w00t
114 else if (command == "SERVER")
116 this->Inbound_Server(params);
118 else if (command == "ERROR")
122 else if (command == "USER")
124 this->SendError("Client connections to this port are prohibited.");
126 else if (command == "CAPAB")
132 this->SendError("Invalid command in negotiation phase: " + command);
138 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
139 * The other option at this stage of things, of course, is for them to close our connection thanks
140 * to invalid credentials.. -- w
142 if (command == "SERVER")
145 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
146 * Both of these aren't allowable, so block them here. -- w
148 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
150 else if (command == "BURST")
154 time_t them = atoi(params[0].c_str());
155 time_t delta = them - ServerInstance->Time();
156 if ((delta < -600) || (delta > 600))
158 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));
159 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
162 else if ((delta < -30) || (delta > 30))
164 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
167 this->LinkState = CONNECTED;
168 Utils->timeoutlist.erase(this);
170 MyRoot->bursting = true;
171 this->DoBurst(MyRoot);
173 parameterlist sparams;
174 sparams.push_back(MyRoot->GetName());
175 sparams.push_back("*");
176 sparams.push_back("0");
177 sparams.push_back(MyRoot->GetID());
178 sparams.push_back(":" + MyRoot->GetDesc());
179 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(), "SERVER", sparams, MyRoot->GetName());
180 Utils->DoOneToAllButSender(MyRoot->GetID(), "BURST", params, MyRoot->GetName());
182 else if (command == "ERROR")
186 else if (command == "CAPAB")
195 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
196 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
197 * + our netburst, which will put them into CONNECTED state. -- w
199 if (command == "SERVER")
201 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
202 this->Outbound_Reply_Server(params);
204 else if (command == "ERROR")
208 else if (command == "CAPAB")
216 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
217 * Anything from here on should be accepted a little more reasonably.
219 this->ProcessConnectedLine(prefix, command, params);
226 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
228 User* who = ServerInstance->FindUUID(prefix);
229 std::string direction;
233 TreeServer* ServerSource = Utils->FindServer(prefix);
235 ServerSource = MyRoot;
239 who = ServerSource->ServerUser;
243 /* It is important that we don't close the link here, unknown prefix can occur
244 * due to various race conditions such as the KILL message for a user somehow
245 * crossing the users QUIT further upstream from the server. Thanks jilles!
248 if ((prefix.length() == UUID_LENGTH-1) && (isdigit(prefix[0])) &&
249 ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE")))
251 /* Special case, we cannot drop these commands as they've been committed already on a
252 * part of the network by the time we receive them, so in this scenario pretend the
253 * command came from a server to avoid desync.
256 who = ServerInstance->FindUUID(prefix.substr(0, 3));
258 who = this->MyRoot->ServerUser;
262 ServerInstance->Logs->Log("m_spanningtree", LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
263 command.c_str(), prefix.c_str());
269 // Make sure prefix is still good
270 direction = who->server;
274 * Check for fake direction here, and drop any instances that are found.
275 * What is fake direction? Imagine the following server setup:
276 * 0AA <-> 0AB <-> 0AC
277 * Fake direction would be 0AC sending a message to 0AB claiming to be from
278 * 0AA, or something similar. Basically, a message taking a path that *cannot*
281 * When would this be seen?
282 * Well, hopefully never. It could be caused by race conditions, bugs, or
283 * "miscreant" servers, though, so let's check anyway. -- w
285 * We also check here for totally invalid prefixes (prefixes that are neither
286 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
287 * to the higher level functions. -- B
289 TreeServer* route_back_again = Utils->BestRouteTo(direction);
290 if ((!route_back_again) || (route_back_again->GetSocket() != this))
292 if (route_back_again)
293 ServerInstance->Logs->Log("m_spanningtree",LOG_DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
294 prefix.c_str(),linkID.c_str());
299 * First up, check for any malformed commands (e.g. MODE without a timestamp)
300 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
302 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
305 // TODO move all this into Commands
306 if (command == "MAP")
308 Utils->Creator->HandleMap(params, who);
310 else if (command == "SERVER")
312 this->RemoteServer(prefix,params);
314 else if (command == "ERROR")
318 else if (command == "AWAY")
320 this->Away(prefix,params);
322 else if (command == "PING")
324 this->LocalPing(prefix,params);
326 else if (command == "PONG")
328 TreeServer *s = Utils->FindServer(prefix);
329 if (s && s->bursting)
331 ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
334 this->LocalPong(prefix,params);
336 else if (command == "VERSION")
338 this->ServerVersion(prefix,params);
340 else if (command == "ADDLINE")
342 this->AddLine(prefix,params);
344 else if (command == "DELLINE")
346 this->DelLine(prefix,params);
348 else if (command == "SAVE")
350 this->ForceNick(prefix,params);
352 else if (command == "OPERQUIT")
354 this->OperQuit(prefix,params);
356 else if (command == "IDLE")
358 this->Whois(prefix,params);
360 else if (command == "PUSH")
362 this->Push(prefix,params);
364 else if (command == "SQUIT")
366 if (params.size() == 2)
368 this->Squit(Utils->FindServer(params[0]),params[1]);
371 else if (command == "SNONOTICE")
373 if (params.size() >= 2)
375 ServerInstance->SNO->WriteToSnoMask(params[0][0], "From " + who->nick + ": "+ params[1]);
376 params[1] = ":" + params[1];
377 Utils->DoOneToAllButSender(prefix, command, params, prefix);
380 else if (command == "BURST")
382 // Set prefix server as bursting
383 TreeServer* ServerSource = Utils->FindServer(prefix);
386 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
390 ServerSource->bursting = true;
391 Utils->DoOneToAllButSender(prefix, command, params, prefix);
393 else if (command == "ENDBURST")
395 TreeServer* ServerSource = Utils->FindServer(prefix);
398 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
402 ServerSource->FinishBurst();
403 Utils->DoOneToAllButSender(prefix, command, params, prefix);
405 else if (command == "ENCAP")
407 this->Encap(who, params);
409 else if (command == "NICK")
411 if (params.size() != 2)
413 SendError("Protocol violation: Wrong number of parameters for NICK message");
419 SendError("Protocol violation: Server changing nick");
423 if ((isdigit(params[0][0])) && (params[0] != who->uuid))
425 SendError("Protocol violation: User changing nick to an invalid UID - " + params[0]);
429 /* Update timestamp on user when they change nicks */
430 who->age = atoi(params[1].c_str());
433 * On nick messages, check that the nick doesnt already exist here.
434 * If it does, perform collision logic.
436 User* x = ServerInstance->FindNickOnly(params[0]);
437 if ((x) && (x != who))
440 /* x is local, who is remote */
441 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
445 * Remote client lost, or both lost, parsing or passing on this
446 * nickchange would be pointless, as the incoming client's server will
447 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
452 who->ForceNickChange(params[0].c_str());
453 Utils->RouteCommand(route_back_again, command, params, who);
457 Command* cmd = ServerInstance->Parser->GetHandler(command);
461 irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
462 ServerInstance->Logs->Log("m_spanningtree", LOG_SPARSE, "Unrecognised S2S command :%s %s %s",
463 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
464 SendError("Unrecognised command '" + command + "' -- possibly loaded mismatched modules");
468 if (params.size() < cmd->min_params)
470 irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
471 ServerInstance->Logs->Log("m_spanningtree", LOG_SPARSE, "Insufficient parameters for S2S command :%s %s %s",
472 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
473 SendError("Insufficient parameters for command '" + command + "'");
477 if ((!params.empty()) && (params.back().empty()) && (!cmd->allow_empty_last_param))
479 // 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
480 if (params.size()-1 < cmd->min_params)
485 CmdResult res = cmd->Handle(params, who);
487 if (res == CMD_INVALID)
489 irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
490 ServerInstance->Logs->Log("m_spanningtree", LOG_SPARSE, "Error handling S2S command :%s %s %s",
491 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
492 SendError("Error handling '" + command + "' -- possibly loaded mismatched modules");
494 else if (res == CMD_SUCCESS)
495 Utils->RouteCommand(route_back_again, command, params, who);
499 void TreeSocket::OnTimeout()
501 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
504 void TreeSocket::Close()
507 ServerInstance->GlobalCulls.AddItem(this);
508 this->BufferedSocket::Close();
509 SetError("Remote host closed connection");
511 // Connection closed.
512 // If the connection is fully up (state CONNECTED)
513 // then propogate a netsplit to all peers.
515 Squit(MyRoot,getError());
517 if (!ConnectionFailureShown)
519 ConnectionFailureShown = true;
520 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
522 time_t server_uptime = ServerInstance->Time() - this->age;
525 std::string timestr = Utils->Creator->TimeToStr(server_uptime);
526 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str());