]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Merge pull request #590 from SaberUK/master+module-logging
[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
25 #include "main.h"
26 #include "utils.h"
27 #include "treeserver.h"
28 #include "treesocket.h"
29 #include "resolvers.h"
30
31 /* Create server sockets off a listener. */
32 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
33 {
34         if (from->bind_tag->getString("type") != "servers")
35                 return MOD_RES_PASSTHRU;
36
37         std::string incomingip = client->addr();
38
39         for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
40         {
41                 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
42                 {
43                         /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
44                         new TreeSocket(Utils, newsock, from, client, server);
45                         return MOD_RES_ALLOW;
46                 }
47         }
48         ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
49         return MOD_RES_DENY;
50 }
51
52 /** Yay for fast searches!
53  * This is hundreds of times faster than recursion
54  * or even scanning a linked list, especially when
55  * there are more than a few servers to deal with.
56  * (read as: lots).
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 /** Returns the locally connected server we must route a
75  * message through to reach server 'ServerName'. This
76  * only applies to one-to-one and not one-to-many routing.
77  * See the comments for the constructor of TreeServer
78  * for more details.
79  */
80 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
81 {
82         if (ServerName == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
83                 return NULL;
84         TreeServer* Found = FindServer(ServerName);
85         if (Found)
86         {
87                 return Found->GetRoute();
88         }
89         else
90         {
91                 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
92                 User *u = ServerInstance->FindNick(ServerName);
93                 if (u)
94                 {
95                         Found = FindServer(u->server);
96                         if (Found)
97                                 return Found->GetRoute();
98                 }
99
100                 return NULL;
101         }
102 }
103
104 /** Find the first server matching a given glob mask.
105  * Theres no find-using-glob method of hash_map [awwww :-(]
106  * so instead, we iterate over the list using an iterator
107  * and match each one until we get a hit. Yes its slow,
108  * deal with it.
109  */
110 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
111 {
112         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
113         {
114                 if (InspIRCd::Match(i->first,ServerName))
115                         return i->second;
116         }
117         return NULL;
118 }
119
120 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
121 {
122         server_hash::iterator iter = sidlist.find(id);
123         if (iter != sidlist.end())
124                 return iter->second;
125         else
126                 return NULL;
127 }
128
129 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
130         : RefreshTimer(this), Creator(C)
131 {
132         ServerInstance->Timers->AddTimer(&RefreshTimer);
133
134         this->TreeRoot = new TreeServer(this);
135         this->ReadConfiguration();
136 }
137
138 CullResult SpanningTreeUtilities::cull()
139 {
140         while (TreeRoot->ChildCount())
141         {
142                 TreeServer* child_server = TreeRoot->GetChild(0);
143                 if (child_server)
144                 {
145                         TreeSocket* sock = child_server->GetSocket();
146                         sock->Close();
147                 }
148         }
149
150         for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
151         {
152                 TreeSocket* s = i->first;
153                 s->Close();
154         }
155         TreeRoot->cull();
156
157         return classbase::cull();
158 }
159
160 SpanningTreeUtilities::~SpanningTreeUtilities()
161 {
162         delete TreeRoot;
163 }
164
165 /* returns a list of DIRECT servernames for a specific channel */
166 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
167 {
168         unsigned int minrank = 0;
169         if (status)
170         {
171                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
172                 if (mh)
173                         minrank = mh->GetPrefixRank();
174         }
175
176         const UserMembList *ulist = c->GetUsers();
177
178         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
179         {
180                 if (IS_LOCAL(i->first))
181                         continue;
182
183                 if (minrank && i->second->getRank() < minrank)
184                         continue;
185
186                 if (exempt_list.find(i->first) == exempt_list.end())
187                 {
188                         TreeServer* best = this->BestRouteTo(i->first->server);
189                         if (best)
190                                 list.insert(best);
191                 }
192         }
193         return;
194 }
195
196 std::string SpanningTreeUtilities::ConstructLine(const std::string& prefix, const std::string& command, const parameterlist& params)
197 {
198         std::string FullLine;
199         FullLine.reserve(1024);
200         FullLine = ":" + prefix + " " + command;
201         for (parameterlist::const_iterator x = params.begin(); x != params.end(); ++x)
202         {
203                 FullLine.push_back(' ');
204                 FullLine.append(*x);
205         }
206         return FullLine;
207 }
208
209 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string& prefix, const std::string& command, const parameterlist& params, const std::string& omit)
210 {
211         TreeServer* omitroute = this->BestRouteTo(omit);
212         std::string FullLine = ConstructLine(prefix, command, params);
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 = ConstructLine(prefix, command, params);
235
236         unsigned int items = this->TreeRoot->ChildCount();
237         for (unsigned int x = 0; x < items; x++)
238         {
239                 TreeServer* Route = this->TreeRoot->GetChild(x);
240                 if (Route && Route->GetSocket())
241                 {
242                         TreeSocket* Sock = Route->GetSocket();
243                         if (Sock)
244                                 Sock->WriteLine(FullLine);
245                 }
246         }
247         return true;
248 }
249
250 bool SpanningTreeUtilities::DoOneToOne(const std::string& prefix, const std::string& command, const parameterlist& params, const std::string& target)
251 {
252         TreeServer* Route = this->BestRouteTo(target);
253         if (Route)
254         {
255                 if (Route && Route->GetSocket())
256                 {
257                         TreeSocket* Sock = Route->GetSocket();
258                         if (Sock)
259                                 Sock->WriteLine(ConstructLine(prefix, command, params));
260                 }
261                 return true;
262         }
263         else
264         {
265                 return false;
266         }
267 }
268
269 void SpanningTreeUtilities::RefreshIPCache()
270 {
271         ValidIPs.clear();
272         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
273         {
274                 Link* L = *i;
275                 if (!L->Port)
276                 {
277                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
278                         /* Invalid link block */
279                         continue;
280                 }
281
282                 if (L->AllowMask.length())
283                         ValidIPs.push_back(L->AllowMask);
284
285                 irc::sockets::sockaddrs dummy;
286                 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
287                 if ((L->IPAddr == "*") || (ipvalid))
288                         ValidIPs.push_back(L->IPAddr);
289                 else if (this->Creator->DNS)
290                 {
291                         SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
292                         try
293                         {
294                                 this->Creator->DNS->Process(sr);
295                         }
296                         catch (DNS::Exception &)
297                         {
298                                 delete sr;
299                         }
300                 }
301         }
302 }
303
304 void SpanningTreeUtilities::ReadConfiguration()
305 {
306         ConfigTag* security = ServerInstance->Config->ConfValue("security");
307         ConfigTag* options = ServerInstance->Config->ConfValue("options");
308         FlatLinks = security->getBool("flatlinks");
309         HideULines = security->getBool("hideulines");
310         AnnounceTSChange = options->getBool("announcets");
311         AllowOptCommon = options->getBool("allowmismatch");
312         ChallengeResponse = !security->getBool("disablehmac");
313         quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
314         PingWarnTime = options->getInt("pingwarning");
315         PingFreq = options->getInt("serverpingfreq");
316
317         if (PingFreq == 0)
318                 PingFreq = 60;
319
320         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
321                 PingWarnTime = 0;
322
323         AutoconnectBlocks.clear();
324         LinkBlocks.clear();
325         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
326         for(ConfigIter i = tags.first; i != tags.second; ++i)
327         {
328                 ConfigTag* tag = i->second;
329                 reference<Link> L = new Link(tag);
330                 std::string linkname = tag->getString("name");
331                 L->Name = linkname.c_str();
332                 L->AllowMask = tag->getString("allowmask");
333                 L->IPAddr = tag->getString("ipaddr");
334                 L->Port = tag->getInt("port");
335                 L->SendPass = tag->getString("sendpass", tag->getString("password"));
336                 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
337                 L->Fingerprint = tag->getString("fingerprint");
338                 L->HiddenFromStats = tag->getBool("statshidden");
339                 L->Timeout = tag->getInt("timeout", 30);
340                 L->Hook = tag->getString("ssl");
341                 L->Bind = tag->getString("bind");
342                 L->Hidden = tag->getBool("hidden");
343
344                 if (L->Name.empty())
345                         throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
346
347                 if (L->Name.find('.') == std::string::npos)
348                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
349
350                 if (L->Name.length() > 64)
351                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
352
353                 if (L->RecvPass.empty())
354                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
355
356                 if (L->SendPass.empty())
357                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
358
359                 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
360                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
361
362                 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
363                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
364
365                 if (L->IPAddr.empty())
366                 {
367                         L->IPAddr = "*";
368                         ServerInstance->Logs->Log(MODNAME, LOG_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.");
369                 }
370
371                 if (!L->Port)
372                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + assign(L->Name) + "' has no port defined, you will not be able to /connect it.");
373
374                 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
375                 LinkBlocks.push_back(L);
376         }
377
378         tags = ServerInstance->Config->ConfTags("autoconnect");
379         for(ConfigIter i = tags.first; i != tags.second; ++i)
380         {
381                 ConfigTag* tag = i->second;
382                 reference<Autoconnect> A = new Autoconnect(tag);
383                 A->Period = tag->getInt("period");
384                 A->NextConnectTime = ServerInstance->Time() + A->Period;
385                 A->position = -1;
386                 irc::spacesepstream ss(tag->getString("server"));
387                 std::string server;
388                 while (ss.GetToken(server))
389                 {
390                         A->servers.push_back(server);
391                 }
392
393                 if (A->Period <= 0)
394                 {
395                         throw ModuleException("Invalid configuration for autoconnect, period not a positive integer!");
396                 }
397
398                 if (A->servers.empty())
399                 {
400                         throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
401                 }
402
403                 AutoconnectBlocks.push_back(A);
404         }
405
406         RefreshIPCache();
407 }
408
409 Link* SpanningTreeUtilities::FindLink(const std::string& name)
410 {
411         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
412         {
413                 Link* x = *i;
414                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
415                 {
416                         return x;
417                 }
418         }
419         return NULL;
420 }
421
422 void SpanningTreeUtilities::SendChannelMessage(const std::string& prefix, Channel* target, const std::string &text, char status, const CUList& exempt_list, const char* message_type)
423 {
424         std::string raw(":");
425         raw.append(prefix).append(1, ' ').append(message_type).push_back(' ');
426         if (status)
427                 raw.push_back(status);
428         raw.append(target->name).append(" :").append(text);
429
430         TreeServerList list;
431         this->GetListOfServersForChannel(target, list, status, exempt_list);
432         for (TreeServerList::iterator i = list.begin(); i != list.end(); ++i)
433         {
434                 TreeSocket* Sock = (*i)->GetSocket();
435                 if (Sock)
436                         Sock->WriteLine(raw);
437         }
438 }