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