1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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;
176 Link* lnk = Utils->FindLink(InboundServerName);
178 Utils->timeoutlist.erase(this);
180 Node = new TreeServer(this->Utils, this->ServerInstance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
182 if (Node->DuplicateID())
184 this->SendError("Server ID "+InboundSID+" already exists on the network!");
185 this->ServerInstance->SNO->WriteToSnoMask('l',"Server \2"+InboundServerName+"\2 being introduced from \2" + prefix + "\2 denied, server ID already exists on the network. Closing link.");
189 Utils->TreeRoot->AddChild(Node);
191 params.push_back(InboundServerName);
192 params.push_back("*");
193 params.push_back("1");
194 params.push_back(InboundSID);
195 params.push_back(":"+InboundDescription);
196 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",params,InboundServerName);
197 Node->bursting = true;
200 else if (command == "ERROR")
202 return this->Error(params);
204 else if (command == "CAPAB")
206 return this->Capab(params);
213 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
214 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
215 * + our netburst, which will put them into CONNECTED state. -- w
217 if (command == "SERVER")
219 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
220 return this->Outbound_Reply_Server(params);
222 else if (command == "ERROR")
224 return this->Error(params);
226 else if (command == "CAPAB")
228 return this->Capab(params);
234 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
235 * Anything from here on should be accepted a little more reasonably.
240 * Check for fake direction here, and drop any instances that are found.
241 * What is fake direction? Imagine the following server setup:
242 * 0AA <-> 0AB <-> 0AC
243 * Fake direction would be 0AC sending a message to 0AB claiming to be from
244 * 0AA, or something similar. Basically, a message taking a path that *cannot*
247 * When would this be seen?
248 * Well, hopefully never. It could be caused by race conditions, bugs, or
249 * "miscreant" servers, though, so let's check anyway. -- w
251 std::string direction = prefix;
253 User *t = this->ServerInstance->FindUUID(prefix);
256 direction = t->server;
259 TreeServer* route_back_again = Utils->BestRouteTo(direction);
260 if ((!route_back_again) || (route_back_again->GetSocket() != this))
262 if (route_back_again)
263 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
267 * When there is activity on the socket, reset the ping counter so
268 * that we're not wasting bandwidth pinging an active server.
270 route_back_again->SetNextPingTime(ServerInstance->Time() + Utils->PingFreq);
271 route_back_again->SetPingFlag();
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);
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 std::vector<std::string> p(params.begin(), params.end());
350 return Utils->Creator->HandleMap(p, user);
353 else if (command == "SERVER")
355 return this->RemoteServer(prefix,params);
357 else if (command == "ERROR")
359 return this->Error(params);
361 else if (command == "OPERTYPE")
363 return this->OperType(prefix,params);
365 else if (command == "FMODE")
367 return this->ForceMode(prefix,params);
369 else if (command == "FTOPIC")
371 return this->ForceTopic(prefix,params);
373 else if (command == "METADATA")
375 return this->MetaData(prefix,params);
377 else if (command == "PING")
379 return this->LocalPing(prefix,params);
381 else if (command == "PONG")
383 TreeServer *s = Utils->FindServer(prefix);
384 if (s && s->bursting)
386 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
389 return this->LocalPong(prefix,params);
391 else if (command == "VERSION")
393 return this->ServerVersion(prefix,params);
395 else if (command == "FHOST")
397 return this->ChangeHost(prefix,params);
399 else if (command == "FNAME")
401 return this->ChangeName(prefix,params);
403 else if (command == "ADDLINE")
405 return this->AddLine(prefix,params);
407 else if (command == "DELLINE")
409 return this->DelLine(prefix,params);
411 else if (command == "SVSNICK")
413 return this->ForceNick(prefix,params);
415 else if (command == "OPERQUIT")
417 return this->OperQuit(prefix,params);
419 else if (command == "IDLE")
421 return this->Whois(prefix,params);
423 else if (command == "PUSH")
425 return this->Push(prefix,params);
427 else if (command == "TIME")
429 return this->Time(prefix,params);
431 else if ((command == "KICK") && (Utils->IsServer(prefix)))
433 if (params.size() == 3)
435 TreeServer* pf = Utils->FindServer(prefix);
436 User* user = this->ServerInstance->FindNick(params[1]);
437 Channel* chan = this->ServerInstance->FindChan(params[0]);
438 if (pf && user && chan)
440 if (!chan->ServerKickUser(user, params[2].c_str(), false, pf->GetName().c_str()))
441 /* Yikes, the channels gone! */
446 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
448 else if (command == "SVSJOIN")
450 return this->ServiceJoin(prefix,params);
452 else if (command == "SVSPART")
454 return this->ServicePart(prefix,params);
456 else if (command == "SQUIT")
458 if (params.size() == 2)
460 this->Squit(Utils->FindServer(params[0]),params[1]);
464 else if (command == "MODENOTICE")
466 if (params.size() >= 2)
469 ServerInstance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
471 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
473 else if (command == "SNONOTICE")
475 if (params.size() >= 2)
477 ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
478 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
482 else if (command == "BURST")
484 // Set prefix server as bursting
487 this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
491 ServerSource->bursting = true;
492 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
494 else if (command == "ENDBURST")
498 this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
502 ServerSource->FinishBurst();
503 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
505 else if (command == "ENCAP")
507 return this->Encap(prefix, params);
509 else if (command == "MODE" && !this->ServerInstance->FindUUID(prefix)) // XXX we should check for no such serv?
511 // Server-prefix MODE.
512 std::vector<std::string> modelist(params.begin(), params.end());
514 /* We don't support this for channel mode changes any more! */
515 if (params.size() >= 1)
517 if (ServerInstance->FindChan(params[0]))
519 this->SendError("Protocol violation by '"+(ServerSource ? ServerSource->GetName().c_str() : prefix)+"'! MODE for channel mode changes is not supported by the InspIRCd 1.2 protocol. You must use FMODE to preserve channel timestamps.");
524 // Insert into the parser
525 this->ServerInstance->SendMode(modelist, this->ServerInstance->FakeClient);
527 // Pass out to the network
528 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
533 * Not a special s2s command. Emulate the user doing it.
534 * This saves us having a huge ugly command parser again.
536 User *who = this->ServerInstance->FindUUID(prefix);
540 // this looks ugly because command is an irc::string
541 this->SendError("Command (" + std::string(command.c_str()) + ") from unknown prefix (" + prefix + ")! Dropping link.");
545 if (command == "NICK")
547 if (params.size() != 2)
549 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
552 /* Update timestamp on user when they change nicks */
553 who->age = atoi(params[1].c_str());
556 * On nick messages, check that the nick doesnt already exist here.
557 * If it does, perform collision logic.
559 User* x = this->ServerInstance->FindNickOnly(params[0]);
560 if ((x) && (x != who))
563 /* x is local, who is remote */
564 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
568 * Remote client lost, or both lost, parsing this nickchange would be
569 * pointless, as the incoming client's server will soon recieve SVSNICK to
570 * change its nick to its UID. :) -- w00t
578 std::vector<std::string> strparams(params.begin(), params.end());
580 switch (this->ServerInstance->CallCommandHandler(command.c_str(), strparams, who))
584 * XXX: command is irc::string, hence ugliness
586 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
591 * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
596 /* CMD_SUCCESS falls through here */
600 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
604 break; // end of state CONNECTED (phew).
609 std::string TreeSocket::GetName()
611 std::string sourceserv = this->myhost;
612 if (!this->InboundServerName.empty())
614 sourceserv = this->InboundServerName;
619 void TreeSocket::OnTimeout()
621 if (this->LinkState == CONNECTING)
623 Utils->Creator->RemoteMessage(NULL, "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
624 Link* MyLink = Utils->FindLink(myhost);
626 Utils->DoFailOver(MyLink);
630 void TreeSocket::OnClose()
632 // Test fix for big fuckup
633 if (this->LinkState != CONNECTED)
636 // Connection closed.
637 // If the connection is fully up (state CONNECTED)
638 // then propogate a netsplit to all peers.
639 std::string quitserver = this->myhost;
640 if (!this->InboundServerName.empty())
642 quitserver = this->InboundServerName;
644 TreeServer* s = Utils->FindServer(quitserver);
647 Squit(s,"Remote host closed the connection");
650 if (!quitserver.empty())
652 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' failed.",quitserver.c_str());
653 time_t server_uptime = ServerInstance->Time() - this->age;
655 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());