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 (ServerInstance->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 /* A convenient wrapper that returns true if a server exists */
134 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
136 return (FindServer(ServerName) != NULL);
139 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
141 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
143 this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
144 this->ReadConfiguration();
147 CullResult SpanningTreeUtilities::cull()
149 while (TreeRoot->ChildCount())
151 TreeServer* child_server = TreeRoot->GetChild(0);
154 TreeSocket* sock = child_server->GetSocket();
159 for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
161 TreeSocket* s = i->first;
166 return classbase::cull();
169 SpanningTreeUtilities::~SpanningTreeUtilities()
174 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
176 if (list.find(server) == list.end())
177 list[server] = server;
180 /* returns a list of DIRECT servernames for a specific channel */
181 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
183 unsigned int minrank = 0;
186 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
188 minrank = mh->GetPrefixRank();
191 const UserMembList *ulist = c->GetUsers();
193 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
195 if (IS_LOCAL(i->first))
198 if (minrank && i->second->getRank() < minrank)
201 if (exempt_list.find(i->first) == exempt_list.end())
203 TreeServer* best = this->BestRouteTo(i->first->server);
205 AddThisServer(best,list);
211 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, const parameterlist ¶ms)
213 TreeServer* omitroute = this->BestRouteTo(omit);
214 unsigned int items =this->TreeRoot->ChildCount();
215 for (unsigned int x = 0; x < items; x++)
217 TreeServer* Route = this->TreeRoot->GetChild(x);
218 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
220 TreeSocket* Sock = Route->GetSocket();
222 Sock->WriteLine(data);
228 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, const parameterlist ¶ms, std::string omit)
230 TreeServer* omitroute = this->BestRouteTo(omit);
231 std::string FullLine = ":" + prefix + " " + command;
232 unsigned int words = params.size();
233 for (unsigned int x = 0; x < words; x++)
235 FullLine = FullLine + " " + params[x];
237 unsigned int items = this->TreeRoot->ChildCount();
238 for (unsigned int x = 0; x < items; x++)
240 TreeServer* Route = this->TreeRoot->GetChild(x);
242 // The route has a socket (its a direct connection)
243 // The route isnt the one to be omitted
244 // The route isnt the path to the one to be omitted
245 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
247 TreeSocket* Sock = Route->GetSocket();
249 Sock->WriteLine(FullLine);
255 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, const parameterlist ¶ms)
257 std::string FullLine = ":" + prefix + " " + command;
258 unsigned int words = params.size();
259 for (unsigned int x = 0; x < words; x++)
261 FullLine = FullLine + " " + params[x];
263 unsigned int items = this->TreeRoot->ChildCount();
264 for (unsigned int x = 0; x < items; x++)
266 TreeServer* Route = this->TreeRoot->GetChild(x);
267 if (Route && Route->GetSocket())
269 TreeSocket* Sock = Route->GetSocket();
271 Sock->WriteLine(FullLine);
277 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, const parameterlist ¶ms)
279 std::string spfx = prefix;
280 std::string scmd = command;
281 return this->DoOneToMany(spfx, scmd, params);
284 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, const parameterlist ¶ms, std::string omit)
286 std::string spfx = prefix;
287 std::string scmd = command;
288 return this->DoOneToAllButSender(spfx, scmd, params, omit);
291 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, const parameterlist ¶ms, std::string target)
293 TreeServer* Route = this->BestRouteTo(target);
296 std::string FullLine = ":" + prefix + " " + command;
297 unsigned int words = params.size();
298 for (unsigned int x = 0; x < words; x++)
300 FullLine = FullLine + " " + params[x];
302 if (Route && Route->GetSocket())
304 TreeSocket* Sock = Route->GetSocket();
306 Sock->WriteLine(FullLine);
316 void SpanningTreeUtilities::RefreshIPCache()
319 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
324 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block without a port.");
325 /* Invalid link block */
329 if (L->AllowMask.length())
330 ValidIPs.push_back(L->AllowMask);
332 irc::sockets::sockaddrs dummy;
333 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
334 if ((L->IPAddr == "*") || (ipvalid))
335 ValidIPs.push_back(L->IPAddr);
341 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
342 ServerInstance->AddResolver(sr, cached);
351 void SpanningTreeUtilities::ReadConfiguration()
355 FlatLinks = Conf.ReadFlag("security","flatlinks",0);
356 HideULines = Conf.ReadFlag("security","hideulines",0);
357 AnnounceTSChange = Conf.ReadFlag("options","announcets",0);
358 AllowOptCommon = Conf.ReadFlag("options", "allowmismatch", 0);
359 ChallengeResponse = !Conf.ReadFlag("security", "disablehmac", 0);
360 quiet_bursts = Conf.ReadFlag("performance", "quietbursts", 0);
361 PingWarnTime = Conf.ReadInteger("options", "pingwarning", 0, true);
362 PingFreq = Conf.ReadInteger("options", "serverpingfreq", 0, true);
367 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
370 AutoconnectBlocks.clear();
372 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
373 for(ConfigIter i = tags.first; i != tags.second; ++i)
375 ConfigTag* tag = i->second;
376 reference<Link> L = new Link(tag);
377 L->Name = tag->getString("name").c_str();
378 L->AllowMask = tag->getString("allowmask");
379 L->IPAddr = tag->getString("ipaddr");
380 L->Port = tag->getInt("port");
381 L->SendPass = tag->getString("sendpass", tag->getString("password"));
382 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
383 L->Fingerprint = tag->getString("fingerprint");
384 L->HiddenFromStats = tag->getBool("statshidden");
385 L->Timeout = tag->getInt("timeout", 30);
386 L->Hook = tag->getString("ssl");
387 L->Bind = tag->getString("bind");
388 L->Hidden = tag->getBool("hidden");
391 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
393 if (L->Name.find('.') == std::string::npos)
394 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
396 if (L->Name.length() > 64)
397 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
399 if (L->RecvPass.empty())
400 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
402 if (L->SendPass.empty())
403 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
405 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
406 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
408 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
409 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
411 if (L->IPAddr.empty())
414 ServerInstance->Logs->Log("m_spanningtree",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.");
418 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block '" + assign(L->Name) + "' has no port defined, you will not be able to /connect it.");
420 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
421 LinkBlocks.push_back(L);
424 tags = ServerInstance->Config->ConfTags("autoconnect");
425 for(ConfigIter i = tags.first; i != tags.second; ++i)
427 ConfigTag* tag = i->second;
428 reference<Autoconnect> A = new Autoconnect(tag);
429 A->Period = tag->getInt("period");
430 A->NextConnectTime = ServerInstance->Time() + A->Period;
432 irc::spacesepstream ss(tag->getString("server"));
434 while (ss.GetToken(server))
436 A->servers.push_back(server);
441 throw ModuleException("Invalid configuration for autoconnect, period not a positive integer!");
444 if (A->servers.empty())
446 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
449 AutoconnectBlocks.push_back(A);
455 Link* SpanningTreeUtilities::FindLink(const std::string& name)
457 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
460 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))