2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013-2014, 2017-2019, 2021 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2013 Adam <Adam@anope.org>
6 * Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
8 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
9 * Copyright (C) 2008-2009 Robin Burchell <robin+git@viroteck.net>
10 * Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
11 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13 * This file is part of InspIRCd. InspIRCd is free software: you can
14 * redistribute it and/or modify it under the terms of the GNU General Public
15 * License as published by the Free Software Foundation, version 2.
17 * This program is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 #include "treeserver.h"
33 #include "treesocket.h"
34 #include "resolvers.h"
35 #include "commandbuilder.h"
37 SpanningTreeUtilities* Utils = NULL;
39 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
41 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "servers"))
42 return MOD_RES_PASSTHRU;
44 std::string incomingip = client->addr();
46 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
48 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
50 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
51 new TreeSocket(newsock, from, client, server);
55 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
59 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
61 if (InspIRCd::IsSID(ServerName))
62 return this->FindServerID(ServerName);
64 server_hash::iterator iter = serverlist.find(ServerName);
65 if (iter != serverlist.end())
75 /** Find the first server matching a given glob mask.
76 * We iterate over the list and match each one until we get a hit.
78 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
80 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
82 if (InspIRCd::Match(i->first,ServerName))
88 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
90 server_hash::iterator iter = sidlist.find(id);
91 if (iter != sidlist.end())
97 TreeServer* SpanningTreeUtilities::FindRouteTarget(const std::string& target)
99 TreeServer* const server = FindServer(target);
103 User* const user = ServerInstance->FindNick(target);
105 return TreeServer::Get(user);
110 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
111 : Creator(C), TreeRoot(NULL)
112 , PingFreq(60) // XXX: TreeServer constructor reads this and TreeRoot is created before the config is read, so init it to something (value doesn't matter) to avoid a valgrind warning in TimerManager on unload
114 ServerInstance->Timers.AddTimer(&RefreshTimer);
117 CullResult SpanningTreeUtilities::cull()
119 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
120 while (!children.empty())
122 TreeSocket* sock = children.front()->GetSocket();
126 for(TimeoutList::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
128 TreeSocket* s = i->first;
133 return classbase::cull();
136 SpanningTreeUtilities::~SpanningTreeUtilities()
141 // Returns a list of DIRECT servers for a specific channel
142 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
144 unsigned int minrank = 0;
147 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
149 minrank = mh->GetPrefixRank();
152 TreeServer::ChildServers children = TreeRoot->GetChildren();
153 const Channel::MemberMap& ulist = c->GetUsers();
154 for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
156 if (IS_LOCAL(i->first))
159 if (minrank && i->second->getRank() < minrank)
162 if (exempt_list.find(i->first) == exempt_list.end())
164 TreeServer* best = TreeServer::Get(i->first);
165 list.insert(best->GetSocket());
167 TreeServer::ChildServers::iterator citer = std::find(children.begin(), children.end(), best);
168 if (citer != children.end())
169 children.erase(citer);
173 // Check whether the servers which do not have users in the channel might need this message. This
174 // is used to keep the chanhistory module synchronised between servers.
175 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
178 FIRST_MOD_RESULT_CUSTOM(Creator->GetBroadcastEventProvider(), ServerProtocol::BroadcastEventListener, OnBroadcastMessage, result, (c, *i));
179 if (result == MOD_RES_ALLOW)
180 list.insert((*i)->GetSocket());
184 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
186 const std::string& FullLine = params.str();
188 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
189 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
191 TreeServer* Route = *i;
192 // Send the line if the route isn't the path to the one to be omitted
193 if (Route != omitroute)
195 Route->GetSocket()->WriteLine(FullLine);
200 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
202 TreeServer* ts = static_cast<TreeServer*>(server);
203 TreeSocket* sock = ts->GetSocket();
205 sock->WriteLine(params);
208 void SpanningTreeUtilities::RefreshIPCache()
211 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
216 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
217 /* Invalid link block */
221 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
223 irc::sockets::sockaddrs dummy;
224 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
225 if ((L->IPAddr == "*") || (ipvalid))
226 ValidIPs.push_back(L->IPAddr);
227 else if (this->Creator->DNS)
229 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
232 this->Creator->DNS->Process(sr);
234 catch (DNS::Exception &)
242 void SpanningTreeUtilities::ReadConfiguration()
244 ConfigTag* security = ServerInstance->Config->ConfValue("security");
245 ConfigTag* options = ServerInstance->Config->ConfValue("options");
246 FlatLinks = security->getBool("flatlinks");
247 HideULines = security->getBool("hideulines");
248 HideSplits = security->getBool("hidesplits");
249 AnnounceTSChange = options->getBool("announcets");
250 AllowOptCommon = options->getBool("allowmismatch");
251 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
252 PingWarnTime = options->getDuration("pingwarning", 15);
253 PingFreq = options->getDuration("serverpingfreq", 60, 1);
255 if (PingWarnTime >= PingFreq)
258 AutoconnectBlocks.clear();
260 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
261 for(ConfigIter i = tags.first; i != tags.second; ++i)
263 ConfigTag* tag = i->second;
264 reference<Link> L = new Link(tag);
266 irc::spacesepstream sep = tag->getString("allowmask");
267 for (std::string s; sep.GetToken(s);)
268 L->AllowMasks.push_back(s);
270 L->Name = tag->getString("name");
271 L->IPAddr = tag->getString("ipaddr");
272 L->Port = tag->getUInt("port", 0);
273 L->SendPass = tag->getString("sendpass", tag->getString("password"));
274 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
275 L->Fingerprint = tag->getString("fingerprint");
276 L->HiddenFromStats = tag->getBool("statshidden");
277 L->Timeout = tag->getDuration("timeout", 30);
278 L->Hook = tag->getString("sslprofile", tag->getString("ssl"));
279 L->Bind = tag->getString("bind");
280 L->Hidden = tag->getBool("hidden");
283 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
285 if (L->Name.find('.') == std::string::npos)
286 throw ModuleException("The link name '"+L->Name+"' is invalid as it must contain at least one '.' character");
288 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
289 throw ModuleException("The link name '"+L->Name+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
291 if (L->RecvPass.empty())
292 throw ModuleException("Invalid configuration for server '"+L->Name+"', recvpass not defined");
294 if (L->SendPass.empty())
295 throw ModuleException("Invalid configuration for server '"+L->Name+"', sendpass not defined");
297 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
298 throw ModuleException("Link block '" + L->Name + "' has a password set that contains a space character which is invalid");
300 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
301 throw ModuleException("Link block '" + L->Name + "' has a password set that begins with a colon (:) which is invalid");
303 if (L->IPAddr.empty())
306 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want.");
309 if (!L->Port && L->IPAddr.find('/') == std::string::npos)
310 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no port defined, you will not be able to /connect it.");
312 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
313 LinkBlocks.push_back(L);
316 tags = ServerInstance->Config->ConfTags("autoconnect");
317 for(ConfigIter i = tags.first; i != tags.second; ++i)
319 ConfigTag* tag = i->second;
320 reference<Autoconnect> A = new Autoconnect(tag);
321 A->Period = tag->getDuration("period", 60, 1);
322 A->NextConnectTime = ServerInstance->Time() + A->Period;
324 irc::spacesepstream ss(tag->getString("server"));
326 while (ss.GetToken(server))
328 A->servers.push_back(server);
331 if (A->servers.empty())
333 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
336 AutoconnectBlocks.push_back(A);
339 for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
340 i->second->CheckULine();
345 Link* SpanningTreeUtilities::FindLink(const std::string& name)
347 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
350 if (InspIRCd::Match(x->Name, name, ascii_case_insensitive_map))
358 void SpanningTreeUtilities::SendChannelMessage(User* source, Channel* target, const std::string& text, char status, const ClientProtocol::TagMap& tags, const CUList& exempt_list, const char* message_type, TreeSocket* omit)
360 CmdBuilder msg(source, message_type);
364 msg.push_raw(status);
365 msg.push_raw(target->name);
370 this->GetListOfServersForChannel(target, list, status, exempt_list);
371 for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
373 TreeSocket* Sock = *i;
375 Sock->WriteLine(msg);
379 void SpanningTreeUtilities::SendListLimits(Channel* chan, TreeSocket* sock)
381 std::stringstream buffer;
382 const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes();
383 for (ModeParser::ListModeList::const_iterator i = listmodes.begin(); i != listmodes.end(); ++i)
385 ListModeBase* lm = *i;
386 buffer << lm->GetModeChar() << " " << lm->GetLimit(chan) << " ";
389 std::string bufferstr = buffer.str();
390 if (bufferstr.empty())
391 return; // Should never happen.
393 bufferstr.erase(bufferstr.end() - 1);
395 sock->WriteLine(CommandMetadata::Builder(chan, "maxlist", bufferstr));
397 CommandMetadata::Builder(chan, "maxlist", bufferstr).Broadcast();