1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
19 #include "../transport.h"
20 #include "socketengine.h"
24 #include "treeserver.h"
26 #include "treesocket.h"
27 #include "resolvers.h"
28 #include "handshaketimer.h"
30 /* $ModDep: m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h m_spanningtree/handshaketimer.h */
32 /* Handle ERROR command */
33 bool TreeSocket::Error(parameterlist ¶ms)
35 if (params.size() < 1)
37 this->ServerInstance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
38 /* we will return false to cause the socket to close. */
42 void TreeSocket::Split(const std::string &line, parameterlist &n)
45 irc::tokenstream tokens(line);
47 while (tokens.GetToken(param))
54 bool TreeSocket::ProcessLine(std::string &line)
60 line = line.substr(0, line.find_first_of("\r\n"));
65 ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
67 this->Split(line.c_str(),params);
72 if ((params[0][0] == ':') && (params.size() > 1))
74 prefix = params[0].substr(1);
78 this->SendError("BUG (?) Empty prefix recieved: " + line);
81 command = params[1].c_str();
82 params.erase(params.begin(), params.begin() + 2);
86 command = params[0].c_str();
87 params.erase(params.begin());
90 switch (this->LinkState)
97 * Waiting for SERVER command from remote server. Server initiating
98 * the connection sends the first SERVER command, listening server
99 * replies with theirs if its happy, then if the initiator is happy,
100 * it starts to send its net sync, which starts the merge, otherwise
103 if (command == "PASS")
106 * Ignore this silently. Some services packages insist on sending PASS, even
107 * when it is not required (i.e. by us). We have to ignore this here, otherwise
108 * as it's an unknown command (effectively), it will cause the connection to be
109 * closed, which probably isn't what people want. -- w00t
112 else if (command == "SERVER")
114 return this->Inbound_Server(params);
116 else if (command == "ERROR")
118 return this->Error(params);
120 else if (command == "USER")
122 this->SendError("Client connections to this port are prohibited.");
125 else if (command == "CAPAB")
127 return this->Capab(params);
132 irc::string error = "Invalid command in negotiation phase: " + command;
133 this->SendError(assign(error));
140 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
141 * The other option at this stage of things, of course, is for them to close our connection thanks
142 * to invalid credentials.. -- w
144 if (command == "SERVER")
147 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
148 * Both of these aren't allowable, so block them here. -- w
150 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
153 else if (command == "BURST")
157 time_t them = atoi(params[0].c_str());
158 time_t delta = them - ServerInstance->Time();
159 if ((delta < -600) || (delta > 600))
161 ServerInstance->SNO->WriteToSnoMask('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));
162 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
165 else if ((delta < -30) || (delta > 30))
167 ServerInstance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
170 this->LinkState = CONNECTED;
172 Utils->timeoutlist.erase(this);
174 Link* lnk = Utils->FindLink(InboundServerName);
176 Node = new TreeServer(this->Utils, this->ServerInstance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
178 Utils->TreeRoot->AddChild(Node);
179 parameterlist sparams;
180 sparams.push_back(InboundServerName);
181 sparams.push_back("*");
182 sparams.push_back("1");
183 sparams.push_back(InboundSID);
184 sparams.push_back(":"+InboundDescription);
185 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",sparams,InboundServerName);
186 Utils->DoOneToAllButSenderRaw(line, InboundServerName, prefix, command, params);
187 Node->bursting = true;
190 else if (command == "ERROR")
192 return this->Error(params);
194 else if (command == "CAPAB")
196 return this->Capab(params);
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
207 if (command == "SERVER")
209 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
210 return this->Outbound_Reply_Server(params);
212 else if (command == "ERROR")
214 return this->Error(params);
216 else if (command == "CAPAB")
218 return this->Capab(params);
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.
230 * Check for fake direction here, and drop any instances that are found.
231 * What is fake direction? Imagine the following server setup:
232 * 0AA <-> 0AB <-> 0AC
233 * Fake direction would be 0AC sending a message to 0AB claiming to be from
234 * 0AA, or something similar. Basically, a message taking a path that *cannot*
237 * When would this be seen?
238 * Well, hopefully never. It could be caused by race conditions, bugs, or
239 * "miscreant" servers, though, so let's check anyway. -- w
241 * We also check here for totally invalid prefixes (prefixes that are neither
242 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
243 * to the higher level functions. -- B
245 std::string direction = prefix;
247 User *t = this->ServerInstance->FindUUID(prefix);
251 direction = t->server;
253 else if (!this->Utils->FindServer(direction))
256 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Protocol violation: Invalid prefix '%s' from connection '%s'", direction.c_str(), this->GetName().c_str());
260 TreeServer* route_back_again = Utils->BestRouteTo(direction);
261 if ((!route_back_again) || (route_back_again->GetSocket() != this))
263 if (route_back_again)
264 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
271 * Empty prefix from a server to server link:
272 * This is somewhat bad/naughty, so let's set the prefix
273 * to be the link that we got it from, so we don't break anything. -- w
275 TreeServer* n = Utils->FindServer(GetName());
283 * First up, check for any malformed commands (e.g. MODE without a timestamp)
284 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
286 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
290 * Now, check for (and parse) commands as appropriate. -- w
293 /* Find the server that this command originated from, used in the handlers below */
294 TreeServer *ServerSource = Utils->FindServer(prefix);
297 Utils->ServerUser->SetFakeServer(ServerSource->GetName());
298 Utils->ServerUser->uuid = ServerSource->GetID();
301 /* Find the link we just got this from so we don't bounce it back incorrectly */
302 std::string sourceserv = this->myhost;
303 if (!this->InboundServerName.empty())
305 sourceserv = this->InboundServerName;
309 * XXX one of these days, this needs to be moved into class Commands.
311 if (command == "UID")
313 return this->ParseUID(prefix, params);
315 else if (command == "FJOIN")
317 return this->ForceJoin(prefix,params);
319 else if ((command == "NOTICE" || command == "PRIVMSG") && (Utils->IsServer(prefix)))
321 return this->ServerMessage(assign(command), prefix, params, sourceserv);
323 else if (command == "STATS")
325 return this->Stats(prefix, params);
327 else if (command == "MOTD")
329 return this->Motd(prefix, params);
331 else if (command == "KILL" && ServerSource)
333 // Kill from a server
334 return this->RemoteKill(prefix,params);
336 else if (command == "MODULES")
338 return this->Modules(prefix, params);
340 else if (command == "ADMIN")
342 return this->Admin(prefix, params);
344 else if (command == "MAP")
346 User* user = ServerInstance->FindNick(prefix);
349 return Utils->Creator->HandleMap(params, user);
352 else if (command == "SERVER")
354 return this->RemoteServer(prefix,params);
356 else if (command == "ERROR")
358 return this->Error(params);
360 else if (command == "OPERTYPE")
362 return this->OperType(prefix,params);
364 else if (command == "FMODE")
366 return this->ForceMode(prefix,params);
368 else if (command == "FTOPIC")
370 return this->ForceTopic(prefix,params);
372 else if (command == "METADATA")
374 return this->MetaData(prefix,params);
376 else if (command == "PING")
378 return this->LocalPing(prefix,params);
380 else if (command == "PONG")
382 TreeServer *s = Utils->FindServer(prefix);
383 if (s && s->bursting)
385 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
388 return this->LocalPong(prefix,params);
390 else if (command == "VERSION")
392 return this->ServerVersion(prefix,params);
394 else if (command == "FHOST")
396 return this->ChangeHost(prefix,params);
398 else if (command == "FNAME")
400 return this->ChangeName(prefix,params);
402 else if (command == "FIDENT")
404 return this->ChangeIdent(prefix,params);
406 else if (command == "ADDLINE")
408 return this->AddLine(prefix,params);
410 else if (command == "DELLINE")
412 return this->DelLine(prefix,params);
414 else if (command == "SVSNICK")
416 return this->ForceNick(prefix,params);
418 else if (command == "OPERQUIT")
420 return this->OperQuit(prefix,params);
422 else if (command == "IDLE")
424 return this->Whois(prefix,params);
426 else if (command == "PUSH")
428 return this->Push(prefix,params);
430 else if (command == "TIME")
432 return this->Time(prefix,params);
434 else if (command == "SVSJOIN")
436 return this->ServiceJoin(prefix,params);
438 else if (command == "SVSPART")
440 return this->ServicePart(prefix,params);
442 else if (command == "SQUIT")
444 if (params.size() == 2)
446 this->Squit(Utils->FindServer(params[0]),params[1]);
450 else if (command == "MODENOTICE")
452 if (params.size() >= 2)
455 ServerInstance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
457 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
459 else if (command == "SNONOTICE")
461 if (params.size() >= 2)
463 std::string oldprefix;
467 User *u = ServerInstance->FindNick(prefix);
473 ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
475 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
479 else if (command == "BURST")
481 // Set prefix server as bursting
484 this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
488 ServerSource->bursting = true;
489 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
491 else if (command == "ENDBURST")
495 this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
499 ServerSource->FinishBurst();
500 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
502 else if (command == "ENCAP")
504 return this->Encap(prefix, params);
509 * Not a special s2s command. Emulate the user doing it.
510 * This saves us having a huge ugly command parser again.
512 User* who = this->ServerInstance->FindUUID(prefix);
516 who = Utils->ServerUser;
520 /* this looks ugly because command is an irc::string
521 * It is important that we dont close the link here, unknown prefix can occur
522 * due to various race conditions such as the KILL message for a user somehow
523 * crossing the users QUIT further upstream from the server. Thanks jilles!
525 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command " + std::string(command.c_str()) + " from unknown prefix " + prefix + "! Dropping entire command.");
529 if (command == "NICK")
531 if (params.size() != 2)
533 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
536 /* Update timestamp on user when they change nicks */
537 who->age = atoi(params[1].c_str());
540 * On nick messages, check that the nick doesnt already exist here.
541 * If it does, perform collision logic.
543 User* x = this->ServerInstance->FindNickOnly(params[0]);
544 if ((x) && (x != who))
547 /* x is local, who is remote */
548 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
552 * Remote client lost, or both lost, parsing or passing on this
553 * nickchange would be pointless, as the incoming client's server will
554 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
561 switch (this->ServerInstance->CallCommandHandler(command.c_str(), params, who))
565 * XXX: command is irc::string, hence ugliness
567 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
572 * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
577 /* CMD_SUCCESS falls through here */
581 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
585 break; // end of state CONNECTED (phew).
590 std::string TreeSocket::GetName()
592 std::string sourceserv = this->myhost;
593 if (!this->InboundServerName.empty())
595 sourceserv = this->InboundServerName;
600 void TreeSocket::OnTimeout()
602 if (this->LinkState == CONNECTING)
604 this->ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
605 Link* MyLink = Utils->FindLink(myhost);
607 Utils->DoFailOver(MyLink);
611 void TreeSocket::OnClose()
613 // Test fix for big fuckup
614 if (this->LinkState != CONNECTED)
617 // Connection closed.
618 // If the connection is fully up (state CONNECTED)
619 // then propogate a netsplit to all peers.
620 std::string quitserver = this->myhost;
621 if (!this->InboundServerName.empty())
623 quitserver = this->InboundServerName;
625 TreeServer* s = Utils->FindServer(quitserver);
628 Squit(s,"Remote host closed the connection");
631 if (!quitserver.empty())
633 this->ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
635 time_t server_uptime = ServerInstance->Time() - this->age;
637 this->ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());