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"
20 #include "transport.h"
21 #include "socketengine.h"
23 #include "m_spanningtree/main.h"
24 #include "m_spanningtree/utils.h"
25 #include "m_spanningtree/treeserver.h"
26 #include "m_spanningtree/link.h"
27 #include "m_spanningtree/treesocket.h"
28 #include "m_spanningtree/resolvers.h"
29 #include "m_spanningtree/handshaketimer.h"
31 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
33 static std::map<std::string, std::string> warned; /* Server names that have had protocol violation warnings displayed for them */
35 int TreeSocket::WriteLine(std::string line)
37 Instance->Logs->Log("m_spanningtree",DEBUG, "S[%d] O %s", this->GetFd(), line.c_str());
39 return this->Write(line);
43 /* Handle ERROR command */
44 bool TreeSocket::Error(std::deque<std::string> ¶ms)
46 if (params.size() < 1)
48 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
49 /* we will return false to cause the socket to close. */
53 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
56 irc::tokenstream tokens(line);
58 while (tokens.GetToken(param))
65 bool TreeSocket::ProcessLine(std::string &line)
67 std::deque<std::string> params;
71 line = line.substr(0, line.find_first_of("\r\n"));
76 Instance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
78 this->Split(line.c_str(),params);
83 if ((params[0][0] == ':') && (params.size() > 1))
85 prefix = params[0].substr(1);
90 this->SendError("BUG (?) Empty prefix recieved.");
95 command = params[0].c_str();
98 switch (this->LinkState)
105 * Waiting for SERVER command from remote server. Server initiating
106 * the connection sends the first SERVER command, listening server
107 * replies with theirs if its happy, then if the initiator is happy,
108 * it starts to send its net sync, which starts the merge, otherwise
111 if (command == "PASS")
114 * Ignore this silently. Some services packages insist on sending PASS, even
115 * when it is not required (i.e. by us). We have to ignore this here, otherwise
116 * as it's an unknown command (effectively), it will cause the connection to be
117 * closed, which probably isn't what people want. -- w00t
120 else if (command == "SERVER")
122 return this->Inbound_Server(params);
124 else if (command == "ERROR")
126 return this->Error(params);
128 else if (command == "USER")
130 this->SendError("Client connections to this port are prohibited.");
133 else if (command == "CAPAB")
135 return this->Capab(params);
140 irc::string error = "Invalid command in negotiation phase: " + command;
141 this->SendError(assign(error));
148 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
149 * The other option at this stage of things, of course, is for them to close our connection thanks
150 * to invalid credentials.. -- w
152 if (command == "SERVER")
155 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
156 * Both of these aren't allowable, so block them here. -- w
158 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
161 else if (command == "BURST")
165 time_t them = atoi(params[0].c_str());
166 time_t delta = them - Instance->Time();
167 if ((delta < -600) || (delta > 600))
169 Instance->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(delta));
170 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
173 else if ((delta < -30) || (delta > 30))
175 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
178 this->LinkState = CONNECTED;
179 Link* lnk = Utils->FindLink(InboundServerName);
181 Node = new TreeServer(this->Utils, this->Instance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
183 if (Node->DuplicateID())
185 this->SendError("Server ID "+InboundSID+" already exists on the network!");
186 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+InboundServerName+"\2 being introduced from \2" + prefix + "\2 denied, server ID already exists on the network. Closing link.");
190 Utils->TreeRoot->AddChild(Node);
192 params.push_back(InboundServerName);
193 params.push_back("*");
194 params.push_back("1");
195 params.push_back(InboundSID);
196 params.push_back(":"+InboundDescription);
197 Utils->DoOneToAllButSender(Instance->Config->GetSID(),"SERVER",params,InboundServerName);
198 Node->bursting = true;
201 else if (command == "ERROR")
203 return this->Error(params);
205 else if (command == "CAPAB")
207 return this->Capab(params);
213 * This really shouldn't happen.
215 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
221 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
222 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
223 * + our netburst, which will put them into CONNECTED state. -- w
225 if (command == "SERVER")
227 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
228 return this->Outbound_Reply_Server(params);
230 else if (command == "ERROR")
232 return this->Error(params);
234 else if (command == "CAPAB")
236 return this->Capab(params);
242 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
243 * Anything from here on should be accepted a little more reasonably.
248 * Check for fake direction here, and drop any instances that are found.
249 * What is fake direction? Imagine the following server setup:
250 * 0AA <-> 0AB <-> 0AC
251 * Fake direction would be 0AC sending a message to 0AB claiming to be from
252 * 0AA, or something similar. Basically, a message taking a path that *cannot*
255 * When would this be seen?
256 * Well, hopefully never. It could be caused by race conditions, bugs, or
257 * "miscreant" servers, though, so let's check anyway. -- w
259 std::string direction = prefix;
261 User *t = this->Instance->FindUUID(prefix);
264 direction = t->server;
267 TreeServer* route_back_again = Utils->BestRouteTo(direction);
268 if ((!route_back_again) || (route_back_again->GetSocket() != this))
270 if (route_back_again)
271 Instance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
275 * When there is activity on the socket, reset the ping counter so
276 * that we're not wasting bandwidth pinging an active server.
278 route_back_again->SetNextPingTime(Instance->Time() + Utils->PingFreq);
279 route_back_again->SetPingFlag();
284 * Empty prefix from a server to server link:
285 * This is somewhat bad/naughty, so let's set the prefix
286 * to be the link that we got it from, so we don't break anything. -- w
288 TreeServer* n = Utils->FindServer(GetName());
296 * First up, check for any malformed commands (e.g. MODE without a timestamp)
297 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
299 if (command == "MODE")
301 if (params.size() >= 2)
303 Channel* channel = Instance->FindChan(params[0]);
306 User* x = Instance->FindNick(prefix);
309 if (warned.find(x->server) == warned.end())
311 Instance->Logs->Log("m_spanningtree",DEFAULT,"WARNING: I revceived modes '%s' from another server '%s'. This is not compliant with InspIRCd. Please check that server for bugs.", params[1].c_str(), x->server);
312 Instance->SNO->WriteToSnoMask('d', "WARNING: The server %s is sending nonstandard modes: '%s MODE %s' where FMODE should be used, and may cause desyncs.", x->server, x->nick, params[1].c_str());
313 warned[x->server] = x->nick;
319 else if (command == "SVSMODE")
326 * Now, check for (and parse) commands as appropriate. -- w
329 /* Find the server that this command originated from, used in the handlers below */
330 TreeServer *ServerSource = Utils->FindServer(prefix);
332 /* Find the link we just got this from so we don't bounce it back incorrectly */
333 std::string sourceserv = this->myhost;
334 if (!this->InboundServerName.empty())
336 sourceserv = this->InboundServerName;
340 * XXX one of these days, this needs to be moved into class Commands.
342 if (command == "UID")
344 return this->ParseUID(prefix, params);
346 else if (command == "FJOIN")
348 return this->ForceJoin(prefix,params);
350 else if (command == "STATS")
352 return this->Stats(prefix, params);
354 else if (command == "MOTD")
356 return this->Motd(prefix, params);
358 else if (command == "KILL" && ServerSource)
360 // Kill from a server
361 return this->RemoteKill(prefix,params);
363 else if (command == "MODULES")
365 return this->Modules(prefix, params);
367 else if (command == "ADMIN")
369 return this->Admin(prefix, params);
371 else if (command == "SERVER")
373 return this->RemoteServer(prefix,params);
375 else if (command == "ERROR")
377 return this->Error(params);
379 else if (command == "OPERTYPE")
381 return this->OperType(prefix,params);
383 else if (command == "FMODE")
385 return this->ForceMode(prefix,params);
387 else if (command == "FTOPIC")
389 return this->ForceTopic(prefix,params);
391 else if (command == "REHASH")
393 return this->RemoteRehash(prefix,params);
395 else if (command == "METADATA")
397 return this->MetaData(prefix,params);
399 else if (command == "PING")
401 return this->LocalPing(prefix,params);
403 else if (command == "PONG")
405 return this->LocalPong(prefix,params);
407 else if (command == "VERSION")
409 return this->ServerVersion(prefix,params);
411 else if (command == "FHOST")
413 return this->ChangeHost(prefix,params);
415 else if (command == "FNAME")
417 return this->ChangeName(prefix,params);
419 else if (command == "ADDLINE")
421 return this->AddLine(prefix,params);
423 else if (command == "DELLINE")
425 return this->DelLine(prefix,params);
427 else if (command == "SVSNICK")
429 return this->ForceNick(prefix,params);
431 else if (command == "OPERQUIT")
433 return this->OperQuit(prefix,params);
435 else if (command == "IDLE")
437 return this->Whois(prefix,params);
439 else if (command == "PUSH")
441 return this->Push(prefix,params);
443 else if (command == "TIMESET")
445 return this->HandleSetTime(prefix, params);
447 else if (command == "TIME")
449 return this->Time(prefix,params);
451 else if ((command == "KICK") && (Utils->IsServer(prefix)))
453 if (params.size() == 3)
455 User* user = this->Instance->FindNick(params[1]);
456 Channel* chan = this->Instance->FindChan(params[0]);
459 if (!chan->ServerKickUser(user, params[2].c_str(), false))
460 /* Yikes, the channels gone! */
465 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
467 else if (command == "SVSJOIN")
469 return this->ServiceJoin(prefix,params);
471 else if (command == "SVSPART")
473 return this->ServicePart(prefix,params);
475 else if (command == "SQUIT")
477 if (params.size() == 2)
479 this->Squit(Utils->FindServer(params[0]),params[1]);
483 else if (command == "OPERNOTICE")
485 if (params.size() >= 1)
486 Instance->SNO->WriteToSnoMask('A', "From " + prefix + ": " + params[0]);
487 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
489 else if (command == "MODENOTICE")
491 if (params.size() >= 2)
493 Instance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", prefix.c_str(), params[1].c_str());
495 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
497 else if (command == "SNONOTICE")
499 if (params.size() >= 2)
501 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + prefix + ": "+ params[1]);
503 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
505 else if (command == "BURST")
507 // Set prefix server as bursting
510 this->Instance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", prefix.c_str());
514 ServerSource->bursting = true;
515 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
517 else if (command == "ENDBURST")
521 this->Instance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", prefix.c_str());
525 ServerSource->FinishBurst();
526 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
528 else if (command == "MODE")
530 // Server-prefix MODE.
531 const char* modelist[MAXPARAMETERS];
532 for (size_t i = 0; i < params.size(); i++)
533 modelist[i] = params[i].c_str();
535 // Insert into the parser
536 this->Instance->SendMode(modelist, params.size(), this->Instance->FakeClient);
538 // Pass out to the network
539 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
544 * Not a special s2s command. Emulate the user doing it.
545 * This saves us having a huge ugly command parser again.
547 User *who = this->Instance->FindUUID(prefix);
551 // this looks ugly because command is an irc::string
552 this->SendError("Command (" + std::string(command.c_str()) + ") from unknown prefix (" + prefix + ")! Dropping link.");
556 if (command == "NICK")
558 if (params.size() != 2)
560 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
563 /* Update timestamp on user when they change nicks */
564 who->age = atoi(params[1].c_str());
567 * On nick messages, check that the nick doesnt already exist here.
568 * If it does, perform collision logic.
570 User* x = this->Instance->FindNickOnly(params[0]);
571 if ((x) && (x != who))
574 /* x is local, who is remote */
575 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
579 * Remote client lost, or both lost, parsing this nickchange would be
580 * pointless, as the incoming client's server will soon recieve SVSNICK to
581 * change its nick to its UID. :) -- w00t
589 const char* strparams[127];
590 for (unsigned int q = 0; q < params.size(); q++)
592 strparams[q] = params[q].c_str();
595 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
598 // command is irc::string, hence ugliness
599 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
603 * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
609 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
613 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
617 break; // end of state CONNECTED (phew).
622 std::string TreeSocket::GetName()
624 std::string sourceserv = this->myhost;
625 if (!this->InboundServerName.empty())
627 sourceserv = this->InboundServerName;
632 void TreeSocket::OnTimeout()
634 if (this->LinkState == CONNECTING)
636 Utils->Creator->RemoteMessage(NULL, "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
637 Link* MyLink = Utils->FindLink(myhost);
639 Utils->DoFailOver(MyLink);
643 void TreeSocket::OnClose()
645 // Test fix for big fuckup
646 if (this->LinkState != CONNECTED)
649 // Connection closed.
650 // If the connection is fully up (state CONNECTED)
651 // then propogate a netsplit to all peers.
652 std::string quitserver = this->myhost;
653 if (!this->InboundServerName.empty())
655 quitserver = this->InboundServerName;
657 TreeServer* s = Utils->FindServer(quitserver);
660 Squit(s,"Remote host closed the connection");
663 if (!quitserver.empty())
665 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' failed.",quitserver.c_str());
666 time_t server_uptime = Instance->Time() - this->age;
668 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
672 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
674 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
675 * or discovering if this port is the server port, we don't allow connections from any
676 * IPs for which we don't have a link block.
680 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
683 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
684 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
689 Utils->Creator->RemoteMessage(NULL,"Server connection from %s denied (no link blocks with that IP address)", ip);
690 Instance->SE->Close(newsock);
695 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
696 s = s; /* Whinge whinge whinge, thats all GCC ever does. */