1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
12  *
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.
16  *
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
20  * details.
21  *
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/>.
24  */
25 
26 
27 #include "inspircd.h"
28 #include "listmode.h"
29 
30 #include "main.h"
31 #include "utils.h"
32 #include "treeserver.h"
33 #include "treesocket.h"
34 #include "resolvers.h"
35 #include "commandbuilder.h"
36 
37 SpanningTreeUtilities* Utils = NULL;
38 
OnAcceptConnection(int newsock,ListenSocket * from,irc::sockets::sockaddrs * client,irc::sockets::sockaddrs * server)39 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
40 {
41 	if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "servers"))
42 		return MOD_RES_PASSTHRU;
43 
44 	std::string incomingip = client->addr();
45 
46 	for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
47 	{
48 		if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
49 		{
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);
52 			return MOD_RES_ALLOW;
53 		}
54 	}
55 	ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
56 	return MOD_RES_DENY;
57 }
58 
FindServer(const std::string & ServerName)59 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
60 {
61 	if (InspIRCd::IsSID(ServerName))
62 		return this->FindServerID(ServerName);
63 
64 	server_hash::iterator iter = serverlist.find(ServerName);
65 	if (iter != serverlist.end())
66 	{
67 		return iter->second;
68 	}
69 	else
70 	{
71 		return NULL;
72 	}
73 }
74 
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.
77  */
FindServerMask(const std::string & ServerName)78 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
79 {
80 	for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
81 	{
82 		if (InspIRCd::Match(i->first,ServerName))
83 			return i->second;
84 	}
85 	return NULL;
86 }
87 
FindServerID(const std::string & id)88 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
89 {
90 	server_hash::iterator iter = sidlist.find(id);
91 	if (iter != sidlist.end())
92 		return iter->second;
93 	else
94 		return NULL;
95 }
96 
FindRouteTarget(const std::string & target)97 TreeServer* SpanningTreeUtilities::FindRouteTarget(const std::string& target)
98 {
99 	TreeServer* const server = FindServer(target);
100 	if (server)
101 		return server;
102 
103 	User* const user = ServerInstance->FindNick(target);
104 	if (user)
105 		return TreeServer::Get(user);
106 
107 	return NULL;
108 }
109 
SpanningTreeUtilities(ModuleSpanningTree * C)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
113 {
114 	ServerInstance->Timers.AddTimer(&RefreshTimer);
115 }
116 
cull()117 CullResult SpanningTreeUtilities::cull()
118 {
119 	const TreeServer::ChildServers& children = TreeRoot->GetChildren();
120 	while (!children.empty())
121 	{
122 		TreeSocket* sock = children.front()->GetSocket();
123 		sock->Close();
124 	}
125 
126 	for(TimeoutList::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
127 	{
128 		TreeSocket* s = i->first;
129 		s->Close();
130 	}
131 	TreeRoot->cull();
132 
133 	return classbase::cull();
134 }
135 
~SpanningTreeUtilities()136 SpanningTreeUtilities::~SpanningTreeUtilities()
137 {
138 	delete TreeRoot;
139 }
140 
141 // Returns a list of DIRECT servers for a specific channel
GetListOfServersForChannel(Channel * c,TreeSocketSet & list,char status,const CUList & exempt_list)142 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
143 {
144 	unsigned int minrank = 0;
145 	if (status)
146 	{
147 		PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
148 		if (mh)
149 			minrank = mh->GetPrefixRank();
150 	}
151 
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)
155 	{
156 		if (IS_LOCAL(i->first))
157 			continue;
158 
159 		if (minrank && i->second->getRank() < minrank)
160 			continue;
161 
162 		if (exempt_list.find(i->first) == exempt_list.end())
163 		{
164 			TreeServer* best = TreeServer::Get(i->first);
165 			list.insert(best->GetSocket());
166 
167 			TreeServer::ChildServers::iterator citer = std::find(children.begin(), children.end(), best);
168 			if (citer != children.end())
169 				children.erase(citer);
170 		}
171 	}
172 
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)
176 	{
177 		ModResult result;
178 		FIRST_MOD_RESULT_CUSTOM(Creator->GetBroadcastEventProvider(), ServerProtocol::BroadcastEventListener, OnBroadcastMessage, result, (c, *i));
179 		if (result == MOD_RES_ALLOW)
180 			list.insert((*i)->GetSocket());
181 	}
182 }
183 
DoOneToAllButSender(const CmdBuilder & params,TreeServer * omitroute)184 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
185 {
186 	const std::string& FullLine = params.str();
187 
188 	const TreeServer::ChildServers& children = TreeRoot->GetChildren();
189 	for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
190 	{
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)
194 		{
195 			Route->GetSocket()->WriteLine(FullLine);
196 		}
197 	}
198 }
199 
DoOneToOne(const CmdBuilder & params,Server * server)200 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
201 {
202 	TreeServer* ts = static_cast<TreeServer*>(server);
203 	TreeSocket* sock = ts->GetSocket();
204 	if (sock)
205 		sock->WriteLine(params);
206 }
207 
RefreshIPCache()208 void SpanningTreeUtilities::RefreshIPCache()
209 {
210 	ValidIPs.clear();
211 	for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
212 	{
213 		Link* L = *i;
214 		if (!L->Port)
215 		{
216 			ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
217 			/* Invalid link block */
218 			continue;
219 		}
220 
221 		ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
222 
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)
228 		{
229 			SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
230 			try
231 			{
232 				this->Creator->DNS->Process(sr);
233 			}
234 			catch (DNS::Exception &)
235 			{
236 				delete sr;
237 			}
238 		}
239 	}
240 }
241 
ReadConfiguration()242 void SpanningTreeUtilities::ReadConfiguration()
243 {
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);
254 
255 	if (PingWarnTime >= PingFreq)
256 		PingWarnTime = 0;
257 
258 	AutoconnectBlocks.clear();
259 	LinkBlocks.clear();
260 	ConfigTagList tags = ServerInstance->Config->ConfTags("link");
261 	for(ConfigIter i = tags.first; i != tags.second; ++i)
262 	{
263 		ConfigTag* tag = i->second;
264 		reference<Link> L = new Link(tag);
265 
266 		irc::spacesepstream sep = tag->getString("allowmask");
267 		for (std::string s; sep.GetToken(s);)
268 			L->AllowMasks.push_back(s);
269 
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");
281 
282 		if (L->Name.empty())
283 			throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
284 
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");
287 
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");
290 
291 		if (L->RecvPass.empty())
292 			throw ModuleException("Invalid configuration for server '"+L->Name+"', recvpass not defined");
293 
294 		if (L->SendPass.empty())
295 			throw ModuleException("Invalid configuration for server '"+L->Name+"', sendpass not defined");
296 
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");
299 
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");
302 
303 		if (L->IPAddr.empty())
304 		{
305 			L->IPAddr = "*";
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.");
307 		}
308 
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.");
311 
312 		L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
313 		LinkBlocks.push_back(L);
314 	}
315 
316 	tags = ServerInstance->Config->ConfTags("autoconnect");
317 	for(ConfigIter i = tags.first; i != tags.second; ++i)
318 	{
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;
323 		A->position = -1;
324 		irc::spacesepstream ss(tag->getString("server"));
325 		std::string server;
326 		while (ss.GetToken(server))
327 		{
328 			A->servers.push_back(server);
329 		}
330 
331 		if (A->servers.empty())
332 		{
333 			throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
334 		}
335 
336 		AutoconnectBlocks.push_back(A);
337 	}
338 
339 	for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
340 		i->second->CheckULine();
341 
342 	RefreshIPCache();
343 }
344 
FindLink(const std::string & name)345 Link* SpanningTreeUtilities::FindLink(const std::string& name)
346 {
347 	for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
348 	{
349 		Link* x = *i;
350 		if (InspIRCd::Match(x->Name, name, ascii_case_insensitive_map))
351 		{
352 			return x;
353 		}
354 	}
355 	return NULL;
356 }
357 
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)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)
359 {
360 	CmdBuilder msg(source, message_type);
361 	msg.push_tags(tags);
362 	msg.push_raw(' ');
363 	if (status != 0)
364 		msg.push_raw(status);
365 	msg.push_raw(target->name);
366 	if (!text.empty())
367 		msg.push_last(text);
368 
369 	TreeSocketSet list;
370 	this->GetListOfServersForChannel(target, list, status, exempt_list);
371 	for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
372 	{
373 		TreeSocket* Sock = *i;
374 		if (Sock != omit)
375 			Sock->WriteLine(msg);
376 	}
377 }
378 
SendListLimits(Channel * chan,TreeSocket * sock)379 void SpanningTreeUtilities::SendListLimits(Channel* chan, TreeSocket* sock)
380 {
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)
384 	{
385 		ListModeBase* lm = *i;
386 		buffer << lm->GetModeChar() << " " << lm->GetLimit(chan) << " ";
387 	}
388 
389 	std::string bufferstr = buffer.str();
390 	if (bufferstr.empty())
391 		return; // Should never happen.
392 
393 	bufferstr.erase(bufferstr.end() - 1);
394 	if (sock)
395 		sock->WriteLine(CommandMetadata::Builder(chan, "maxlist", bufferstr));
396 	else
397 		CommandMetadata::Builder(chan, "maxlist", bufferstr).Broadcast();
398 }
399