2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2009 Craig Edwards <craigedwards@brainbox.cc>
6 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
7 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "socketengine.h"
30 #include "treeserver.h"
32 #include "treesocket.h"
33 #include "resolvers.h"
35 /* Create server sockets off a listener. */
36 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
38 if (from->bind_tag->getString("type") != "servers")
39 return MOD_RES_PASSTHRU;
41 std::string incomingip = client->addr();
43 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
45 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
47 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
48 new TreeSocket(Utils, newsock, from, client, server);
52 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
56 /** Yay for fast searches!
57 * This is hundreds of times faster than recursion
58 * or even scanning a linked list, especially when
59 * there are more than a few servers to deal with.
62 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
64 if (InspIRCd::IsSID(ServerName))
65 return this->FindServerID(ServerName);
67 server_hash::iterator iter = serverlist.find(ServerName.c_str());
68 if (iter != serverlist.end())
78 /** Returns the locally connected server we must route a
79 * message through to reach server 'ServerName'. This
80 * only applies to one-to-one and not one-to-many routing.
81 * See the comments for the constructor of TreeServer
84 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
86 if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
88 TreeServer* Found = FindServer(ServerName);
91 return Found->GetRoute();
95 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
96 User *u = ServerInstance->FindNick(ServerName);
99 Found = FindServer(u->server);
101 return Found->GetRoute();
108 /** Find the first server matching a given glob mask.
109 * Theres no find-using-glob method of hash_map [awwww :-(]
110 * so instead, we iterate over the list using an iterator
111 * and match each one until we get a hit. Yes its slow,
114 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
116 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
118 if (InspIRCd::Match(i->first,ServerName))
124 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
126 server_hash::iterator iter = sidlist.find(id);
127 if (iter != sidlist.end())
133 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
135 ServerInstance->Logs->Log("m_spanningtree",LOG_DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
137 this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
138 this->ReadConfiguration();
141 CullResult SpanningTreeUtilities::cull()
143 while (TreeRoot->ChildCount())
145 TreeServer* child_server = TreeRoot->GetChild(0);
148 TreeSocket* sock = child_server->GetSocket();
153 for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
155 TreeSocket* s = i->first;
160 return classbase::cull();
163 SpanningTreeUtilities::~SpanningTreeUtilities()
168 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
170 if (list.find(server) == list.end())
171 list[server] = server;
174 /* returns a list of DIRECT servernames for a specific channel */
175 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
177 unsigned int minrank = 0;
180 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
182 minrank = mh->GetPrefixRank();
185 const UserMembList *ulist = c->GetUsers();
187 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
189 if (IS_LOCAL(i->first))
192 if (minrank && i->second->getRank() < minrank)
195 if (exempt_list.find(i->first) == exempt_list.end())
197 TreeServer* best = this->BestRouteTo(i->first->server);
199 AddThisServer(best,list);
205 std::string SpanningTreeUtilities::ConstructLine(const std::string& prefix, const std::string& command, const parameterlist& params)
207 std::string FullLine;
208 FullLine.reserve(MAXBUF);
209 FullLine = ":" + prefix + " " + command;
210 for (parameterlist::const_iterator x = params.begin(); x != params.end(); ++x)
212 FullLine.push_back(' ');
218 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string& prefix, const std::string& command, const parameterlist& params, const std::string& omit)
220 TreeServer* omitroute = this->BestRouteTo(omit);
221 std::string FullLine = ConstructLine(prefix, command, params);
223 unsigned int items = this->TreeRoot->ChildCount();
224 for (unsigned int x = 0; x < items; x++)
226 TreeServer* Route = this->TreeRoot->GetChild(x);
228 // The route has a socket (its a direct connection)
229 // The route isnt the one to be omitted
230 // The route isnt the path to the one to be omitted
231 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
233 TreeSocket* Sock = Route->GetSocket();
235 Sock->WriteLine(FullLine);
241 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, const parameterlist ¶ms)
243 std::string FullLine = ConstructLine(prefix, command, params);
245 unsigned int items = this->TreeRoot->ChildCount();
246 for (unsigned int x = 0; x < items; x++)
248 TreeServer* Route = this->TreeRoot->GetChild(x);
249 if (Route && Route->GetSocket())
251 TreeSocket* Sock = Route->GetSocket();
253 Sock->WriteLine(FullLine);
259 bool SpanningTreeUtilities::DoOneToOne(const std::string& prefix, const std::string& command, const parameterlist& params, const std::string& target)
261 TreeServer* Route = this->BestRouteTo(target);
264 if (Route && Route->GetSocket())
266 TreeSocket* Sock = Route->GetSocket();
268 Sock->WriteLine(ConstructLine(prefix, command, params));
278 void SpanningTreeUtilities::RefreshIPCache()
281 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
286 ServerInstance->Logs->Log("m_spanningtree",LOG_DEFAULT,"m_spanningtree: Ignoring a link block without a port.");
287 /* Invalid link block */
291 if (L->AllowMask.length())
292 ValidIPs.push_back(L->AllowMask);
294 irc::sockets::sockaddrs dummy;
295 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
296 if ((L->IPAddr == "*") || (ipvalid))
297 ValidIPs.push_back(L->IPAddr);
303 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
304 ServerInstance->AddResolver(sr, cached);
313 void SpanningTreeUtilities::ReadConfiguration()
315 ConfigTag* security = ServerInstance->Config->ConfValue("security");
316 ConfigTag* options = ServerInstance->Config->ConfValue("options");
317 FlatLinks = security->getBool("flatlinks");
318 HideULines = security->getBool("hideulines");
319 AnnounceTSChange = options->getBool("announcets");
320 AllowOptCommon = options->getBool("allowmismatch");
321 ChallengeResponse = !security->getBool("disablehmac");
322 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
323 PingWarnTime = options->getInt("pingwarning");
324 PingFreq = options->getInt("serverpingfreq");
329 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
332 AutoconnectBlocks.clear();
334 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
335 for(ConfigIter i = tags.first; i != tags.second; ++i)
337 ConfigTag* tag = i->second;
338 reference<Link> L = new Link(tag);
339 std::string linkname = tag->getString("name");
340 L->Name = linkname.c_str();
341 L->AllowMask = tag->getString("allowmask");
342 L->IPAddr = tag->getString("ipaddr");
343 L->Port = tag->getInt("port");
344 L->SendPass = tag->getString("sendpass", tag->getString("password"));
345 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
346 L->Fingerprint = tag->getString("fingerprint");
347 L->HiddenFromStats = tag->getBool("statshidden");
348 L->Timeout = tag->getInt("timeout", 30);
349 L->Hook = tag->getString("ssl");
350 L->Bind = tag->getString("bind");
351 L->Hidden = tag->getBool("hidden");
354 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
356 if (L->Name.find('.') == std::string::npos)
357 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
359 if (L->Name.length() > 64)
360 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
362 if (L->RecvPass.empty())
363 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
365 if (L->SendPass.empty())
366 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
368 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
369 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
371 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
372 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
374 if (L->IPAddr.empty())
377 ServerInstance->Logs->Log("m_spanningtree",LOG_DEFAULT,"Configuration warning: Link block '" + assign(L->Name) + "' has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want.");
381 ServerInstance->Logs->Log("m_spanningtree",LOG_DEFAULT,"Configuration warning: Link block '" + assign(L->Name) + "' has no port defined, you will not be able to /connect it.");
383 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
384 LinkBlocks.push_back(L);
387 tags = ServerInstance->Config->ConfTags("autoconnect");
388 for(ConfigIter i = tags.first; i != tags.second; ++i)
390 ConfigTag* tag = i->second;
391 reference<Autoconnect> A = new Autoconnect(tag);
392 A->Period = tag->getInt("period");
393 A->NextConnectTime = ServerInstance->Time() + A->Period;
395 irc::spacesepstream ss(tag->getString("server"));
397 while (ss.GetToken(server))
399 A->servers.push_back(server);
404 throw ModuleException("Invalid configuration for autoconnect, period not a positive integer!");
407 if (A->servers.empty())
409 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
412 AutoconnectBlocks.push_back(A);
418 Link* SpanningTreeUtilities::FindLink(const std::string& name)
420 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
423 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))