1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 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 "socketengine.h"
21 #include "treeserver.h"
23 #include "treesocket.h"
24 #include "resolvers.h"
26 /* Handle ERROR command */
27 void TreeSocket::Error(parameterlist ¶ms)
29 std::string msg = params.size() ? params[0] : "";
30 SetError("received ERROR " + msg);
33 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
35 irc::tokenstream tokens(line);
37 if (!tokens.GetToken(prefix))
42 prefix = prefix.substr(1);
46 this->SendError("BUG (?) Empty prefix received: " + line);
49 if (!tokens.GetToken(command))
51 this->SendError("BUG (?) Empty command received: " + line);
61 this->SendError("BUG (?) Empty command received: " + line);
64 while (tokens.GetToken(param))
66 params.push_back(param);
70 void TreeSocket::ProcessLine(std::string &line)
76 ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
78 Split(line, prefix, command, params);
83 switch (this->LinkState)
90 * Waiting for SERVER command from remote server. Server initiating
91 * the connection sends the first SERVER command, listening server
92 * replies with theirs if its happy, then if the initiator is happy,
93 * it starts to send its net sync, which starts the merge, otherwise
96 if (command == "PASS")
99 * Ignore this silently. Some services packages insist on sending PASS, even
100 * when it is not required (i.e. by us). We have to ignore this here, otherwise
101 * as it's an unknown command (effectively), it will cause the connection to be
102 * closed, which probably isn't what people want. -- w00t
105 else if (command == "SERVER")
107 this->Inbound_Server(params);
109 else if (command == "ERROR")
113 else if (command == "USER")
115 this->SendError("Client connections to this port are prohibited.");
117 else if (command == "CAPAB")
123 this->SendError(std::string("Invalid command in negotiation phase: ") + command.c_str());
129 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
130 * The other option at this stage of things, of course, is for them to close our connection thanks
131 * to invalid credentials.. -- w
133 if (command == "SERVER")
136 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
137 * Both of these aren't allowable, so block them here. -- w
139 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
141 else if (command == "BURST")
145 time_t them = atoi(params[0].c_str());
146 time_t delta = them - ServerInstance->Time();
147 if ((delta < -600) || (delta > 600))
149 ServerInstance->SNO->WriteGlobalSno('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));
150 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
153 else if ((delta < -30) || (delta > 30))
155 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
158 this->LinkState = CONNECTED;
160 Utils->timeoutlist.erase(this);
163 myautoconnect->position = -1;
164 myautoconnect = NULL;
167 Link* lnk = Utils->FindLink(InboundServerName);
169 Node = new TreeServer(this->Utils, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
171 Utils->TreeRoot->AddChild(Node);
172 parameterlist sparams;
173 sparams.push_back(InboundServerName);
174 sparams.push_back("*");
175 sparams.push_back("1");
176 sparams.push_back(InboundSID);
177 sparams.push_back(":"+InboundDescription);
178 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",sparams,InboundServerName);
179 Utils->DoOneToAllButSender(prefix, "BURST", params, InboundServerName);
180 Node->bursting = true;
183 else if (command == "ERROR")
187 else if (command == "CAPAB")
196 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
197 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
198 * + our netburst, which will put them into CONNECTED state. -- w
200 if (command == "SERVER")
202 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
203 this->Outbound_Reply_Server(params);
205 else if (command == "ERROR")
209 else if (command == "CAPAB")
217 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
218 * Anything from here on should be accepted a little more reasonably.
220 this->ProcessConnectedLine(prefix, command, params);
225 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
227 User* who = ServerInstance->FindUUID(prefix);
228 std::string direction;
232 direction = who->server;
236 TreeServer* ServerSource = Utils->FindServer(prefix);
238 ServerSource = Utils->FindServer(GetName());
242 who = ServerSource->ServerUser;
247 /* It is important that we don't close the link here, unknown prefix can occur
248 * due to various race conditions such as the KILL message for a user somehow
249 * crossing the users QUIT further upstream from the server. Thanks jilles!
251 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
252 command.c_str(), prefix.c_str());
257 // Make sure prefix is still good
261 * Check for fake direction here, and drop any instances that are found.
262 * What is fake direction? Imagine the following server setup:
263 * 0AA <-> 0AB <-> 0AC
264 * Fake direction would be 0AC sending a message to 0AB claiming to be from
265 * 0AA, or something similar. Basically, a message taking a path that *cannot*
268 * When would this be seen?
269 * Well, hopefully never. It could be caused by race conditions, bugs, or
270 * "miscreant" servers, though, so let's check anyway. -- w
272 * We also check here for totally invalid prefixes (prefixes that are neither
273 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
274 * to the higher level functions. -- B
276 TreeServer* route_back_again = Utils->BestRouteTo(direction);
277 if ((!route_back_again) || (route_back_again->GetSocket() != this))
279 if (route_back_again)
280 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
281 prefix.c_str(),this->GetName().c_str());
286 * First up, check for any malformed commands (e.g. MODE without a timestamp)
287 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
289 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
292 // TODO move all this into Commands
293 if (command == "MAP")
295 Utils->Creator->HandleMap(params, who);
297 else if (command == "SERVER")
299 this->RemoteServer(prefix,params);
301 else if (command == "ERROR")
305 else if (command == "AWAY")
307 this->Away(prefix,params);
309 else if (command == "PING")
311 this->LocalPing(prefix,params);
313 else if (command == "PONG")
315 TreeServer *s = Utils->FindServer(prefix);
316 if (s && s->bursting)
318 ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
321 this->LocalPong(prefix,params);
323 else if (command == "VERSION")
325 this->ServerVersion(prefix,params);
327 else if (command == "ADDLINE")
329 this->AddLine(prefix,params);
331 else if (command == "DELLINE")
333 this->DelLine(prefix,params);
335 else if (command == "SAVE")
337 this->ForceNick(prefix,params);
339 else if (command == "OPERQUIT")
341 this->OperQuit(prefix,params);
343 else if (command == "IDLE")
345 this->Whois(prefix,params);
347 else if (command == "PUSH")
349 this->Push(prefix,params);
351 else if (command == "SQUIT")
353 if (params.size() == 2)
355 this->Squit(Utils->FindServer(params[0]),params[1]);
358 else if (command == "SNONOTICE")
360 if (params.size() >= 2)
362 ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + who->nick + ": "+ params[1]);
363 Utils->DoOneToAllButSender(prefix, command, params, prefix);
366 else if (command == "BURST")
368 // Set prefix server as bursting
369 TreeServer* ServerSource = Utils->FindServer(prefix);
372 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
376 ServerSource->bursting = true;
377 Utils->DoOneToAllButSender(prefix, command, params, prefix);
379 else if (command == "ENDBURST")
381 TreeServer* ServerSource = Utils->FindServer(prefix);
384 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
388 ServerSource->FinishBurst();
389 Utils->DoOneToAllButSender(prefix, command, params, prefix);
391 else if (command == "ENCAP")
393 this->Encap(who, params);
395 else if (command == "NICK")
397 if (params.size() != 2)
399 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
405 SendError("Protocol violation: Server changing nick");
409 /* Update timestamp on user when they change nicks */
410 who->age = atoi(params[1].c_str());
413 * On nick messages, check that the nick doesnt already exist here.
414 * If it does, perform collision logic.
416 User* x = ServerInstance->FindNickOnly(params[0]);
417 if ((x) && (x != who))
420 /* x is local, who is remote */
421 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
425 * Remote client lost, or both lost, parsing or passing on this
426 * nickchange would be pointless, as the incoming client's server will
427 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
432 who->ForceNickChange(params[0].c_str());
433 Utils->RouteCommand(route_back_again, command, params, who);
437 Command* cmd = ServerInstance->Parser->GetHandler(command);
438 CmdResult res = CMD_INVALID;
439 if (cmd && params.size() >= cmd->min_params)
441 res = cmd->Handle(params, who);
444 if (res == CMD_INVALID)
445 SendError("Unrecognised or malformed command '" + command + "' -- possibly loaded mismatched modules");
446 if (res == CMD_SUCCESS)
447 Utils->RouteCommand(route_back_again, command, params, who);
451 std::string TreeSocket::GetName()
453 std::string sourceserv = this->myhost;
454 if (!this->InboundServerName.empty())
456 sourceserv = this->InboundServerName;
461 void TreeSocket::OnTimeout()
463 if (this->LinkState == CONNECTING)
465 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
469 void TreeSocket::Close()
471 this->BufferedSocket::Close();
473 // Test fix for big fuckup
474 if (this->LinkState != CONNECTED)
477 // Connection closed.
478 // If the connection is fully up (state CONNECTED)
479 // then propogate a netsplit to all peers.
480 std::string quitserver = this->myhost;
481 if (!this->InboundServerName.empty())
483 quitserver = this->InboundServerName;
485 TreeServer* s = Utils->FindServer(quitserver);
488 Squit(s,"Remote host closed the connection");
491 if (!quitserver.empty())
493 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
495 time_t server_uptime = ServerInstance->Time() - this->age;
497 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());