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