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 "socketengine.h"
21 #include "treeserver.h"
23 #include "treesocket.h"
24 #include "resolvers.h"
26 /* Handle ERROR command */
27 bool TreeSocket::Error(parameterlist ¶ms)
29 if (params.size() < 1)
31 ServerInstance->SNO->WriteGlobalSno('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
32 /* we will return false to cause the socket to close. */
36 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
38 irc::tokenstream tokens(line);
40 if (!tokens.GetToken(prefix))
45 prefix = prefix.substr(1);
49 this->SendError("BUG (?) Empty prefix received: " + line);
52 if (!tokens.GetToken(command))
54 this->SendError("BUG (?) Empty command received: " + line);
64 this->SendError("BUG (?) Empty command received: " + line);
67 while (tokens.GetToken(param))
69 params.push_back(param);
73 void TreeSocket::ProcessLine(std::string &line)
79 ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
81 Split(line, prefix, command, params);
86 switch (this->LinkState)
93 * Waiting for SERVER command from remote server. Server initiating
94 * the connection sends the first SERVER command, listening server
95 * replies with theirs if its happy, then if the initiator is happy,
96 * it starts to send its net sync, which starts the merge, otherwise
99 if (command == "PASS")
102 * Ignore this silently. Some services packages insist on sending PASS, even
103 * when it is not required (i.e. by us). We have to ignore this here, otherwise
104 * as it's an unknown command (effectively), it will cause the connection to be
105 * closed, which probably isn't what people want. -- w00t
108 else if (command == "SERVER")
110 this->Inbound_Server(params);
112 else if (command == "ERROR")
116 else if (command == "USER")
118 this->SendError("Client connections to this port are prohibited.");
120 else if (command == "CAPAB")
126 this->SendError(std::string("Invalid command in negotiation phase: ") + command.c_str());
132 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
133 * The other option at this stage of things, of course, is for them to close our connection thanks
134 * to invalid credentials.. -- w
136 if (command == "SERVER")
139 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
140 * Both of these aren't allowable, so block them here. -- w
142 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
144 else if (command == "BURST")
148 time_t them = atoi(params[0].c_str());
149 time_t delta = them - ServerInstance->Time();
150 if ((delta < -600) || (delta > 600))
152 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));
153 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
156 else if ((delta < -30) || (delta > 30))
158 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
161 this->LinkState = CONNECTED;
163 Utils->timeoutlist.erase(this);
166 myautoconnect->position = -1;
167 myautoconnect = NULL;
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->DoOneToAllButSender(prefix, "BURST", params, InboundServerName);
183 Node->bursting = true;
186 else if (command == "ERROR")
190 else if (command == "CAPAB")
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 this->Outbound_Reply_Server(params);
208 else if (command == "ERROR")
212 else if (command == "CAPAB")
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.
223 this->ProcessConnectedLine(prefix, command, params);
228 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
230 User* who = ServerInstance->FindUUID(prefix);
231 std::string direction;
235 direction = who->server;
239 TreeServer* ServerSource = Utils->FindServer(prefix);
241 ServerSource = Utils->FindServer(GetName());
245 who = ServerSource->ServerUser;
250 /* It is important that we don't close the link here, unknown prefix can occur
251 * due to various race conditions such as the KILL message for a user somehow
252 * crossing the users QUIT further upstream from the server. Thanks jilles!
254 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
255 command.c_str(), prefix.c_str());
260 // Make sure prefix is still good
264 * Check for fake direction here, and drop any instances that are found.
265 * What is fake direction? Imagine the following server setup:
266 * 0AA <-> 0AB <-> 0AC
267 * Fake direction would be 0AC sending a message to 0AB claiming to be from
268 * 0AA, or something similar. Basically, a message taking a path that *cannot*
271 * When would this be seen?
272 * Well, hopefully never. It could be caused by race conditions, bugs, or
273 * "miscreant" servers, though, so let's check anyway. -- w
275 * We also check here for totally invalid prefixes (prefixes that are neither
276 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
277 * to the higher level functions. -- B
279 TreeServer* route_back_again = Utils->BestRouteTo(direction);
280 if ((!route_back_again) || (route_back_again->GetSocket() != this))
282 if (route_back_again)
283 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
284 prefix.c_str(),this->GetName().c_str());
289 * First up, check for any malformed commands (e.g. MODE without a timestamp)
290 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
292 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
295 // TODO move all this into Commands
296 if (command == "UID")
298 this->ParseUID(prefix, params);
300 else if (command == "FJOIN")
302 this->ForceJoin(who,params);
304 else if (command == "STATS")
306 this->Stats(prefix, params);
308 else if (command == "MOTD")
310 this->Motd(prefix, params);
312 else if (command == "ADMIN")
314 this->Admin(prefix, params);
316 else if (command == "MAP")
318 Utils->Creator->HandleMap(params, who);
320 else if (command == "SERVER")
322 this->RemoteServer(prefix,params);
324 else if (command == "ERROR")
328 else if (command == "OPERTYPE")
330 this->OperType(prefix,params);
332 else if (command == "AWAY")
334 this->Away(prefix,params);
336 else if (command == "FMODE")
338 this->ForceMode(who,params);
340 else if (command == "FTOPIC")
342 this->ForceTopic(prefix,params);
344 else if (command == "METADATA")
346 this->MetaData(prefix,params);
348 else if (command == "PING")
350 this->LocalPing(prefix,params);
352 else if (command == "PONG")
354 TreeServer *s = Utils->FindServer(prefix);
355 if (s && s->bursting)
357 ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
360 this->LocalPong(prefix,params);
362 else if (command == "VERSION")
364 this->ServerVersion(prefix,params);
366 else if (command == "FHOST")
368 this->ChangeHost(prefix,params);
370 else if (command == "FNAME")
372 this->ChangeName(prefix,params);
374 else if (command == "FIDENT")
376 this->ChangeIdent(prefix,params);
378 else if (command == "ADDLINE")
380 this->AddLine(prefix,params);
382 else if (command == "DELLINE")
384 this->DelLine(prefix,params);
386 else if (command == "SVSNICK")
388 this->SVSNick(prefix,params);
390 else if (command == "SAVE")
392 this->ForceNick(prefix,params);
394 else if (command == "OPERQUIT")
396 this->OperQuit(prefix,params);
398 else if (command == "IDLE")
400 this->Whois(prefix,params);
402 else if (command == "PUSH")
404 this->Push(prefix,params);
406 else if (command == "TIME")
408 this->Time(prefix,params);
410 else if (command == "SVSJOIN")
412 this->ServiceJoin(prefix,params);
414 else if (command == "SVSPART")
416 this->ServicePart(prefix,params);
418 else if (command == "SQUIT")
420 if (params.size() == 2)
422 this->Squit(Utils->FindServer(params[0]),params[1]);
425 else if (command == "SNONOTICE")
427 if (params.size() >= 2)
429 ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + who->nick + ": "+ params[1]);
430 Utils->DoOneToAllButSender(prefix, command, params, prefix);
433 else if (command == "BURST")
435 // Set prefix server as bursting
436 TreeServer* ServerSource = Utils->FindServer(prefix);
439 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
443 ServerSource->bursting = true;
444 Utils->DoOneToAllButSender(prefix, command, params, prefix);
446 else if (command == "ENDBURST")
448 TreeServer* ServerSource = Utils->FindServer(prefix);
451 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
455 ServerSource->FinishBurst();
456 Utils->DoOneToAllButSender(prefix, command, params, prefix);
458 else if (command == "ENCAP")
460 this->Encap(who, params);
462 else if (command == "NICK")
464 if (params.size() != 2)
466 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
472 SendError("Protocol violation: Server changing nick");
476 /* Update timestamp on user when they change nicks */
477 who->age = atoi(params[1].c_str());
480 * On nick messages, check that the nick doesnt already exist here.
481 * If it does, perform collision logic.
483 User* x = ServerInstance->FindNickOnly(params[0]);
484 if ((x) && (x != who))
487 /* x is local, who is remote */
488 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
492 * Remote client lost, or both lost, parsing or passing on this
493 * nickchange would be pointless, as the incoming client's server will
494 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
499 who->ForceNickChange(params[0].c_str());
500 Utils->RouteCommand(route_back_again, command, params, who);
504 Command* cmd = ServerInstance->Parser->GetHandler(command);
505 CmdResult res = CMD_INVALID;
506 if (cmd && params.size() >= cmd->min_params)
508 res = cmd->Handle(params, who);
511 if (res == CMD_INVALID)
512 SendError("Unrecognised or malformed command '" + command + "' -- possibly loaded mismatched modules");
513 if (res == CMD_SUCCESS)
514 Utils->RouteCommand(route_back_again, command, params, who);
518 std::string TreeSocket::GetName()
520 std::string sourceserv = this->myhost;
521 if (!this->InboundServerName.empty())
523 sourceserv = this->InboundServerName;
528 void TreeSocket::OnTimeout()
530 if (this->LinkState == CONNECTING)
532 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
536 void TreeSocket::Close()
538 this->BufferedSocket::Close();
540 // Test fix for big fuckup
541 if (this->LinkState != CONNECTED)
544 // Connection closed.
545 // If the connection is fully up (state CONNECTED)
546 // then propogate a netsplit to all peers.
547 std::string quitserver = this->myhost;
548 if (!this->InboundServerName.empty())
550 quitserver = this->InboundServerName;
552 TreeServer* s = Utils->FindServer(quitserver);
555 Squit(s,"Remote host closed the connection");
558 if (!quitserver.empty())
560 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
562 time_t server_uptime = ServerInstance->Time() - this->age;
564 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());