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/>.
29 #include "treeserver.h"
30 #include "treesocket.h"
31 #include "resolvers.h"
34 /* Handle ERROR command */
35 void TreeSocket::Error(parameterlist ¶ms)
37 std::string msg = params.size() ? params[0] : "";
38 SetError("received ERROR " + msg);
41 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
43 irc::tokenstream tokens(line);
45 if (!tokens.GetToken(prefix))
50 prefix = prefix.substr(1);
54 this->SendError("BUG (?) Empty prefix received: " + line);
57 if (!tokens.GetToken(command))
59 this->SendError("BUG (?) Empty command received: " + line);
69 this->SendError("BUG (?) Empty command received: " + line);
72 while (tokens.GetToken(param))
74 params.push_back(param);
78 void TreeSocket::ProcessLine(std::string &line)
84 ServerInstance->Logs->Log(MODNAME, LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
86 Split(line, prefix, command, params);
91 switch (this->LinkState)
96 * Waiting for SERVER command from remote server. Server initiating
97 * the connection sends the first SERVER command, listening server
98 * replies with theirs if its happy, then if the initiator is happy,
99 * it starts to send its net sync, which starts the merge, otherwise
102 if (command == "PASS")
105 * Ignore this silently. Some services packages insist on sending PASS, even
106 * when it is not required (i.e. by us). We have to ignore this here, otherwise
107 * as it's an unknown command (effectively), it will cause the connection to be
108 * closed, which probably isn't what people want. -- w00t
111 else if (command == "SERVER")
113 this->Inbound_Server(params);
115 else if (command == "ERROR")
119 else if (command == "USER")
121 this->SendError("Client connections to this port are prohibited.");
123 else if (command == "CAPAB")
129 this->SendError("Invalid command in negotiation phase: " + command);
135 * We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
136 * The other option at this stage of things, of course, is for them to close our connection thanks
137 * to invalid credentials.. -- w
139 if (command == "SERVER")
142 * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
143 * Both of these aren't allowable, so block them here. -- w
145 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
147 else if (command == "BURST")
151 time_t them = ConvToInt(params[0]);
152 time_t delta = them - ServerInstance->Time();
153 if ((delta < -600) || (delta > 600))
155 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));
156 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
159 else if ((delta < -30) || (delta > 30))
161 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
165 // Check for duplicate server name/sid again, it's possible that a new
166 // server was introduced while we were waiting for them to send BURST.
167 // (we do not reserve their server name/sid when they send SERVER, we do it now)
168 if (!CheckDuplicate(capab->name, capab->sid))
171 FinishAuth(capab->name, capab->sid, capab->description, capab->hidden);
173 else if (command == "ERROR")
177 else if (command == "CAPAB")
186 * We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
187 * our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
188 * + our netburst, which will put them into CONNECTED state. -- w
190 if (command == "SERVER")
192 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
193 this->Outbound_Reply_Server(params);
195 else if (command == "ERROR")
199 else if (command == "CAPAB")
207 * Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
208 * Anything from here on should be accepted a little more reasonably.
210 this->ProcessConnectedLine(prefix, command, params);
217 User* TreeSocket::FindSource(const std::string& prefix, const std::string& command)
219 // Empty prefix means the source is the directly connected server that sent this command
221 return MyRoot->ServerUser;
223 // If the prefix string is a uuid or a sid FindUUID() returns the appropriate User object
224 User* who = ServerInstance->FindUUID(prefix);
228 // Some implementations wrongly send a server name as prefix occasionally, handle that too for now
229 TreeServer* const server = Utils->FindServer(prefix);
231 return server->ServerUser;
233 /* It is important that we don't close the link here, unknown prefix can occur
234 * due to various race conditions such as the KILL message for a user somehow
235 * crossing the users QUIT further upstream from the server. Thanks jilles!
238 if ((prefix.length() == UIDGenerator::UUID_LENGTH) && (isdigit(prefix[0])) &&
239 ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE")))
241 /* Special case, we cannot drop these commands as they've been committed already on a
242 * part of the network by the time we receive them, so in this scenario pretend the
243 * command came from a server to avoid desync.
246 who = ServerInstance->FindUUID(prefix.substr(0, 3));
249 return this->MyRoot->ServerUser;
256 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
258 User* who = FindSource(prefix, command);
261 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.", command.c_str(), prefix.c_str());
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* const server = TreeServer::Get(who);
282 if (server->GetSocket() != this)
284 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Protocol violation: Fake direction '%s' from connection '%s'", prefix.c_str(), linkID.c_str());
288 // Translate commands coming from servers using an older protocol
289 if (proto_version < ProtocolVersion)
291 if (!PreProcessOldProtocolMessage(who, command, params))
295 ServerCommand* scmd = Utils->Creator->CmdManager.GetHandler(command);
296 CommandBase* cmdbase = scmd;
300 // Not a special server-to-server command
301 cmd = ServerInstance->Parser.GetHandler(command);
304 if (command == "ERROR")
310 throw ProtocolException("Unknown command");
315 if (params.size() < cmdbase->min_params)
316 throw ProtocolException("Insufficient parameters");
318 if ((!params.empty()) && (params.back().empty()) && (!cmdbase->allow_empty_last_param))
320 // the last param is empty and the command handler doesn't allow that, check if there will be enough params if we drop the last
321 if (params.size()-1 < cmdbase->min_params)
328 res = scmd->Handle(who, params);
331 res = cmd->Handle(params, who);
332 if (res == CMD_INVALID)
333 throw ProtocolException("Error in command handler");
336 if (res == CMD_SUCCESS)
337 Utils->RouteCommand(server->GetRoute(), cmdbase, params, who);
340 void TreeSocket::OnTimeout()
342 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
345 void TreeSocket::Close()
350 ServerInstance->GlobalCulls.AddItem(this);
351 this->BufferedSocket::Close();
352 SetError("Remote host closed connection");
354 // Connection closed.
355 // If the connection is fully up (state CONNECTED)
356 // then propogate a netsplit to all peers.
358 MyRoot->SQuit(getError());
360 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
362 time_t server_uptime = ServerInstance->Time() - this->age;
365 std::string timestr = ModuleSpanningTree::TimeToStr(server_uptime);
366 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str());
370 void TreeSocket::FinishAuth(const std::string& remotename, const std::string& remotesid, const std::string& remotedesc, bool hidden)
372 this->LinkState = CONNECTED;
373 Utils->timeoutlist.erase(this);
377 MyRoot = new TreeServer(remotename, remotedesc, remotesid, Utils->TreeRoot, this, hidden);
379 // Mark the server as bursting
380 MyRoot->BeginBurst();
381 this->DoBurst(MyRoot);
383 CommandServer::Builder(MyRoot).Forward(MyRoot);