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 = Utils->ServerUser;
246 Utils->ServerUser->SetFakeServer(ServerSource->GetName());
247 Utils->ServerUser->uuid = ServerSource->GetID();
252 /* It is important that we don't close the link here, unknown prefix can occur
253 * due to various race conditions such as the KILL message for a user somehow
254 * crossing the users QUIT further upstream from the server. Thanks jilles!
256 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
257 command.c_str(), prefix.c_str());
262 // Make sure prefix is still good
266 * Check for fake direction here, and drop any instances that are found.
267 * What is fake direction? Imagine the following server setup:
268 * 0AA <-> 0AB <-> 0AC
269 * Fake direction would be 0AC sending a message to 0AB claiming to be from
270 * 0AA, or something similar. Basically, a message taking a path that *cannot*
273 * When would this be seen?
274 * Well, hopefully never. It could be caused by race conditions, bugs, or
275 * "miscreant" servers, though, so let's check anyway. -- w
277 * We also check here for totally invalid prefixes (prefixes that are neither
278 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
279 * to the higher level functions. -- B
281 TreeServer* route_back_again = Utils->BestRouteTo(direction);
282 if ((!route_back_again) || (route_back_again->GetSocket() != this))
284 if (route_back_again)
285 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
286 prefix.c_str(),this->GetName().c_str());
291 * First up, check for any malformed commands (e.g. MODE without a timestamp)
292 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
294 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
297 // TODO move all this into Commands
298 if (command == "UID")
300 this->ParseUID(prefix, params);
302 else if (command == "FJOIN")
304 this->ForceJoin(prefix,params);
306 else if (command == "STATS")
308 this->Stats(prefix, params);
310 else if (command == "MOTD")
312 this->Motd(prefix, params);
314 else if (command == "ADMIN")
316 this->Admin(prefix, params);
318 else if (command == "MAP")
320 Utils->Creator->HandleMap(params, who);
322 else if (command == "SERVER")
324 this->RemoteServer(prefix,params);
326 else if (command == "ERROR")
330 else if (command == "OPERTYPE")
332 this->OperType(prefix,params);
334 else if (command == "AWAY")
336 this->Away(prefix,params);
338 else if (command == "FMODE")
340 this->ForceMode(prefix,params);
342 else if (command == "FTOPIC")
344 this->ForceTopic(prefix,params);
346 else if (command == "METADATA")
348 this->MetaData(prefix,params);
350 else if (command == "PING")
352 this->LocalPing(prefix,params);
354 else if (command == "PONG")
356 TreeServer *s = Utils->FindServer(prefix);
357 if (s && s->bursting)
359 ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
362 this->LocalPong(prefix,params);
364 else if (command == "VERSION")
366 this->ServerVersion(prefix,params);
368 else if (command == "FHOST")
370 this->ChangeHost(prefix,params);
372 else if (command == "FNAME")
374 this->ChangeName(prefix,params);
376 else if (command == "FIDENT")
378 this->ChangeIdent(prefix,params);
380 else if (command == "ADDLINE")
382 this->AddLine(prefix,params);
384 else if (command == "DELLINE")
386 this->DelLine(prefix,params);
388 else if (command == "SVSNICK")
390 this->SVSNick(prefix,params);
392 else if (command == "SAVE")
394 this->ForceNick(prefix,params);
396 else if (command == "OPERQUIT")
398 this->OperQuit(prefix,params);
400 else if (command == "IDLE")
402 this->Whois(prefix,params);
404 else if (command == "PUSH")
406 this->Push(prefix,params);
408 else if (command == "TIME")
410 this->Time(prefix,params);
412 else if (command == "SVSJOIN")
414 this->ServiceJoin(prefix,params);
416 else if (command == "SVSPART")
418 this->ServicePart(prefix,params);
420 else if (command == "SQUIT")
422 if (params.size() == 2)
424 this->Squit(Utils->FindServer(params[0]),params[1]);
427 else if (command == "MODENOTICE")
429 if (params.size() >= 2)
431 ServerInstance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s",
432 who->nick.c_str(), params[1].c_str());
434 Utils->DoOneToAllButSender(prefix, command, params, prefix);
436 else if (command == "SNONOTICE")
438 if (params.size() >= 2)
440 ServerInstance->SNO->WriteGlobalSno(*(params[0].c_str()), "From " + who->nick + ": "+ params[1]);
441 Utils->DoOneToAllButSender(prefix, command, params, prefix);
444 else if (command == "BURST")
446 // Set prefix server as bursting
449 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
453 route_back_again->bursting = true;
454 Utils->DoOneToAllButSender(prefix, command, params, prefix);
456 else if (command == "ENDBURST")
458 TreeServer* ServerSource = Utils->FindServer(prefix);
461 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
465 ServerSource->FinishBurst();
466 Utils->DoOneToAllButSender(prefix, command, params, prefix);
468 else if (command == "ENCAP")
470 this->Encap(prefix, params);
472 else if (command == "NICK")
474 if (params.size() != 2)
476 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
482 SendError("Protocol violation: Server changing nick");
486 /* Update timestamp on user when they change nicks */
487 who->age = atoi(params[1].c_str());
490 * On nick messages, check that the nick doesnt already exist here.
491 * If it does, perform collision logic.
493 User* x = ServerInstance->FindNickOnly(params[0]);
494 if ((x) && (x != who))
497 /* x is local, who is remote */
498 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
502 * Remote client lost, or both lost, parsing or passing on this
503 * nickchange would be pointless, as the incoming client's server will
504 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
509 who->ForceNickChange(params[0].c_str());
510 Utils->RouteCommand(route_back_again, command, params, who);
514 Command* cmd = ServerInstance->Parser->GetHandler(command);
515 CmdResult res = CMD_INVALID;
516 if (cmd && params.size() >= cmd->min_params)
518 res = cmd->Handle(params, who);
521 if (res == CMD_INVALID)
522 SendError("Unrecognised or malformed command '" + command + "' -- possibly loaded mismatched modules");
523 if (res == CMD_SUCCESS)
524 Utils->RouteCommand(route_back_again, command, params, who);
528 std::string TreeSocket::GetName()
530 std::string sourceserv = this->myhost;
531 if (!this->InboundServerName.empty())
533 sourceserv = this->InboundServerName;
538 void TreeSocket::OnTimeout()
540 if (this->LinkState == CONNECTING)
542 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
546 void TreeSocket::Close()
548 this->BufferedSocket::Close();
550 // Test fix for big fuckup
551 if (this->LinkState != CONNECTED)
554 // Connection closed.
555 // If the connection is fully up (state CONNECTED)
556 // then propogate a netsplit to all peers.
557 std::string quitserver = this->myhost;
558 if (!this->InboundServerName.empty())
560 quitserver = this->InboundServerName;
562 TreeServer* s = Utils->FindServer(quitserver);
565 Squit(s,"Remote host closed the connection");
568 if (!quitserver.empty())
570 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
572 time_t server_uptime = ServerInstance->Time() - this->age;
574 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());