2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013-2014, 2017-2019 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/>.
31 #include "treeserver.h"
32 #include "treesocket.h"
33 #include "resolvers.h"
34 #include "commandbuilder.h"
36 SpanningTreeUtilities* Utils = NULL;
38 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
40 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "servers"))
41 return MOD_RES_PASSTHRU;
43 std::string incomingip = client->addr();
45 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
47 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
49 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
50 new TreeSocket(newsock, from, client, server);
54 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
58 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
60 if (InspIRCd::IsSID(ServerName))
61 return this->FindServerID(ServerName);
63 server_hash::iterator iter = serverlist.find(ServerName);
64 if (iter != serverlist.end())
74 /** Find the first server matching a given glob mask.
75 * We iterate over the list and match each one until we get a hit.
77 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
79 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
81 if (InspIRCd::Match(i->first,ServerName))
87 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
89 server_hash::iterator iter = sidlist.find(id);
90 if (iter != sidlist.end())
96 TreeServer* SpanningTreeUtilities::FindRouteTarget(const std::string& target)
98 TreeServer* const server = FindServer(target);
102 User* const user = ServerInstance->FindNick(target);
104 return TreeServer::Get(user);
109 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
110 : Creator(C), TreeRoot(NULL)
111 , 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
113 ServerInstance->Timers.AddTimer(&RefreshTimer);
116 CullResult SpanningTreeUtilities::cull()
118 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
119 while (!children.empty())
121 TreeSocket* sock = children.front()->GetSocket();
125 for(TimeoutList::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
127 TreeSocket* s = i->first;
132 return classbase::cull();
135 SpanningTreeUtilities::~SpanningTreeUtilities()
140 // Returns a list of DIRECT servers for a specific channel
141 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
143 unsigned int minrank = 0;
146 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
148 minrank = mh->GetPrefixRank();
151 TreeServer::ChildServers children = TreeRoot->GetChildren();
152 const Channel::MemberMap& ulist = c->GetUsers();
153 for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
155 if (IS_LOCAL(i->first))
158 if (minrank && i->second->getRank() < minrank)
161 if (exempt_list.find(i->first) == exempt_list.end())
163 TreeServer* best = TreeServer::Get(i->first);
164 list.insert(best->GetSocket());
166 TreeServer::ChildServers::iterator citer = std::find(children.begin(), children.end(), best);
167 if (citer != children.end())
168 children.erase(citer);
172 // Check whether the servers which do not have users in the channel might need this message. This
173 // is used to keep the chanhistory module synchronised between servers.
174 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
177 FIRST_MOD_RESULT_CUSTOM(Creator->GetBroadcastEventProvider(), ServerProtocol::BroadcastEventListener, OnBroadcastMessage, result, (c, *i));
178 if (result == MOD_RES_ALLOW)
179 list.insert((*i)->GetSocket());
183 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
185 const std::string& FullLine = params.str();
187 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
188 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
190 TreeServer* Route = *i;
191 // Send the line if the route isn't the path to the one to be omitted
192 if (Route != omitroute)
194 Route->GetSocket()->WriteLine(FullLine);
199 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
201 TreeServer* ts = static_cast<TreeServer*>(server);
202 TreeSocket* sock = ts->GetSocket();
204 sock->WriteLine(params);
207 void SpanningTreeUtilities::RefreshIPCache()
210 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
215 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
216 /* Invalid link block */
220 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
222 irc::sockets::sockaddrs dummy;
223 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
224 if ((L->IPAddr == "*") || (ipvalid))
225 ValidIPs.push_back(L->IPAddr);
226 else if (this->Creator->DNS)
228 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
231 this->Creator->DNS->Process(sr);
233 catch (DNS::Exception &)
241 void SpanningTreeUtilities::ReadConfiguration()
243 ConfigTag* security = ServerInstance->Config->ConfValue("security");
244 ConfigTag* options = ServerInstance->Config->ConfValue("options");
245 FlatLinks = security->getBool("flatlinks");
246 HideULines = security->getBool("hideulines");
247 HideSplits = security->getBool("hidesplits");
248 AnnounceTSChange = options->getBool("announcets");
249 AllowOptCommon = options->getBool("allowmismatch");
250 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
251 PingWarnTime = options->getDuration("pingwarning", 15);
252 PingFreq = options->getDuration("serverpingfreq", 60, 1);
254 if (PingWarnTime >= PingFreq)
257 AutoconnectBlocks.clear();
259 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
260 for(ConfigIter i = tags.first; i != tags.second; ++i)
262 ConfigTag* tag = i->second;
263 reference<Link> L = new Link(tag);
265 irc::spacesepstream sep = tag->getString("allowmask");
266 for (std::string s; sep.GetToken(s);)
267 L->AllowMasks.push_back(s);
269 L->Name = tag->getString("name");
270 L->IPAddr = tag->getString("ipaddr");
271 L->Port = tag->getUInt("port", 0);
272 L->SendPass = tag->getString("sendpass", tag->getString("password"));
273 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
274 L->Fingerprint = tag->getString("fingerprint");
275 L->HiddenFromStats = tag->getBool("statshidden");
276 L->Timeout = tag->getDuration("timeout", 30);
277 L->Hook = tag->getString("ssl");
278 L->Bind = tag->getString("bind");
279 L->Hidden = tag->getBool("hidden");
282 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
284 if (L->Name.find('.') == std::string::npos)
285 throw ModuleException("The link name '"+L->Name+"' is invalid as it must contain at least one '.' character");
287 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
288 throw ModuleException("The link name '"+L->Name+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
290 if (L->RecvPass.empty())
291 throw ModuleException("Invalid configuration for server '"+L->Name+"', recvpass not defined");
293 if (L->SendPass.empty())
294 throw ModuleException("Invalid configuration for server '"+L->Name+"', sendpass not defined");
296 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
297 throw ModuleException("Link block '" + L->Name + "' has a password set that contains a space character which is invalid");
299 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
300 throw ModuleException("Link block '" + L->Name + "' has a password set that begins with a colon (:) which is invalid");
302 if (L->IPAddr.empty())
305 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.");
308 if (!L->Port && L->IPAddr.find('/') == std::string::npos)
309 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no port defined, you will not be able to /connect it.");
311 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
312 LinkBlocks.push_back(L);
315 tags = ServerInstance->Config->ConfTags("autoconnect");
316 for(ConfigIter i = tags.first; i != tags.second; ++i)
318 ConfigTag* tag = i->second;
319 reference<Autoconnect> A = new Autoconnect(tag);
320 A->Period = tag->getDuration("period", 60, 1);
321 A->NextConnectTime = ServerInstance->Time() + A->Period;
323 irc::spacesepstream ss(tag->getString("server"));
325 while (ss.GetToken(server))
327 A->servers.push_back(server);
330 if (A->servers.empty())
332 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
335 AutoconnectBlocks.push_back(A);
338 for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
339 i->second->CheckULine();
344 Link* SpanningTreeUtilities::FindLink(const std::string& name)
346 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
349 if (InspIRCd::Match(x->Name, name, ascii_case_insensitive_map))
357 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)
359 CmdBuilder msg(source, message_type);
363 msg.push_raw(status);
364 msg.push_raw(target->name);
369 this->GetListOfServersForChannel(target, list, status, exempt_list);
370 for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
372 TreeSocket* Sock = *i;
374 Sock->WriteLine(msg);