]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Merge pull request #320 from ChrisTX/insp20+cleanupwin
[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 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
134 {
135         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
136
137         this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
138         this->ReadConfiguration();
139 }
140
141 CullResult SpanningTreeUtilities::cull()
142 {
143         while (TreeRoot->ChildCount())
144         {
145                 TreeServer* child_server = TreeRoot->GetChild(0);
146                 if (child_server)
147                 {
148                         TreeSocket* sock = child_server->GetSocket();
149                         sock->Close();
150                 }
151         }
152
153         for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
154         {
155                 TreeSocket* s = i->first;
156                 s->Close();
157         }
158         TreeRoot->cull();
159
160         return classbase::cull();
161 }
162
163 SpanningTreeUtilities::~SpanningTreeUtilities()
164 {
165         delete TreeRoot;
166 }
167
168 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
169 {
170         if (list.find(server) == list.end())
171                 list[server] = server;
172 }
173
174 /* returns a list of DIRECT servernames for a specific channel */
175 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
176 {
177         unsigned int minrank = 0;
178         if (status)
179         {
180                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
181                 if (mh)
182                         minrank = mh->GetPrefixRank();
183         }
184
185         const UserMembList *ulist = c->GetUsers();
186
187         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
188         {
189                 if (IS_LOCAL(i->first))
190                         continue;
191
192                 if (minrank && i->second->getRank() < minrank)
193                         continue;
194
195                 if (exempt_list.find(i->first) == exempt_list.end())
196                 {
197                         TreeServer* best = this->BestRouteTo(i->first->server);
198                         if (best)
199                                 AddThisServer(best,list);
200                 }
201         }
202         return;
203 }
204
205 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, const parameterlist &params, std::string omit)
206 {
207         TreeServer* omitroute = this->BestRouteTo(omit);
208         std::string FullLine = ":" + prefix + " " + command;
209         unsigned int words = params.size();
210         for (unsigned int x = 0; x < words; x++)
211         {
212                 FullLine = FullLine + " " + params[x];
213         }
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                 // Send the line IF:
219                 // The route has a socket (its a direct connection)
220                 // The route isnt the one to be omitted
221                 // The route isnt the path to the one to be omitted
222                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
223                 {
224                         TreeSocket* Sock = Route->GetSocket();
225                         if (Sock)
226                                 Sock->WriteLine(FullLine);
227                 }
228         }
229         return true;
230 }
231
232 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, const parameterlist &params)
233 {
234         std::string FullLine = ":" + prefix + " " + command;
235         unsigned int words = params.size();
236         for (unsigned int x = 0; x < words; x++)
237         {
238                 FullLine = FullLine + " " + params[x];
239         }
240         unsigned int items = this->TreeRoot->ChildCount();
241         for (unsigned int x = 0; x < items; x++)
242         {
243                 TreeServer* Route = this->TreeRoot->GetChild(x);
244                 if (Route && Route->GetSocket())
245                 {
246                         TreeSocket* Sock = Route->GetSocket();
247                         if (Sock)
248                                 Sock->WriteLine(FullLine);
249                 }
250         }
251         return true;
252 }
253
254 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, const parameterlist &params)
255 {
256         std::string spfx = prefix;
257         std::string scmd = command;
258         return this->DoOneToMany(spfx, scmd, params);
259 }
260
261 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, const parameterlist &params, std::string omit)
262 {
263         std::string spfx = prefix;
264         std::string scmd = command;
265         return this->DoOneToAllButSender(spfx, scmd, params, omit);
266 }
267
268 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, const parameterlist &params, std::string target)
269 {
270         TreeServer* Route = this->BestRouteTo(target);
271         if (Route)
272         {
273                 std::string FullLine = ":" + prefix + " " + command;
274                 unsigned int words = params.size();
275                 for (unsigned int x = 0; x < words; x++)
276                 {
277                         FullLine = FullLine + " " + params[x];
278                 }
279                 if (Route && Route->GetSocket())
280                 {
281                         TreeSocket* Sock = Route->GetSocket();
282                         if (Sock)
283                                 Sock->WriteLine(FullLine);
284                 }
285                 return true;
286         }
287         else
288         {
289                 return false;
290         }
291 }
292
293 void SpanningTreeUtilities::RefreshIPCache()
294 {
295         ValidIPs.clear();
296         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
297         {
298                 Link* L = *i;
299                 if (!L->Port)
300                 {
301                         ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block without a port.");
302                         /* Invalid link block */
303                         continue;
304                 }
305
306                 if (L->AllowMask.length())
307                         ValidIPs.push_back(L->AllowMask);
308
309                 irc::sockets::sockaddrs dummy;
310                 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
311                 if ((L->IPAddr == "*") || (ipvalid))
312                         ValidIPs.push_back(L->IPAddr);
313                 else
314                 {
315                         try
316                         {
317                                 bool cached = false;
318                                 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
319                                 ServerInstance->AddResolver(sr, cached);
320                         }
321                         catch (...)
322                         {
323                         }
324                 }
325         }
326 }
327
328 void SpanningTreeUtilities::ReadConfiguration()
329 {
330         ConfigReader Conf;
331
332         FlatLinks = Conf.ReadFlag("security","flatlinks",0);
333         HideULines = Conf.ReadFlag("security","hideulines",0);
334         AnnounceTSChange = Conf.ReadFlag("options","announcets",0);
335         AllowOptCommon = Conf.ReadFlag("options", "allowmismatch", 0);
336         ChallengeResponse = !Conf.ReadFlag("security", "disablehmac", 0);
337         quiet_bursts = Conf.ReadFlag("performance", "quietbursts", 0);
338         PingWarnTime = Conf.ReadInteger("options", "pingwarning", 0, true);
339         PingFreq = Conf.ReadInteger("options", "serverpingfreq", 0, true);
340
341         if (PingFreq == 0)
342                 PingFreq = 60;
343
344         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
345                 PingWarnTime = 0;
346
347         AutoconnectBlocks.clear();
348         LinkBlocks.clear();
349         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
350         for(ConfigIter i = tags.first; i != tags.second; ++i)
351         {
352                 ConfigTag* tag = i->second;
353                 reference<Link> L = new Link(tag);
354                 std::string linkname = tag->getString("name");
355                 L->Name = linkname.c_str();
356                 L->AllowMask = tag->getString("allowmask");
357                 L->IPAddr = tag->getString("ipaddr");
358                 L->Port = tag->getInt("port");
359                 L->SendPass = tag->getString("sendpass", tag->getString("password"));
360                 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
361                 L->Fingerprint = tag->getString("fingerprint");
362                 L->HiddenFromStats = tag->getBool("statshidden");
363                 L->Timeout = tag->getInt("timeout", 30);
364                 L->Hook = tag->getString("ssl");
365                 L->Bind = tag->getString("bind");
366                 L->Hidden = tag->getBool("hidden");
367
368                 if (L->Name.empty())
369                         throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
370
371                 if (L->Name.find('.') == std::string::npos)
372                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
373
374                 if (L->Name.length() > 64)
375                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
376
377                 if (L->RecvPass.empty())
378                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
379
380                 if (L->SendPass.empty())
381                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
382
383                 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
384                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
385
386                 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
387                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
388
389                 if (L->IPAddr.empty())
390                 {
391                         L->IPAddr = "*";
392                         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.");
393                 }
394
395                 if (!L->Port)
396                         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.");
397
398                 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
399                 LinkBlocks.push_back(L);
400         }
401
402         tags = ServerInstance->Config->ConfTags("autoconnect");
403         for(ConfigIter i = tags.first; i != tags.second; ++i)
404         {
405                 ConfigTag* tag = i->second;
406                 reference<Autoconnect> A = new Autoconnect(tag);
407                 A->Period = tag->getInt("period");
408                 A->NextConnectTime = ServerInstance->Time() + A->Period;
409                 A->position = -1;
410                 irc::spacesepstream ss(tag->getString("server"));
411                 std::string server;
412                 while (ss.GetToken(server))
413                 {
414                         A->servers.push_back(server);
415                 }
416
417                 if (A->Period <= 0)
418                 {
419                         throw ModuleException("Invalid configuration for autoconnect, period not a positive integer!");
420                 }
421
422                 if (A->servers.empty())
423                 {
424                         throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
425                 }
426
427                 AutoconnectBlocks.push_back(A);
428         }
429
430         RefreshIPCache();
431 }
432
433 Link* SpanningTreeUtilities::FindLink(const std::string& name)
434 {
435         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
436         {
437                 Link* x = *i;
438                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
439                 {
440                         return x;
441                 }
442         }
443         return NULL;
444 }