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