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"
22 #include "m_spanningtree/main.h"
23 #include "m_spanningtree/utils.h"
24 #include "m_spanningtree/treeserver.h"
25 #include "m_spanningtree/link.h"
26 #include "m_spanningtree/treesocket.h"
27 #include "m_spanningtree/resolvers.h"
28 #include "m_spanningtree/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 void TreeSocket::WriteLine(std::string line)
34 ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] O %s", this->GetFd(), line.c_str());
40 /* Handle ERROR command */
41 bool TreeSocket::Error(std::deque<std::string> ¶ms)
43 if (params.size() < 1)
45 this->ServerInstance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
46 /* we will return false to cause the socket to close. */
50 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
53 irc::tokenstream tokens(line);
55 while (tokens.GetToken(param))
62 bool TreeSocket::ProcessLine(std::string &line)
64 std::deque<std::string> params;
68 line = line.substr(0, line.find_first_of("\r\n"));
73 ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
75 this->Split(line.c_str(),params);
80 if ((params[0][0] == ':') && (params.size() > 1))
82 prefix = params[0].substr(1);
87 this->SendError("BUG (?) Empty prefix recieved.");
92 command = params[0].c_str();
95 switch (this->LinkState)
102 * Waiting for SERVER command from remote server. Server initiating
103 * the connection sends the first SERVER command, listening server
104 * replies with theirs if its happy, then if the initiator is happy,
105 * it starts to send its net sync, which starts the merge, otherwise
108 if (command == "PASS")
111 * Ignore this silently. Some services packages insist on sending PASS, even
112 * when it is not required (i.e. by us). We have to ignore this here, otherwise
113 * as it's an unknown command (effectively), it will cause the connection to be
114 * closed, which probably isn't what people want. -- w00t
117 else if (command == "SERVER")
119 return this->Inbound_Server(params);
121 else if (command == "ERROR")
123 return this->Error(params);
125 else if (command == "USER")
127 this->SendError("Client connections to this port are prohibited.");
130 else if (command == "CAPAB")
132 return this->Capab(params);
137 irc::string error = "Invalid command in negotiation phase: " + command;
138 this->SendError(assign(error));
145 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
146 * The other option at this stage of things, of course, is for them to close our connection thanks
147 * to invalid credentials.. -- w
149 if (command == "SERVER")
152 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
153 * Both of these aren't allowable, so block them here. -- w
155 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
158 else if (command == "BURST")
162 time_t them = atoi(params[0].c_str());
163 time_t delta = them - ServerInstance->Time();
164 if ((delta < -600) || (delta > 600))
166 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));
167 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
170 else if ((delta < -30) || (delta > 30))
172 ServerInstance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
175 this->LinkState = CONNECTED;
177 Utils->timeoutlist.erase(this);
179 Link* lnk = Utils->FindLink(InboundServerName);
181 Node = new TreeServer(this->Utils, this->ServerInstance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
183 Utils->TreeRoot->AddChild(Node);
184 parameterlist sparams;
185 sparams.push_back(InboundServerName);
186 sparams.push_back("*");
187 sparams.push_back("1");
188 sparams.push_back(InboundSID);
189 sparams.push_back(":"+InboundDescription);
190 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",sparams,InboundServerName);
191 Utils->DoOneToAllButSenderRaw(line, InboundServerName, prefix, command, params);
192 Node->bursting = true;
195 else if (command == "ERROR")
197 return this->Error(params);
199 else if (command == "CAPAB")
201 return this->Capab(params);
208 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
209 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
210 * + our netburst, which will put them into CONNECTED state. -- w
212 if (command == "SERVER")
214 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
215 return this->Outbound_Reply_Server(params);
217 else if (command == "ERROR")
219 return this->Error(params);
221 else if (command == "CAPAB")
223 return this->Capab(params);
229 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
230 * Anything from here on should be accepted a little more reasonably.
235 * Check for fake direction here, and drop any instances that are found.
236 * What is fake direction? Imagine the following server setup:
237 * 0AA <-> 0AB <-> 0AC
238 * Fake direction would be 0AC sending a message to 0AB claiming to be from
239 * 0AA, or something similar. Basically, a message taking a path that *cannot*
242 * When would this be seen?
243 * Well, hopefully never. It could be caused by race conditions, bugs, or
244 * "miscreant" servers, though, so let's check anyway. -- w
246 * We also check here for totally invalid prefixes (prefixes that are neither
247 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
248 * to the higher level functions. -- B
250 std::string direction = prefix;
252 User *t = this->ServerInstance->FindUUID(prefix);
256 direction = t->server;
258 else if (!this->Utils->FindServer(direction))
261 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Protocol violation: Invalid prefix '%s' from connection '%s'", direction.c_str(), this->GetName().c_str());
265 TreeServer* route_back_again = Utils->BestRouteTo(direction);
266 if ((!route_back_again) || (route_back_again->GetSocket() != this))
268 if (route_back_again)
269 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
276 * Empty prefix from a server to server link:
277 * This is somewhat bad/naughty, so let's set the prefix
278 * to be the link that we got it from, so we don't break anything. -- w
280 TreeServer* n = Utils->FindServer(GetName());
288 * First up, check for any malformed commands (e.g. MODE without a timestamp)
289 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
291 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
295 * Now, check for (and parse) commands as appropriate. -- w
298 /* Find the server that this command originated from, used in the handlers below */
299 TreeServer *ServerSource = Utils->FindServer(prefix);
302 Utils->ServerUser->SetFakeServer(ServerSource->GetName());
303 Utils->ServerUser->uuid = ServerSource->GetID();
306 /* Find the link we just got this from so we don't bounce it back incorrectly */
307 std::string sourceserv = this->myhost;
308 if (!this->InboundServerName.empty())
310 sourceserv = this->InboundServerName;
314 * XXX one of these days, this needs to be moved into class Commands.
316 if (command == "UID")
318 return this->ParseUID(prefix, params);
320 else if (command == "FJOIN")
322 return this->ForceJoin(prefix,params);
324 else if ((command == "NOTICE" || command == "PRIVMSG") && (Utils->IsServer(prefix)))
326 return this->ServerMessage(assign(command), prefix, params, sourceserv);
328 else if (command == "STATS")
330 return this->Stats(prefix, params);
332 else if (command == "MOTD")
334 return this->Motd(prefix, params);
336 else if (command == "KILL" && ServerSource)
338 // Kill from a server
339 return this->RemoteKill(prefix,params);
341 else if (command == "MODULES")
343 return this->Modules(prefix, params);
345 else if (command == "ADMIN")
347 return this->Admin(prefix, params);
349 else if (command == "MAP")
351 User* user = ServerInstance->FindNick(prefix);
354 std::vector<std::string> p(params.begin(), params.end());
355 return Utils->Creator->HandleMap(p, user);
358 else if (command == "SERVER")
360 return this->RemoteServer(prefix,params);
362 else if (command == "ERROR")
364 return this->Error(params);
366 else if (command == "OPERTYPE")
368 return this->OperType(prefix,params);
370 else if (command == "FMODE")
372 return this->ForceMode(prefix,params);
374 else if (command == "FTOPIC")
376 return this->ForceTopic(prefix,params);
378 else if (command == "METADATA")
380 return this->MetaData(prefix,params);
382 else if (command == "PING")
384 return this->LocalPing(prefix,params);
386 else if (command == "PONG")
388 TreeServer *s = Utils->FindServer(prefix);
389 if (s && s->bursting)
391 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
394 return this->LocalPong(prefix,params);
396 else if (command == "VERSION")
398 return this->ServerVersion(prefix,params);
400 else if (command == "FHOST")
402 return this->ChangeHost(prefix,params);
404 else if (command == "FNAME")
406 return this->ChangeName(prefix,params);
408 else if (command == "ADDLINE")
410 return this->AddLine(prefix,params);
412 else if (command == "DELLINE")
414 return this->DelLine(prefix,params);
416 else if (command == "SVSNICK")
418 return this->ForceNick(prefix,params);
420 else if (command == "OPERQUIT")
422 return this->OperQuit(prefix,params);
424 else if (command == "IDLE")
426 return this->Whois(prefix,params);
428 else if (command == "PUSH")
430 return this->Push(prefix,params);
432 else if (command == "TIME")
434 return this->Time(prefix,params);
436 else if (command == "SVSJOIN")
438 return this->ServiceJoin(prefix,params);
440 else if (command == "SVSPART")
442 return this->ServicePart(prefix,params);
444 else if (command == "SQUIT")
446 if (params.size() == 2)
448 this->Squit(Utils->FindServer(params[0]),params[1]);
452 else if (command == "MODENOTICE")
454 if (params.size() >= 2)
457 ServerInstance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
459 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
461 else if (command == "SNONOTICE")
463 if (params.size() >= 2)
465 std::string oldprefix;
469 User *u = ServerInstance->FindNick(prefix);
475 ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
477 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
481 else if (command == "BURST")
483 // Set prefix server as bursting
486 this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
490 ServerSource->bursting = true;
491 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
493 else if (command == "ENDBURST")
497 this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
501 ServerSource->FinishBurst();
502 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
504 else if (command == "ENCAP")
506 return this->Encap(prefix, params);
511 * Not a special s2s command. Emulate the user doing it.
512 * This saves us having a huge ugly command parser again.
514 User* who = this->ServerInstance->FindUUID(prefix);
518 who = Utils->ServerUser;
522 /* this looks ugly because command is an irc::string
523 * It is important that we dont close the link here, unknown prefix can occur
524 * due to various race conditions such as the KILL message for a user somehow
525 * crossing the users QUIT further upstream from the server. Thanks jilles!
527 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command " + std::string(command.c_str()) + " from unknown prefix " + prefix + "! Dropping entire command.");
531 if (command == "NICK")
533 if (params.size() != 2)
535 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
538 /* Update timestamp on user when they change nicks */
539 who->age = atoi(params[1].c_str());
542 * On nick messages, check that the nick doesnt already exist here.
543 * If it does, perform collision logic.
545 User* x = this->ServerInstance->FindNickOnly(params[0]);
546 if ((x) && (x != who))
549 /* x is local, who is remote */
550 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
554 * Remote client lost, or both lost, parsing or passing on this
555 * nickchange would be pointless, as the incoming client's server will
556 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
564 std::vector<std::string> strparams(params.begin(), params.end());
566 switch (this->ServerInstance->CallCommandHandler(command.c_str(), strparams, who))
570 * XXX: command is irc::string, hence ugliness
572 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
577 * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
582 /* CMD_SUCCESS falls through here */
586 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
590 break; // end of state CONNECTED (phew).
595 std::string TreeSocket::GetName()
597 std::string sourceserv = this->myhost;
598 if (!this->InboundServerName.empty())
600 sourceserv = this->InboundServerName;
605 void TreeSocket::OnTimeout()
607 if (this->LinkState == CONNECTING)
609 this->ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
610 Link* MyLink = Utils->FindLink(myhost);
612 Utils->DoFailOver(MyLink);
616 void TreeSocket::OnClose()
618 // Test fix for big fuckup
619 if (this->LinkState != CONNECTED)
622 // Connection closed.
623 // If the connection is fully up (state CONNECTED)
624 // then propogate a netsplit to all peers.
625 std::string quitserver = this->myhost;
626 if (!this->InboundServerName.empty())
628 quitserver = this->InboundServerName;
630 TreeServer* s = Utils->FindServer(quitserver);
633 Squit(s,"Remote host closed the connection");
636 if (!quitserver.empty())
638 this->ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
640 time_t server_uptime = ServerInstance->Time() - this->age;
642 this->ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());