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