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 * ---------------------------------------------------
17 #include "../transport.h"
18 #include "socketengine.h"
22 #include "treeserver.h"
24 #include "treesocket.h"
25 #include "resolvers.h"
26 #include "handshaketimer.h"
28 /* $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 */
30 /* Handle ERROR command */
31 bool TreeSocket::Error(parameterlist ¶ms)
33 if (params.size() < 1)
35 ServerInstance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
36 /* we will return false to cause the socket to close. */
40 void TreeSocket::Split(const std::string &line, parameterlist &n)
43 irc::tokenstream tokens(line);
45 while (tokens.GetToken(param))
52 bool TreeSocket::ProcessLine(std::string &line)
58 line = line.substr(0, line.find_first_of("\r\n"));
63 ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
65 this->Split(line.c_str(),params);
70 if ((params[0][0] == ':') && (params.size() > 1))
72 prefix = params[0].substr(1);
76 this->SendError("BUG (?) Empty prefix recieved: " + line);
79 command = params[1].c_str();
80 params.erase(params.begin(), params.begin() + 2);
84 command = params[0].c_str();
85 params.erase(params.begin());
88 switch (this->LinkState)
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
101 if (command == "PASS")
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
110 else if (command == "SERVER")
112 return this->Inbound_Server(params);
114 else if (command == "ERROR")
116 return this->Error(params);
118 else if (command == "USER")
120 this->SendError("Client connections to this port are prohibited.");
123 else if (command == "CAPAB")
125 return this->Capab(params);
129 this->SendError(std::string("Invalid command in negotiation phase: ") + command.c_str());
136 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
137 * The other option at this stage of things, of course, is for them to close our connection thanks
138 * to invalid credentials.. -- w
140 if (command == "SERVER")
143 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
144 * Both of these aren't allowable, so block them here. -- w
146 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
149 else if (command == "BURST")
153 time_t them = atoi(params[0].c_str());
154 time_t delta = them - ServerInstance->Time();
155 if ((delta < -600) || (delta > 600))
157 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));
158 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
161 else if ((delta < -30) || (delta > 30))
163 ServerInstance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
166 this->LinkState = CONNECTED;
168 Utils->timeoutlist.erase(this);
170 Link* lnk = Utils->FindLink(InboundServerName);
172 Node = new TreeServer(this->Utils, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
174 Utils->TreeRoot->AddChild(Node);
175 parameterlist sparams;
176 sparams.push_back(InboundServerName);
177 sparams.push_back("*");
178 sparams.push_back("1");
179 sparams.push_back(InboundSID);
180 sparams.push_back(":"+InboundDescription);
181 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",sparams,InboundServerName);
182 Utils->DoOneToAllButSenderRaw(line, InboundServerName, prefix, command, params);
183 Node->bursting = true;
186 else if (command == "ERROR")
188 return this->Error(params);
190 else if (command == "CAPAB")
192 return this->Capab(params);
199 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
200 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
201 * + our netburst, which will put them into CONNECTED state. -- w
203 if (command == "SERVER")
205 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
206 return this->Outbound_Reply_Server(params);
208 else if (command == "ERROR")
210 return this->Error(params);
212 else if (command == "CAPAB")
214 return this->Capab(params);
220 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
221 * Anything from here on should be accepted a little more reasonably.
226 * Check for fake direction here, and drop any instances that are found.
227 * What is fake direction? Imagine the following server setup:
228 * 0AA <-> 0AB <-> 0AC
229 * Fake direction would be 0AC sending a message to 0AB claiming to be from
230 * 0AA, or something similar. Basically, a message taking a path that *cannot*
233 * When would this be seen?
234 * Well, hopefully never. It could be caused by race conditions, bugs, or
235 * "miscreant" servers, though, so let's check anyway. -- w
237 * We also check here for totally invalid prefixes (prefixes that are neither
238 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
239 * to the higher level functions. -- B
241 std::string direction = prefix;
243 User *t = ServerInstance->FindUUID(prefix);
247 direction = t->server;
249 else if (!this->Utils->FindServer(direction))
252 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Protocol violation: Invalid prefix '%s' from connection '%s'", direction.c_str(), this->GetName().c_str());
256 TreeServer* route_back_again = Utils->BestRouteTo(direction);
257 if ((!route_back_again) || (route_back_again->GetSocket() != this))
259 if (route_back_again)
260 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
267 * Empty prefix from a server to server link:
268 * This is somewhat bad/naughty, so let's set the prefix
269 * to be the link that we got it from, so we don't break anything. -- w
271 TreeServer* n = Utils->FindServer(GetName());
279 * First up, check for any malformed commands (e.g. MODE without a timestamp)
280 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
282 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
286 * Now, check for (and parse) commands as appropriate. -- w
289 /* Find the server that this command originated from, used in the handlers below */
290 TreeServer *ServerSource = Utils->FindServer(prefix);
293 Utils->ServerUser->SetFakeServer(ServerSource->GetName());
294 Utils->ServerUser->uuid = ServerSource->GetID();
297 /* Find the link we just got this from so we don't bounce it back incorrectly */
298 std::string sourceserv = this->myhost;
299 if (!this->InboundServerName.empty())
301 sourceserv = this->InboundServerName;
305 * XXX one of these days, this needs to be moved into class Commands.
307 if (command == "UID")
309 return this->ParseUID(prefix, params);
311 else if (command == "FJOIN")
313 return this->ForceJoin(prefix,params);
315 else if ((command == "NOTICE" || command == "PRIVMSG") && (Utils->IsServer(prefix)))
317 return ServerMessage(assign(command), prefix, params, sourceserv);
319 else if (command == "STATS")
321 return this->Stats(prefix, params);
323 else if (command == "MOTD")
325 return this->Motd(prefix, params);
327 else if (command == "KILL" && ServerSource)
329 // Kill from a server
330 return this->RemoteKill(prefix,params);
332 else if (command == "MODULES")
334 return this->Modules(prefix, params);
336 else if (command == "ADMIN")
338 return this->Admin(prefix, params);
340 else if (command == "MAP")
342 User* user = ServerInstance->FindNick(prefix);
345 return Utils->Creator->HandleMap(params, user);
348 else if (command == "SERVER")
350 return this->RemoteServer(prefix,params);
352 else if (command == "ERROR")
354 return this->Error(params);
356 else if (command == "OPERTYPE")
358 return this->OperType(prefix,params);
360 else if (command == "AWAY")
362 return this->Away(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->SVSNick(prefix,params);
418 else if (command == "SAVE")
420 return this->ForceNick(prefix,params);
422 else if (command == "OPERQUIT")
424 return this->OperQuit(prefix,params);
426 else if (command == "IDLE")
428 return this->Whois(prefix,params);
430 else if (command == "PUSH")
432 return this->Push(prefix,params);
434 else if (command == "TIME")
436 return this->Time(prefix,params);
438 else if (command == "SVSJOIN")
440 return this->ServiceJoin(prefix,params);
442 else if (command == "SVSPART")
444 return this->ServicePart(prefix,params);
446 else if (command == "SQUIT")
448 if (params.size() == 2)
450 this->Squit(Utils->FindServer(params[0]),params[1]);
454 else if (command == "MODENOTICE")
456 if (params.size() >= 2)
459 ServerInstance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
461 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
463 else if (command == "SNONOTICE")
465 if (params.size() >= 2)
467 std::string oldprefix;
471 User *u = ServerInstance->FindNick(prefix);
477 ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
479 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
483 else if (command == "BURST")
485 // Set prefix server as bursting
488 ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
492 ServerSource->bursting = true;
493 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
495 else if (command == "ENDBURST")
499 ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
503 ServerSource->FinishBurst();
504 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
506 else if (command == "ENCAP")
508 return this->Encap(prefix, params);
513 * Not a special s2s command. Emulate the user doing it.
514 * This saves us having a huge ugly command parser again.
516 User* who = ServerInstance->FindUUID(prefix);
520 who = Utils->ServerUser;
524 /* this looks ugly because command is an irc::string
525 * It is important that we dont close the link here, unknown prefix can occur
526 * due to various race conditions such as the KILL message for a user somehow
527 * crossing the users QUIT further upstream from the server. Thanks jilles!
529 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command " + std::string(command.c_str()) + " from unknown prefix " + prefix + "! Dropping entire command.");
533 if (command == "NICK")
535 if (params.size() != 2)
537 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
540 /* Update timestamp on user when they change nicks */
541 who->age = atoi(params[1].c_str());
544 * On nick messages, check that the nick doesnt already exist here.
545 * If it does, perform collision logic.
547 User* x = ServerInstance->FindNickOnly(params[0]);
548 if ((x) && (x != who))
551 /* x is local, who is remote */
552 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
556 * Remote client lost, or both lost, parsing or passing on this
557 * nickchange would be pointless, as the incoming client's server will
558 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
565 switch (ServerInstance->CallCommandHandler(command.c_str(), params, who))
569 * XXX: command is irc::string, hence ugliness
571 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
576 * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
581 /* CMD_SUCCESS falls through here */
585 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
589 break; // end of state CONNECTED (phew).
594 std::string TreeSocket::GetName()
596 std::string sourceserv = this->myhost;
597 if (!this->InboundServerName.empty())
599 sourceserv = this->InboundServerName;
604 void TreeSocket::OnTimeout()
606 if (this->LinkState == CONNECTING)
608 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
609 Utils->Creator->ConnectServer(myautoconnect);
613 void TreeSocket::Close()
615 this->BufferedSocket::Close();
617 // Test fix for big fuckup
618 if (this->LinkState != CONNECTED)
621 // Connection closed.
622 // If the connection is fully up (state CONNECTED)
623 // then propogate a netsplit to all peers.
624 std::string quitserver = this->myhost;
625 if (!this->InboundServerName.empty())
627 quitserver = this->InboundServerName;
629 TreeServer* s = Utils->FindServer(quitserver);
632 Squit(s,"Remote host closed the connection");
635 if (!quitserver.empty())
637 ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
639 time_t server_uptime = ServerInstance->Time() - this->age;
641 ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());