]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
m_spanningtree Add TreeServer::GetChildren() that replaces ChildCount() and GetChild()
[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 SpanningTreeUtilities* Utils = NULL;
32
33 /* Create server sockets off a listener. */
34 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
35 {
36         if (from->bind_tag->getString("type") != "servers")
37                 return MOD_RES_PASSTHRU;
38
39         std::string incomingip = client->addr();
40
41         for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
42         {
43                 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
44                 {
45                         /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
46                         new TreeSocket(newsock, from, client, server);
47                         return MOD_RES_ALLOW;
48                 }
49         }
50         ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
51         return MOD_RES_DENY;
52 }
53
54 /** Yay for fast searches!
55  * This is hundreds of times faster than recursion
56  * or even scanning a linked list, especially when
57  * there are more than a few servers to deal with.
58  * (read as: lots).
59  */
60 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
61 {
62         if (InspIRCd::IsSID(ServerName))
63                 return this->FindServerID(ServerName);
64
65         server_hash::iterator iter = serverlist.find(ServerName);
66         if (iter != serverlist.end())
67         {
68                 return iter->second;
69         }
70         else
71         {
72                 return NULL;
73         }
74 }
75
76 /** Returns the locally connected server we must route a
77  * message through to reach server 'ServerName'. This
78  * only applies to one-to-one and not one-to-many routing.
79  * See the comments for the constructor of TreeServer
80  * for more details.
81  */
82 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
83 {
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         : Creator(C), TreeRoot(NULL)
131 {
132         ServerInstance->Timers->AddTimer(&RefreshTimer);
133
134         this->ReadConfiguration();
135 }
136
137 CullResult SpanningTreeUtilities::cull()
138 {
139         const TreeServer::ChildServers& children = TreeRoot->GetChildren();
140         while (!children.empty())
141         {
142                 TreeSocket* sock = children.front()->GetSocket();
143                 sock->Close();
144         }
145
146         for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
147         {
148                 TreeSocket* s = i->first;
149                 s->Close();
150         }
151         TreeRoot->cull();
152
153         return classbase::cull();
154 }
155
156 SpanningTreeUtilities::~SpanningTreeUtilities()
157 {
158         delete TreeRoot;
159 }
160
161 /* returns a list of DIRECT servernames for a specific channel */
162 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
163 {
164         unsigned int minrank = 0;
165         if (status)
166         {
167                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
168                 if (mh)
169                         minrank = mh->GetPrefixRank();
170         }
171
172         const UserMembList *ulist = c->GetUsers();
173
174         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
175         {
176                 if (IS_LOCAL(i->first))
177                         continue;
178
179                 if (minrank && i->second->getRank() < minrank)
180                         continue;
181
182                 if (exempt_list.find(i->first) == exempt_list.end())
183                 {
184                         TreeServer* best = this->BestRouteTo(i->first->server);
185                         if (best)
186                                 list.insert(best->GetSocket());
187                 }
188         }
189         return;
190 }
191
192 std::string SpanningTreeUtilities::ConstructLine(const std::string& prefix, const std::string& command, const parameterlist& params)
193 {
194         std::string FullLine;
195         FullLine.reserve(1024);
196         FullLine = ":" + prefix + " " + command;
197         for (parameterlist::const_iterator x = params.begin(); x != params.end(); ++x)
198         {
199                 FullLine.push_back(' ');
200                 FullLine.append(*x);
201         }
202         return FullLine;
203 }
204
205 void SpanningTreeUtilities::DoOneToAllButSender(const std::string& prefix, const std::string& command, const parameterlist& params, TreeServer* omitroute)
206 {
207         std::string FullLine = ConstructLine(prefix, command, params);
208
209         const TreeServer::ChildServers& children = TreeRoot->GetChildren();
210         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
211         {
212                 TreeServer* Route = *i;
213                 // Send the line if the route isn't the path to the one to be omitted
214                 if (Route != omitroute)
215                 {
216                         Route->GetSocket()->WriteLine(FullLine);
217                 }
218         }
219 }
220
221 bool SpanningTreeUtilities::DoOneToOne(const std::string& prefix, const std::string& command, const parameterlist& params, const std::string& target)
222 {
223         TreeServer* Route = this->BestRouteTo(target);
224         if (!Route)
225                 return false;
226
227         Route->GetSocket()->WriteLine(ConstructLine(prefix, command, params));
228         return true;
229 }
230
231 void SpanningTreeUtilities::RefreshIPCache()
232 {
233         ValidIPs.clear();
234         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
235         {
236                 Link* L = *i;
237                 if (!L->Port)
238                 {
239                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
240                         /* Invalid link block */
241                         continue;
242                 }
243
244                 if (L->AllowMask.length())
245                         ValidIPs.push_back(L->AllowMask);
246
247                 irc::sockets::sockaddrs dummy;
248                 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
249                 if ((L->IPAddr == "*") || (ipvalid))
250                         ValidIPs.push_back(L->IPAddr);
251                 else if (this->Creator->DNS)
252                 {
253                         SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
254                         try
255                         {
256                                 this->Creator->DNS->Process(sr);
257                         }
258                         catch (DNS::Exception &)
259                         {
260                                 delete sr;
261                         }
262                 }
263         }
264 }
265
266 void SpanningTreeUtilities::ReadConfiguration()
267 {
268         ConfigTag* security = ServerInstance->Config->ConfValue("security");
269         ConfigTag* options = ServerInstance->Config->ConfValue("options");
270         FlatLinks = security->getBool("flatlinks");
271         HideULines = security->getBool("hideulines");
272         AnnounceTSChange = options->getBool("announcets");
273         AllowOptCommon = options->getBool("allowmismatch");
274         ChallengeResponse = !security->getBool("disablehmac");
275         quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
276         PingWarnTime = options->getInt("pingwarning");
277         PingFreq = options->getInt("serverpingfreq");
278
279         if (PingFreq == 0)
280                 PingFreq = 60;
281
282         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
283                 PingWarnTime = 0;
284
285         AutoconnectBlocks.clear();
286         LinkBlocks.clear();
287         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
288         for(ConfigIter i = tags.first; i != tags.second; ++i)
289         {
290                 ConfigTag* tag = i->second;
291                 reference<Link> L = new Link(tag);
292                 std::string linkname = tag->getString("name");
293                 L->Name = linkname.c_str();
294                 L->AllowMask = tag->getString("allowmask");
295                 L->IPAddr = tag->getString("ipaddr");
296                 L->Port = tag->getInt("port");
297                 L->SendPass = tag->getString("sendpass", tag->getString("password"));
298                 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
299                 L->Fingerprint = tag->getString("fingerprint");
300                 L->HiddenFromStats = tag->getBool("statshidden");
301                 L->Timeout = tag->getDuration("timeout", 30);
302                 L->Hook = tag->getString("ssl");
303                 L->Bind = tag->getString("bind");
304                 L->Hidden = tag->getBool("hidden");
305
306                 if (L->Name.empty())
307                         throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
308
309                 if (L->Name.find('.') == std::string::npos)
310                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
311
312                 if (L->Name.length() > 64)
313                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
314
315                 if (L->RecvPass.empty())
316                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
317
318                 if (L->SendPass.empty())
319                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
320
321                 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
322                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
323
324                 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
325                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
326
327                 if (L->IPAddr.empty())
328                 {
329                         L->IPAddr = "*";
330                         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.");
331                 }
332
333                 if (!L->Port)
334                         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.");
335
336                 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
337                 LinkBlocks.push_back(L);
338         }
339
340         tags = ServerInstance->Config->ConfTags("autoconnect");
341         for(ConfigIter i = tags.first; i != tags.second; ++i)
342         {
343                 ConfigTag* tag = i->second;
344                 reference<Autoconnect> A = new Autoconnect(tag);
345                 A->Period = tag->getDuration("period", 60, 1);
346                 A->NextConnectTime = ServerInstance->Time() + A->Period;
347                 A->position = -1;
348                 irc::spacesepstream ss(tag->getString("server"));
349                 std::string server;
350                 while (ss.GetToken(server))
351                 {
352                         A->servers.push_back(server);
353                 }
354
355                 if (A->servers.empty())
356                 {
357                         throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
358                 }
359
360                 AutoconnectBlocks.push_back(A);
361         }
362
363         RefreshIPCache();
364 }
365
366 Link* SpanningTreeUtilities::FindLink(const std::string& name)
367 {
368         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
369         {
370                 Link* x = *i;
371                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
372                 {
373                         return x;
374                 }
375         }
376         return NULL;
377 }
378
379 void SpanningTreeUtilities::SendChannelMessage(const std::string& prefix, Channel* target, const std::string& text, char status, const CUList& exempt_list, const char* message_type, TreeSocket* omit)
380 {
381         std::string raw(":");
382         raw.append(prefix).append(1, ' ').append(message_type).push_back(' ');
383         if (status)
384                 raw.push_back(status);
385         raw.append(target->name).append(" :").append(text);
386
387         TreeSocketSet list;
388         this->GetListOfServersForChannel(target, list, status, exempt_list);
389         for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
390         {
391                 TreeSocket* Sock = *i;
392                 if (Sock != omit)
393                         Sock->WriteLine(raw);
394         }
395 }