]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
11fdeb6cc62e8be612cf3cab78fdd547036d09ec
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / utils.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
8  *
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.
12  *
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
16  * details.
17  *
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/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "socket.h"
25 #include "xline.h"
26 #include "socketengine.h"
27
28 #include "main.h"
29 #include "utils.h"
30 #include "treeserver.h"
31 #include "link.h"
32 #include "treesocket.h"
33 #include "resolvers.h"
34
35 /* Create server sockets off a listener. */
36 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
37 {
38         if (from->bind_tag->getString("type") != "servers")
39                 return MOD_RES_PASSTHRU;
40
41         std::string incomingip = client->addr();
42
43         for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
44         {
45                 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
46                 {
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);
49                         return MOD_RES_ALLOW;
50                 }
51         }
52         ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
53         return MOD_RES_DENY;
54 }
55
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.
60  * (read as: lots).
61  */
62 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
63 {
64         if (ServerInstance->IsSID(ServerName))
65                 return this->FindServerID(ServerName);
66
67         server_hash::iterator iter = serverlist.find(ServerName.c_str());
68         if (iter != serverlist.end())
69         {
70                 return iter->second;
71         }
72         else
73         {
74                 return NULL;
75         }
76 }
77
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
82  * for more details.
83  */
84 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
85 {
86         if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
87                 return NULL;
88         TreeServer* Found = FindServer(ServerName);
89         if (Found)
90         {
91                 return Found->GetRoute();
92         }
93         else
94         {
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);
97                 if (u)
98                 {
99                         Found = FindServer(u->server);
100                         if (Found)
101                                 return Found->GetRoute();
102                 }
103
104                 return NULL;
105         }
106 }
107
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,
112  * deal with it.
113  */
114 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
115 {
116         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
117         {
118                 if (InspIRCd::Match(i->first,ServerName))
119                         return i->second;
120         }
121         return NULL;
122 }
123
124 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
125 {
126         server_hash::iterator iter = sidlist.find(id);
127         if (iter != sidlist.end())
128                 return iter->second;
129         else
130                 return NULL;
131 }
132
133 /* A convenient wrapper that returns true if a server exists */
134 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
135 {
136         return (FindServer(ServerName) != NULL);
137 }
138
139 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
140 {
141         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
142
143         this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
144         this->ReadConfiguration();
145 }
146
147 CullResult SpanningTreeUtilities::cull()
148 {
149         while (TreeRoot->ChildCount())
150         {
151                 TreeServer* child_server = TreeRoot->GetChild(0);
152                 if (child_server)
153                 {
154                         TreeSocket* sock = child_server->GetSocket();
155                         sock->Close();
156                 }
157         }
158
159         for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
160         {
161                 TreeSocket* s = i->first;
162                 s->Close();
163         }
164         TreeRoot->cull();
165
166         return classbase::cull();
167 }
168
169 SpanningTreeUtilities::~SpanningTreeUtilities()
170 {
171         delete TreeRoot;
172 }
173
174 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
175 {
176         if (list.find(server) == list.end())
177                 list[server] = server;
178 }
179
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)
182 {
183         unsigned int minrank = 0;
184         if (status)
185         {
186                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
187                 if (mh)
188                         minrank = mh->GetPrefixRank();
189         }
190
191         const UserMembList *ulist = c->GetUsers();
192
193         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
194         {
195                 if (IS_LOCAL(i->first))
196                         continue;
197
198                 if (minrank && i->second->getRank() < minrank)
199                         continue;
200
201                 if (exempt_list.find(i->first) == exempt_list.end())
202                 {
203                         TreeServer* best = this->BestRouteTo(i->first->server);
204                         if (best)
205                                 AddThisServer(best,list);
206                 }
207         }
208         return;
209 }
210
211 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, const parameterlist &params)
212 {
213         TreeServer* omitroute = this->BestRouteTo(omit);
214         unsigned int items =this->TreeRoot->ChildCount();
215         for (unsigned int x = 0; x < items; x++)
216         {
217                 TreeServer* Route = this->TreeRoot->GetChild(x);
218                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
219                 {
220                         TreeSocket* Sock = Route->GetSocket();
221                         if (Sock)
222                                 Sock->WriteLine(data);
223                 }
224         }
225         return true;
226 }
227
228 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, const parameterlist &params, std::string omit)
229 {
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++)
234         {
235                 FullLine = FullLine + " " + params[x];
236         }
237         unsigned int items = this->TreeRoot->ChildCount();
238         for (unsigned int x = 0; x < items; x++)
239         {
240                 TreeServer* Route = this->TreeRoot->GetChild(x);
241                 // Send the line IF:
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))
246                 {
247                         TreeSocket* Sock = Route->GetSocket();
248                         if (Sock)
249                                 Sock->WriteLine(FullLine);
250                 }
251         }
252         return true;
253 }
254
255 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, const parameterlist &params)
256 {
257         std::string FullLine = ":" + prefix + " " + command;
258         unsigned int words = params.size();
259         for (unsigned int x = 0; x < words; x++)
260         {
261                 FullLine = FullLine + " " + params[x];
262         }
263         unsigned int items = this->TreeRoot->ChildCount();
264         for (unsigned int x = 0; x < items; x++)
265         {
266                 TreeServer* Route = this->TreeRoot->GetChild(x);
267                 if (Route && Route->GetSocket())
268                 {
269                         TreeSocket* Sock = Route->GetSocket();
270                         if (Sock)
271                                 Sock->WriteLine(FullLine);
272                 }
273         }
274         return true;
275 }
276
277 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, const parameterlist &params)
278 {
279         std::string spfx = prefix;
280         std::string scmd = command;
281         return this->DoOneToMany(spfx, scmd, params);
282 }
283
284 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, const parameterlist &params, std::string omit)
285 {
286         std::string spfx = prefix;
287         std::string scmd = command;
288         return this->DoOneToAllButSender(spfx, scmd, params, omit);
289 }
290
291 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, const parameterlist &params, std::string target)
292 {
293         TreeServer* Route = this->BestRouteTo(target);
294         if (Route)
295         {
296                 std::string FullLine = ":" + prefix + " " + command;
297                 unsigned int words = params.size();
298                 for (unsigned int x = 0; x < words; x++)
299                 {
300                         FullLine = FullLine + " " + params[x];
301                 }
302                 if (Route && Route->GetSocket())
303                 {
304                         TreeSocket* Sock = Route->GetSocket();
305                         if (Sock)
306                                 Sock->WriteLine(FullLine);
307                 }
308                 return true;
309         }
310         else
311         {
312                 return false;
313         }
314 }
315
316 void SpanningTreeUtilities::RefreshIPCache()
317 {
318         ValidIPs.clear();
319         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
320         {
321                 Link* L = *i;
322                 if (!L->Port)
323                 {
324                         ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block without a port.");
325                         /* Invalid link block */
326                         continue;
327                 }
328
329                 if (L->AllowMask.length())
330                         ValidIPs.push_back(L->AllowMask);
331
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);
336                 else
337                 {
338                         try
339                         {
340                                 bool cached;
341                                 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
342                                 ServerInstance->AddResolver(sr, cached);
343                         }
344                         catch (...)
345                         {
346                         }
347                 }
348         }
349 }
350
351 void SpanningTreeUtilities::ReadConfiguration()
352 {
353         ConfigReader Conf;
354
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);
363
364         if (PingFreq == 0)
365                 PingFreq = 60;
366
367         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
368                 PingWarnTime = 0;
369
370         AutoconnectBlocks.clear();
371         LinkBlocks.clear();
372         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
373         for(ConfigIter i = tags.first; i != tags.second; ++i)
374         {
375                 ConfigTag* tag = i->second;
376                 reference<Link> L = new Link(tag);
377                 std::string linkname = tag->getString("name");
378                 L->Name = linkname.c_str();
379                 L->AllowMask = tag->getString("allowmask");
380                 L->IPAddr = tag->getString("ipaddr");
381                 L->Port = tag->getInt("port");
382                 L->SendPass = tag->getString("sendpass", tag->getString("password"));
383                 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
384                 L->Fingerprint = tag->getString("fingerprint");
385                 L->HiddenFromStats = tag->getBool("statshidden");
386                 L->Timeout = tag->getInt("timeout", 30);
387                 L->Hook = tag->getString("ssl");
388                 L->Bind = tag->getString("bind");
389                 L->Hidden = tag->getBool("hidden");
390
391                 if (L->Name.empty())
392                         throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
393
394                 if (L->Name.find('.') == std::string::npos)
395                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
396
397                 if (L->Name.length() > 64)
398                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
399
400                 if (L->RecvPass.empty())
401                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
402
403                 if (L->SendPass.empty())
404                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
405
406                 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
407                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
408
409                 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
410                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
411
412                 if (L->IPAddr.empty())
413                 {
414                         L->IPAddr = "*";
415                         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.");
416                 }
417
418                 if (!L->Port)
419                         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
421                 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
422                 LinkBlocks.push_back(L);
423         }
424
425         tags = ServerInstance->Config->ConfTags("autoconnect");
426         for(ConfigIter i = tags.first; i != tags.second; ++i)
427         {
428                 ConfigTag* tag = i->second;
429                 reference<Autoconnect> A = new Autoconnect(tag);
430                 A->Period = tag->getInt("period");
431                 A->NextConnectTime = ServerInstance->Time() + A->Period;
432                 A->position = -1;
433                 irc::spacesepstream ss(tag->getString("server"));
434                 std::string server;
435                 while (ss.GetToken(server))
436                 {
437                         A->servers.push_back(server);
438                 }
439
440                 if (A->Period <= 0)
441                 {
442                         throw ModuleException("Invalid configuration for autoconnect, period not a positive integer!");
443                 }
444
445                 if (A->servers.empty())
446                 {
447                         throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
448                 }
449
450                 AutoconnectBlocks.push_back(A);
451         }
452
453         RefreshIPCache();
454 }
455
456 Link* SpanningTreeUtilities::FindLink(const std::string& name)
457 {
458         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
459         {
460                 Link* x = *i;
461                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
462                 {
463                         return x;
464                 }
465         }
466         return NULL;
467 }