2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2007-2008, 2012 Robin Burchell <robin+git@viroteck.net>
5 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6 * Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include "socketengine.h"
32 #include "treeserver.h"
34 #include "treesocket.h"
35 #include "resolvers.h"
37 /* Handle ERROR command */
38 void TreeSocket::Error(parameterlist ¶ms)
40 std::string msg = params.size() ? params[0] : "";
41 SetError("received ERROR " + msg);
44 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
46 irc::tokenstream tokens(line);
48 if (!tokens.GetToken(prefix))
53 prefix = prefix.substr(1);
57 this->SendError("BUG (?) Empty prefix received: " + line);
60 if (!tokens.GetToken(command))
62 this->SendError("BUG (?) Empty command received: " + line);
72 this->SendError("BUG (?) Empty command received: " + line);
75 while (tokens.GetToken(param))
77 params.push_back(param);
81 void TreeSocket::ProcessLine(std::string &line)
87 ServerInstance->Logs->Log("m_spanningtree", RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
89 Split(line, prefix, command, params);
94 switch (this->LinkState)
99 * Waiting for SERVER command from remote server. Server initiating
100 * the connection sends the first SERVER command, listening server
101 * replies with theirs if its happy, then if the initiator is happy,
102 * it starts to send its net sync, which starts the merge, otherwise
105 if (command == "PASS")
108 * Ignore this silently. Some services packages insist on sending PASS, even
109 * when it is not required (i.e. by us). We have to ignore this here, otherwise
110 * as it's an unknown command (effectively), it will cause the connection to be
111 * closed, which probably isn't what people want. -- w00t
114 else if (command == "SERVER")
116 this->Inbound_Server(params);
118 else if (command == "ERROR")
122 else if (command == "USER")
124 this->SendError("Client connections to this port are prohibited.");
126 else if (command == "CAPAB")
132 this->SendError(std::string("Invalid command in negotiation phase: ") + command.c_str());
138 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
139 * The other option at this stage of things, of course, is for them to close our connection thanks
140 * to invalid credentials.. -- w
142 if (command == "SERVER")
145 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
146 * Both of these aren't allowable, so block them here. -- w
148 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
150 else if (command == "BURST")
154 time_t them = atoi(params[0].c_str());
155 time_t delta = them - ServerInstance->Time();
156 if ((delta < -600) || (delta > 600))
158 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));
159 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
162 else if ((delta < -30) || (delta > 30))
164 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
167 this->LinkState = CONNECTED;
168 Utils->timeoutlist.erase(this);
170 MyRoot->bursting = true;
171 this->DoBurst(MyRoot);
173 parameterlist sparams;
174 sparams.push_back(MyRoot->GetName());
175 sparams.push_back("*");
176 sparams.push_back("0");
177 sparams.push_back(MyRoot->GetID());
178 sparams.push_back(":" + MyRoot->GetDesc());
179 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(), "SERVER", sparams, MyRoot->GetName());
180 Utils->DoOneToAllButSender(MyRoot->GetID(), "BURST", params, MyRoot->GetName());
182 else if (command == "ERROR")
186 else if (command == "CAPAB")
195 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
196 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
197 * + our netburst, which will put them into CONNECTED state. -- w
199 if (command == "SERVER")
201 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
202 this->Outbound_Reply_Server(params);
204 else if (command == "ERROR")
208 else if (command == "CAPAB")
216 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
217 * Anything from here on should be accepted a little more reasonably.
219 this->ProcessConnectedLine(prefix, command, params);
226 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
228 User* who = ServerInstance->FindUUID(prefix);
229 std::string direction;
233 TreeServer* ServerSource = Utils->FindServer(prefix);
235 ServerSource = MyRoot;
239 who = ServerSource->ServerUser;
243 /* It is important that we don't close the link here, unknown prefix can occur
244 * due to various race conditions such as the KILL message for a user somehow
245 * crossing the users QUIT further upstream from the server. Thanks jilles!
247 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
248 command.c_str(), prefix.c_str());
253 // Make sure prefix is still good
254 direction = who->server;
258 * Check for fake direction here, and drop any instances that are found.
259 * What is fake direction? Imagine the following server setup:
260 * 0AA <-> 0AB <-> 0AC
261 * Fake direction would be 0AC sending a message to 0AB claiming to be from
262 * 0AA, or something similar. Basically, a message taking a path that *cannot*
265 * When would this be seen?
266 * Well, hopefully never. It could be caused by race conditions, bugs, or
267 * "miscreant" servers, though, so let's check anyway. -- w
269 * We also check here for totally invalid prefixes (prefixes that are neither
270 * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
271 * to the higher level functions. -- B
273 TreeServer* route_back_again = Utils->BestRouteTo(direction);
274 if ((!route_back_again) || (route_back_again->GetSocket() != this))
276 if (route_back_again)
277 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
278 prefix.c_str(),linkID.c_str());
283 * First up, check for any malformed commands (e.g. MODE without a timestamp)
284 * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
286 if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
289 // TODO move all this into Commands
290 if (command == "MAP")
292 Utils->Creator->HandleMap(params, who);
294 else if (command == "SERVER")
296 this->RemoteServer(prefix,params);
298 else if (command == "ERROR")
302 else if (command == "AWAY")
304 this->Away(prefix,params);
306 else if (command == "PING")
308 this->LocalPing(prefix,params);
310 else if (command == "PONG")
312 TreeServer *s = Utils->FindServer(prefix);
313 if (s && s->bursting)
315 ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
318 this->LocalPong(prefix,params);
320 else if (command == "VERSION")
322 this->ServerVersion(prefix,params);
324 else if (command == "ADDLINE")
326 this->AddLine(prefix,params);
328 else if (command == "DELLINE")
330 this->DelLine(prefix,params);
332 else if (command == "SAVE")
334 this->ForceNick(prefix,params);
336 else if (command == "OPERQUIT")
338 this->OperQuit(prefix,params);
340 else if (command == "IDLE")
342 this->Whois(prefix,params);
344 else if (command == "PUSH")
346 this->Push(prefix,params);
348 else if (command == "SQUIT")
350 if (params.size() == 2)
352 this->Squit(Utils->FindServer(params[0]),params[1]);
355 else if (command == "SNONOTICE")
357 if (params.size() >= 2)
359 ServerInstance->SNO->WriteToSnoMask(params[0][0], "From " + who->nick + ": "+ params[1]);
360 params[1] = ":" + params[1];
361 Utils->DoOneToAllButSender(prefix, command, params, prefix);
364 else if (command == "BURST")
366 // Set prefix server as bursting
367 TreeServer* ServerSource = Utils->FindServer(prefix);
370 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
374 ServerSource->bursting = true;
375 Utils->DoOneToAllButSender(prefix, command, params, prefix);
377 else if (command == "ENDBURST")
379 TreeServer* ServerSource = Utils->FindServer(prefix);
382 ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
386 ServerSource->FinishBurst();
387 Utils->DoOneToAllButSender(prefix, command, params, prefix);
389 else if (command == "ENCAP")
391 this->Encap(who, params);
393 else if (command == "NICK")
395 if (params.size() != 2)
397 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
403 SendError("Protocol violation: Server changing nick");
407 /* Update timestamp on user when they change nicks */
408 who->age = atoi(params[1].c_str());
411 * On nick messages, check that the nick doesnt already exist here.
412 * If it does, perform collision logic.
414 User* x = ServerInstance->FindNickOnly(params[0]);
415 if ((x) && (x != who))
418 /* x is local, who is remote */
419 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
423 * Remote client lost, or both lost, parsing or passing on this
424 * nickchange would be pointless, as the incoming client's server will
425 * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
430 who->ForceNickChange(params[0].c_str());
431 Utils->RouteCommand(route_back_again, command, params, who);
435 Command* cmd = ServerInstance->Parser->GetHandler(command);
439 irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
440 ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Unrecognised S2S command :%s %s %s",
441 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
442 SendError("Unrecognised command '" + command + "' -- possibly loaded mismatched modules");
446 if (params.size() < cmd->min_params)
448 irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
449 ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Insufficient parameters for S2S command :%s %s %s",
450 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
451 SendError("Insufficient parameters for command '" + command + "'");
455 CmdResult res = cmd->Handle(params, who);
457 if (res == CMD_INVALID)
459 irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
460 ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Error handling S2S command :%s %s %s",
461 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
462 SendError("Error handling '" + command + "' -- possibly loaded mismatched modules");
464 else if (res == CMD_SUCCESS)
465 Utils->RouteCommand(route_back_again, command, params, who);
469 void TreeSocket::OnTimeout()
471 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
474 void TreeSocket::Close()
477 ServerInstance->GlobalCulls.AddItem(this);
478 this->BufferedSocket::Close();
479 SetError("Remote host closed connection");
481 // Connection closed.
482 // If the connection is fully up (state CONNECTED)
483 // then propogate a netsplit to all peers.
485 Squit(MyRoot,getError());
489 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
491 time_t server_uptime = ServerInstance->Time() - this->age;
493 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());