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 void TreeSocket::WriteLine(std::string line)
35 Instance->Logs->Log("m_spanningtree",DEBUG, "S[%d] O %s", this->GetFd(), line.c_str());
41 /* Handle ERROR command */
42 bool TreeSocket::Error(std::deque<std::string> ¶ms)
44 if (params.size() < 1)
46 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
47 /* we will return false to cause the socket to close. */
51 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
54 irc::tokenstream tokens(line);
56 while (tokens.GetToken(param))
63 bool TreeSocket::ProcessLine(std::string &line)
65 std::deque<std::string> params;
69 line = line.substr(0, line.find_first_of("\r\n"));
74 Instance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
76 this->Split(line.c_str(),params);
81 if ((params[0][0] == ':') && (params.size() > 1))
83 prefix = params[0].substr(1);
88 this->SendError("BUG (?) Empty prefix recieved.");
93 command = params[0].c_str();
96 switch (this->LinkState)
103 * Waiting for SERVER command from remote server. Server initiating
104 * the connection sends the first SERVER command, listening server
105 * replies with theirs if its happy, then if the initiator is happy,
106 * it starts to send its net sync, which starts the merge, otherwise
109 if (command == "PASS")
112 * Ignore this silently. Some services packages insist on sending PASS, even
113 * when it is not required (i.e. by us). We have to ignore this here, otherwise
114 * as it's an unknown command (effectively), it will cause the connection to be
115 * closed, which probably isn't what people want. -- w00t
118 else if (command == "SERVER")
120 return this->Inbound_Server(params);
122 else if (command == "ERROR")
124 return this->Error(params);
126 else if (command == "USER")
128 this->SendError("Client connections to this port are prohibited.");
131 else if (command == "CAPAB")
133 return this->Capab(params);
138 irc::string error = "Invalid command in negotiation phase: " + command;
139 this->SendError(assign(error));
146 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
147 * The other option at this stage of things, of course, is for them to close our connection thanks
148 * to invalid credentials.. -- w
150 if (command == "SERVER")
153 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
154 * Both of these aren't allowable, so block them here. -- w
156 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
159 else if (command == "BURST")
163 time_t them = atoi(params[0].c_str());
164 time_t delta = them - Instance->Time();
165 if ((delta < -600) || (delta > 600))
167 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));
168 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
171 else if ((delta < -30) || (delta > 30))
173 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
176 this->LinkState = CONNECTED;
177 Link* lnk = Utils->FindLink(InboundServerName);
179 Node = new TreeServer(this->Utils, this->Instance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
181 if (Node->DuplicateID())
183 this->SendError("Server ID "+InboundSID+" already exists on the network!");
184 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.");
188 Utils->TreeRoot->AddChild(Node);
190 params.push_back(InboundServerName);
191 params.push_back("*");
192 params.push_back("1");
193 params.push_back(InboundSID);
194 params.push_back(":"+InboundDescription);
195 Utils->DoOneToAllButSender(Instance->Config->GetSID(),"SERVER",params,InboundServerName);
196 Node->bursting = true;
199 else if (command == "ERROR")
201 return this->Error(params);
203 else if (command == "CAPAB")
205 return this->Capab(params);
211 * This really shouldn't happen.
213 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
219 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
220 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
221 * + our netburst, which will put them into CONNECTED state. -- w
223 if (command == "SERVER")
225 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
226 return this->Outbound_Reply_Server(params);
228 else if (command == "ERROR")
230 return this->Error(params);
232 else if (command == "CAPAB")
234 return this->Capab(params);
240 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
241 * Anything from here on should be accepted a little more reasonably.
246 * Check for fake direction here, and drop any instances that are found.
247 * What is fake direction? Imagine the following server setup:
248 * 0AA <-> 0AB <-> 0AC
249 * Fake direction would be 0AC sending a message to 0AB claiming to be from
250 * 0AA, or something similar. Basically, a message taking a path that *cannot*
253 * When would this be seen?
254 * Well, hopefully never. It could be caused by race conditions, bugs, or
255 * "miscreant" servers, though, so let's check anyway. -- w
257 std::string direction = prefix;
259 User *t = this->Instance->FindUUID(prefix);
262 direction = t->server;
265 TreeServer* route_back_again = Utils->BestRouteTo(direction);
266 if ((!route_back_again) || (route_back_again->GetSocket() != this))
268 if (route_back_again)
269 Instance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
273 * When there is activity on the socket, reset the ping counter so
274 * that we're not wasting bandwidth pinging an active server.
276 route_back_again->SetNextPingTime(Instance->Time() + Utils->PingFreq);
277 route_back_again->SetPingFlag();
282 * Empty prefix from a server to server link:
283 * This is somewhat bad/naughty, so let's set the prefix
284 * to be the link that we got it from, so we don't break anything. -- w
286 TreeServer* n = Utils->FindServer(GetName());
294 * First up, check for any malformed commands (e.g. MODE without a timestamp)
295 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
297 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
300 if (command == "MODE")
302 if (params.size() >= 2)
304 Channel* channel = Instance->FindChan(params[0]);
307 this->SendError("MODE may no longer be used on channels. Please use FMODE, with correct timestamp rules.");
315 * Now, check for (and parse) commands as appropriate. -- w
318 /* Find the server that this command originated from, used in the handlers below */
319 TreeServer *ServerSource = Utils->FindServer(prefix);
321 /* Find the link we just got this from so we don't bounce it back incorrectly */
322 std::string sourceserv = this->myhost;
323 if (!this->InboundServerName.empty())
325 sourceserv = this->InboundServerName;
329 * XXX one of these days, this needs to be moved into class Commands.
331 if (command == "UID")
333 return this->ParseUID(prefix, params);
335 else if (command == "FJOIN")
337 return this->ForceJoin(prefix,params);
339 else if ((command == "NOTICE" || command == "PRIVMSG") && (Utils->IsServer(prefix)))
341 return this->ServerMessage(assign(command), prefix, params, sourceserv);
343 else if (command == "STATS")
345 return this->Stats(prefix, params);
347 else if (command == "MOTD")
349 return this->Motd(prefix, params);
351 else if (command == "KILL" && ServerSource)
353 // Kill from a server
354 return this->RemoteKill(prefix,params);
356 else if (command == "MODULES")
358 return this->Modules(prefix, params);
360 else if (command == "ADMIN")
362 return this->Admin(prefix, params);
364 else if (command == "MAP")
366 User* user = Instance->FindNick(prefix);
369 std::vector<std::string> p(params.begin(), params.end());
370 return Utils->Creator->HandleMap(p, user);
373 else if (command == "SERVER")
375 return this->RemoteServer(prefix,params);
377 else if (command == "ERROR")
379 return this->Error(params);
381 else if (command == "OPERTYPE")
383 return this->OperType(prefix,params);
385 else if (command == "FMODE")
387 return this->ForceMode(prefix,params);
389 else if (command == "FTOPIC")
391 return this->ForceTopic(prefix,params);
393 else if (command == "METADATA")
395 return this->MetaData(prefix,params);
397 else if (command == "PING")
399 return this->LocalPing(prefix,params);
401 else if (command == "PONG")
403 return this->LocalPong(prefix,params);
405 else if (command == "VERSION")
407 return this->ServerVersion(prefix,params);
409 else if (command == "FHOST")
411 return this->ChangeHost(prefix,params);
413 else if (command == "FNAME")
415 return this->ChangeName(prefix,params);
417 else if (command == "ADDLINE")
419 return this->AddLine(prefix,params);
421 else if (command == "DELLINE")
423 return this->DelLine(prefix,params);
425 else if (command == "SVSNICK")
427 return this->ForceNick(prefix,params);
429 else if (command == "OPERQUIT")
431 return this->OperQuit(prefix,params);
433 else if (command == "IDLE")
435 return this->Whois(prefix,params);
437 else if (command == "PUSH")
439 return this->Push(prefix,params);
441 else if (command == "TIME")
443 return this->Time(prefix,params);
445 else if ((command == "KICK") && (Utils->IsServer(prefix)))
447 if (params.size() == 3)
449 TreeServer* pf = Utils->FindServer(prefix);
450 User* user = this->Instance->FindNick(params[1]);
451 Channel* chan = this->Instance->FindChan(params[0]);
452 if (pf && user && chan)
454 if (!chan->ServerKickUser(user, params[2].c_str(), false, pf->GetName().c_str()))
455 /* Yikes, the channels gone! */
460 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
462 else if (command == "SVSJOIN")
464 return this->ServiceJoin(prefix,params);
466 else if (command == "SVSPART")
468 return this->ServicePart(prefix,params);
470 else if (command == "SQUIT")
472 if (params.size() == 2)
474 this->Squit(Utils->FindServer(params[0]),params[1]);
478 else if (command == "MODENOTICE")
480 if (params.size() >= 2)
483 Instance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
485 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
487 else if (command == "SNONOTICE")
489 if (params.size() >= 2)
493 * The SetLocalOnly stuff here is to work around a bit of a nasty recursion bug.
494 * WriteToSnoMask() sends global snotices out globally, but of course this is a problem
495 * when triggering it from an already global snotice (yay loops).
497 * The current (horrible) solution I'm implementing here because nobody else seems to
498 * want to look at this except me, sets the snotice local-only temporarily, sends the snotice
499 * and then flushes the snomask.
501 * This works, but it is total and utter garbage, as it bypasses the snotice compression
502 * totally for this snomask (and may well trigger other snotices to send too early.....)
503 * but at least it won't crash the server.
505 * Master of hacks, we salute you!
509 // If we get a SNONOTICE, it must have been global... so set it local
510 Instance->SNO->SetLocalOnly(*(params[0].c_str()), true);
512 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
514 Instance->SNO->FlushSnotices();
515 // set it global again
516 Instance->SNO->SetLocalOnly(*(params[0].c_str()), true);
518 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
520 else if (command == "BURST")
522 // Set prefix server as bursting
525 this->Instance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
529 ServerSource->bursting = true;
530 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
532 else if (command == "ENDBURST")
536 this->Instance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
540 ServerSource->FinishBurst();
541 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
543 else if (command == "ENCAP")
545 return this->Encap(prefix, params);
547 else if (command == "MODE")
549 // Server-prefix MODE.
550 std::vector<std::string> modelist(params.begin(), params.end());
552 /* We don't support this for channel mode changes any more! */
553 if (params.size() >= 1)
555 if (Instance->FindChan(params[0]))
557 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.");
562 // Insert into the parser
563 this->Instance->SendMode(modelist, this->Instance->FakeClient);
565 // Pass out to the network
566 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
571 * Not a special s2s command. Emulate the user doing it.
572 * This saves us having a huge ugly command parser again.
574 User *who = this->Instance->FindUUID(prefix);
578 // this looks ugly because command is an irc::string
579 this->SendError("Command (" + std::string(command.c_str()) + ") from unknown prefix (" + prefix + ")! Dropping link.");
583 if (command == "NICK")
585 if (params.size() != 2)
587 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
590 /* Update timestamp on user when they change nicks */
591 who->age = atoi(params[1].c_str());
594 * On nick messages, check that the nick doesnt already exist here.
595 * If it does, perform collision logic.
597 User* x = this->Instance->FindNickOnly(params[0]);
598 if ((x) && (x != who))
601 /* x is local, who is remote */
602 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
606 * Remote client lost, or both lost, parsing this nickchange would be
607 * pointless, as the incoming client's server will soon recieve SVSNICK to
608 * change its nick to its UID. :) -- w00t
616 std::vector<std::string> strparams(params.begin(), params.end());
618 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, who))
622 * XXX: command is irc::string, hence ugliness
624 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
629 * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
634 /* CMD_SUCCESS falls through here */
638 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
642 break; // end of state CONNECTED (phew).
647 std::string TreeSocket::GetName()
649 std::string sourceserv = this->myhost;
650 if (!this->InboundServerName.empty())
652 sourceserv = this->InboundServerName;
657 void TreeSocket::OnTimeout()
659 if (this->LinkState == CONNECTING)
661 Utils->Creator->RemoteMessage(NULL, "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
662 Link* MyLink = Utils->FindLink(myhost);
664 Utils->DoFailOver(MyLink);
668 void TreeSocket::OnClose()
670 // Test fix for big fuckup
671 if (this->LinkState != CONNECTED)
674 // Connection closed.
675 // If the connection is fully up (state CONNECTED)
676 // then propogate a netsplit to all peers.
677 std::string quitserver = this->myhost;
678 if (!this->InboundServerName.empty())
680 quitserver = this->InboundServerName;
682 TreeServer* s = Utils->FindServer(quitserver);
685 Squit(s,"Remote host closed the connection");
688 if (!quitserver.empty())
690 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' failed.",quitserver.c_str());
691 time_t server_uptime = Instance->Time() - this->age;
693 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
697 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
701 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
704 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
706 if ((*i) == "*" || irc::sockets::MatchCIDR(ip, (*i).c_str()))
715 Utils->Creator->RemoteMessage(NULL,"Server connection from %s denied (no link blocks with that IP address)", ip);
716 Instance->SE->Close(newsock);
721 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
722 s = s; /* Whinge whinge whinge, thats all GCC ever does. */