]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Lower the acceptable drift for clocks on link.
[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 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
35 {
36         if (!stdalgo::string::equalsci(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 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
55 {
56         if (InspIRCd::IsSID(ServerName))
57                 return this->FindServerID(ServerName);
58
59         server_hash::iterator iter = serverlist.find(ServerName);
60         if (iter != serverlist.end())
61         {
62                 return iter->second;
63         }
64         else
65         {
66                 return NULL;
67         }
68 }
69
70 /** Find the first server matching a given glob mask.
71  * We iterate over the list and match each one until we get a hit.
72  */
73 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
74 {
75         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
76         {
77                 if (InspIRCd::Match(i->first,ServerName))
78                         return i->second;
79         }
80         return NULL;
81 }
82
83 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
84 {
85         server_hash::iterator iter = sidlist.find(id);
86         if (iter != sidlist.end())
87                 return iter->second;
88         else
89                 return NULL;
90 }
91
92 TreeServer* SpanningTreeUtilities::FindRouteTarget(const std::string& target)
93 {
94         TreeServer* const server = FindServer(target);
95         if (server)
96                 return server;
97
98         User* const user = ServerInstance->FindNick(target);
99         if (user)
100                 return TreeServer::Get(user);
101
102         return NULL;
103 }
104
105 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
106         : Creator(C), TreeRoot(NULL)
107         , PingFreq(60) // XXX: TreeServer constructor reads this and TreeRoot is created before the config is read, so init it to something (value doesn't matter) to avoid a valgrind warning in TimerManager on unload
108 {
109         ServerInstance->Timers.AddTimer(&RefreshTimer);
110 }
111
112 CullResult SpanningTreeUtilities::cull()
113 {
114         const TreeServer::ChildServers& children = TreeRoot->GetChildren();
115         while (!children.empty())
116         {
117                 TreeSocket* sock = children.front()->GetSocket();
118                 sock->Close();
119         }
120
121         for(TimeoutList::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
122         {
123                 TreeSocket* s = i->first;
124                 s->Close();
125         }
126         TreeRoot->cull();
127
128         return classbase::cull();
129 }
130
131 SpanningTreeUtilities::~SpanningTreeUtilities()
132 {
133         delete TreeRoot;
134 }
135
136 // Returns a list of DIRECT servers for a specific channel
137 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
138 {
139         unsigned int minrank = 0;
140         if (status)
141         {
142                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
143                 if (mh)
144                         minrank = mh->GetPrefixRank();
145         }
146
147         TreeServer::ChildServers children = TreeRoot->GetChildren();
148         const Channel::MemberMap& ulist = c->GetUsers();
149         for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
150         {
151                 if (IS_LOCAL(i->first))
152                         continue;
153
154                 if (minrank && i->second->getRank() < minrank)
155                         continue;
156
157                 if (exempt_list.find(i->first) == exempt_list.end())
158                 {
159                         TreeServer* best = TreeServer::Get(i->first);
160                         list.insert(best->GetSocket());
161
162                         TreeServer::ChildServers::iterator citer = std::find(children.begin(), children.end(), best);
163                         if (citer != children.end())
164                                 children.erase(citer);
165                 }
166         }
167
168         // Check whether the servers which do not have users in the channel might need this message. This
169         // is used to keep the chanhistory module synchronised between servers.
170         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
171         {
172                 ModResult result;
173                 FIRST_MOD_RESULT_CUSTOM(Creator->GetBroadcastEventProvider(), ServerProtocol::BroadcastEventListener, OnBroadcastMessage, result, (c, *i));
174                 if (result == MOD_RES_ALLOW)
175                         list.insert((*i)->GetSocket());
176         }
177 }
178
179 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
180 {
181         const std::string& FullLine = params.str();
182
183         const TreeServer::ChildServers& children = TreeRoot->GetChildren();
184         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
185         {
186                 TreeServer* Route = *i;
187                 // Send the line if the route isn't the path to the one to be omitted
188                 if (Route != omitroute)
189                 {
190                         Route->GetSocket()->WriteLine(FullLine);
191                 }
192         }
193 }
194
195 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
196 {
197         TreeServer* ts = static_cast<TreeServer*>(server);
198         TreeSocket* sock = ts->GetSocket();
199         if (sock)
200                 sock->WriteLine(params);
201 }
202
203 void SpanningTreeUtilities::RefreshIPCache()
204 {
205         ValidIPs.clear();
206         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
207         {
208                 Link* L = *i;
209                 if (!L->Port)
210                 {
211                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
212                         /* Invalid link block */
213                         continue;
214                 }
215
216                 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
217
218                 irc::sockets::sockaddrs dummy;
219                 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
220                 if ((L->IPAddr == "*") || (ipvalid))
221                         ValidIPs.push_back(L->IPAddr);
222                 else if (this->Creator->DNS)
223                 {
224                         SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
225                         try
226                         {
227                                 this->Creator->DNS->Process(sr);
228                         }
229                         catch (DNS::Exception &)
230                         {
231                                 delete sr;
232                         }
233                 }
234         }
235 }
236
237 void SpanningTreeUtilities::ReadConfiguration()
238 {
239         ConfigTag* security = ServerInstance->Config->ConfValue("security");
240         ConfigTag* options = ServerInstance->Config->ConfValue("options");
241         FlatLinks = security->getBool("flatlinks");
242         HideULines = security->getBool("hideulines");
243         HideSplits = security->getBool("hidesplits");
244         AnnounceTSChange = options->getBool("announcets");
245         AllowOptCommon = options->getBool("allowmismatch");
246         quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
247         PingWarnTime = options->getDuration("pingwarning", 15);
248         PingFreq = options->getDuration("serverpingfreq", 60, 1);
249
250         if (PingWarnTime >= PingFreq)
251                 PingWarnTime = 0;
252
253         AutoconnectBlocks.clear();
254         LinkBlocks.clear();
255         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
256         for(ConfigIter i = tags.first; i != tags.second; ++i)
257         {
258                 ConfigTag* tag = i->second;
259                 reference<Link> L = new Link(tag);
260
261                 irc::spacesepstream sep = tag->getString("allowmask");
262                 for (std::string s; sep.GetToken(s);)
263                         L->AllowMasks.push_back(s);
264
265                 L->Name = tag->getString("name");
266                 L->IPAddr = tag->getString("ipaddr");
267                 L->Port = tag->getUInt("port", 0);
268                 L->SendPass = tag->getString("sendpass", tag->getString("password"));
269                 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
270                 L->Fingerprint = tag->getString("fingerprint");
271                 L->HiddenFromStats = tag->getBool("statshidden");
272                 L->Timeout = tag->getDuration("timeout", 30);
273                 L->Hook = tag->getString("ssl");
274                 L->Bind = tag->getString("bind");
275                 L->Hidden = tag->getBool("hidden");
276
277                 if (L->Name.empty())
278                         throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
279
280                 if (L->Name.find('.') == std::string::npos)
281                         throw ModuleException("The link name '"+L->Name+"' is invalid as it must contain at least one '.' character");
282
283                 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
284                         throw ModuleException("The link name '"+L->Name+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
285
286                 if (L->RecvPass.empty())
287                         throw ModuleException("Invalid configuration for server '"+L->Name+"', recvpass not defined");
288
289                 if (L->SendPass.empty())
290                         throw ModuleException("Invalid configuration for server '"+L->Name+"', sendpass not defined");
291
292                 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
293                         throw ModuleException("Link block '" + L->Name + "' has a password set that contains a space character which is invalid");
294
295                 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
296                         throw ModuleException("Link block '" + L->Name + "' has a password set that begins with a colon (:) which is invalid");
297
298                 if (L->IPAddr.empty())
299                 {
300                         L->IPAddr = "*";
301                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want.");
302                 }
303
304                 if (!L->Port && L->IPAddr.find('/') == std::string::npos)
305                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no port defined, you will not be able to /connect it.");
306
307                 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
308                 LinkBlocks.push_back(L);
309         }
310
311         tags = ServerInstance->Config->ConfTags("autoconnect");
312         for(ConfigIter i = tags.first; i != tags.second; ++i)
313         {
314                 ConfigTag* tag = i->second;
315                 reference<Autoconnect> A = new Autoconnect(tag);
316                 A->Period = tag->getDuration("period", 60, 1);
317                 A->NextConnectTime = ServerInstance->Time() + A->Period;
318                 A->position = -1;
319                 irc::spacesepstream ss(tag->getString("server"));
320                 std::string server;
321                 while (ss.GetToken(server))
322                 {
323                         A->servers.push_back(server);
324                 }
325
326                 if (A->servers.empty())
327                 {
328                         throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
329                 }
330
331                 AutoconnectBlocks.push_back(A);
332         }
333
334         for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
335                 i->second->CheckULine();
336
337         RefreshIPCache();
338 }
339
340 Link* SpanningTreeUtilities::FindLink(const std::string& name)
341 {
342         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
343         {
344                 Link* x = *i;
345                 if (InspIRCd::Match(x->Name, name, ascii_case_insensitive_map))
346                 {
347                         return x;
348                 }
349         }
350         return NULL;
351 }
352
353 void SpanningTreeUtilities::SendChannelMessage(User* source, Channel* target, const std::string& text, char status, const ClientProtocol::TagMap& tags, const CUList& exempt_list, const char* message_type, TreeSocket* omit)
354 {
355         CmdBuilder msg(source, message_type);
356         msg.push_tags(tags);
357         msg.push_raw(' ');
358         if (status != 0)
359                 msg.push_raw(status);
360         msg.push_raw(target->name);
361         if (!text.empty())
362                 msg.push_last(text);
363
364         TreeSocketSet list;
365         this->GetListOfServersForChannel(target, list, status, exempt_list);
366         for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
367         {
368                 TreeSocket* Sock = *i;
369                 if (Sock != omit)
370                         Sock->WriteLine(msg);
371         }
372 }