]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Fix valgrind issues and crashes on exit
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / utils.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "socket.h"
16 #include "xline.h"
17 #include "../transport.h"
18 #include "socketengine.h"
19
20 #include "main.h"
21 #include "utils.h"
22 #include "treeserver.h"
23 #include "link.h"
24 #include "treesocket.h"
25 #include "resolvers.h"
26
27 /* $ModDep: m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
28
29 /* Create server sockets off a listener. */
30 void ServerSocketListener::OnAcceptReady(int newsock)
31 {
32         bool found = false;
33         int port;
34         std::string incomingip;
35         irc::sockets::satoap(&client, incomingip, port);
36         char *ip = const_cast<char*>(incomingip.c_str());
37
38         found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
39         if (!found)
40         {
41                 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
42                 {
43                         if (*i == "*" || irc::sockets::MatchCIDR(ip, *i))
44                         {
45                                 found = true;
46                                 break;
47                         }
48                 }
49
50                 if (!found)
51                 {
52                         ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", ip);
53                         ServerInstance->SE->Close(newsock);
54                         return;
55                 }
56         }
57
58         /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
59         TreeSocket* ts = new TreeSocket(Utils, newsock, ip, NULL, Hook);
60
61         if (Hook)
62                 Hook->OnStreamSocketAccept(ts, &client, &server);
63
64         return;
65 }
66
67 /** Yay for fast searches!
68  * This is hundreds of times faster than recursion
69  * or even scanning a linked list, especially when
70  * there are more than a few servers to deal with.
71  * (read as: lots).
72  */
73 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
74 {
75         if (ServerInstance->IsSID(ServerName))
76                 return this->FindServerID(ServerName);
77
78         server_hash::iterator iter = serverlist.find(ServerName.c_str());
79         if (iter != serverlist.end())
80         {
81                 return iter->second;
82         }
83         else
84         {
85                 return NULL;
86         }
87 }
88
89 /** Returns the locally connected server we must route a
90  * message through to reach server 'ServerName'. This
91  * only applies to one-to-one and not one-to-many routing.
92  * See the comments for the constructor of TreeServer
93  * for more details.
94  */
95 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
96 {
97         if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
98                 return NULL;
99         TreeServer* Found = FindServer(ServerName);
100         if (Found)
101         {
102                 return Found->GetRoute();
103         }
104         else
105         {
106                 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
107                 User *u = ServerInstance->FindNick(ServerName);
108                 if (u)
109                 {
110                         Found = FindServer(u->server);
111                         if (Found)
112                                 return Found->GetRoute();
113                 }
114
115                 return NULL;
116         }
117 }
118
119 /** Find the first server matching a given glob mask.
120  * Theres no find-using-glob method of hash_map [awwww :-(]
121  * so instead, we iterate over the list using an iterator
122  * and match each one until we get a hit. Yes its slow,
123  * deal with it.
124  */
125 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
126 {
127         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
128         {
129                 if (InspIRCd::Match(i->first,ServerName))
130                         return i->second;
131         }
132         return NULL;
133 }
134
135 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
136 {
137         server_hash::iterator iter = sidlist.find(id);
138         if (iter != sidlist.end())
139                 return iter->second;
140         else
141                 return NULL;
142 }
143
144 /* A convenient wrapper that returns true if a server exists */
145 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
146 {
147         return (FindServer(ServerName) != NULL);
148 }
149
150 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
151 {
152         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
153
154         this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
155         ServerUser = new FakeUser(TreeRoot->GetID());
156
157         this->ReadConfiguration(true);
158 }
159
160 bool SpanningTreeUtilities::cull()
161 {
162         for (unsigned int i = 0; i < Bindings.size(); i++)
163         {
164                 Bindings[i]->cull();
165         }
166
167         while (TreeRoot->ChildCount())
168         {
169                 TreeServer* child_server = TreeRoot->GetChild(0);
170                 if (child_server)
171                 {
172                         TreeSocket* sock = child_server->GetSocket();
173                         sock->Close();
174                         ServerInstance->GlobalCulls.AddItem(sock);
175                 }
176         }
177
178         ServerUser->uuid = TreeRoot->GetID();
179         if (ServerUser->cull())
180                 delete ServerUser;
181         return true;
182 }
183
184 SpanningTreeUtilities::~SpanningTreeUtilities()
185 {
186         for (unsigned int i = 0; i < Bindings.size(); i++)
187         {
188                 delete Bindings[i];
189         }
190
191         delete TreeRoot;
192 }
193
194 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
195 {
196         if (list.find(server) == list.end())
197                 list[server] = server;
198 }
199
200 /* returns a list of DIRECT servernames for a specific channel */
201 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
202 {
203         const UserMembList *ulist = c->GetUsers();
204
205         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
206         {
207                 if (IS_LOCAL(i->first))
208                         continue;
209
210                 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
211                         continue;
212
213                 if (exempt_list.find(i->first) == exempt_list.end())
214                 {
215                         TreeServer* best = this->BestRouteTo(i->first->server);
216                         if (best)
217                                 AddThisServer(best,list);
218                 }
219         }
220         return;
221 }
222
223 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist &params)
224 {
225         TreeServer* omitroute = this->BestRouteTo(omit);
226         unsigned int items =this->TreeRoot->ChildCount();
227         for (unsigned int x = 0; x < items; x++)
228         {
229                 TreeServer* Route = this->TreeRoot->GetChild(x);
230                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
231                 {
232                         TreeSocket* Sock = Route->GetSocket();
233                         if (Sock)
234                                 Sock->WriteLine(data);
235                 }
236         }
237         return true;
238 }
239
240 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist &params, std::string omit)
241 {
242         TreeServer* omitroute = this->BestRouteTo(omit);
243         std::string FullLine = ":" + prefix + " " + command;
244         unsigned int words = params.size();
245         for (unsigned int x = 0; x < words; x++)
246         {
247                 FullLine = FullLine + " " + params[x];
248         }
249         unsigned int items = this->TreeRoot->ChildCount();
250         for (unsigned int x = 0; x < items; x++)
251         {
252                 TreeServer* Route = this->TreeRoot->GetChild(x);
253                 // Send the line IF:
254                 // The route has a socket (its a direct connection)
255                 // The route isnt the one to be omitted
256                 // The route isnt the path to the one to be omitted
257                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
258                 {
259                         TreeSocket* Sock = Route->GetSocket();
260                         if (Sock)
261                                 Sock->WriteLine(FullLine);
262                 }
263         }
264         return true;
265 }
266
267 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist &params)
268 {
269         std::string FullLine = ":" + prefix + " " + command;
270         unsigned int words = params.size();
271         for (unsigned int x = 0; x < words; x++)
272         {
273                 FullLine = FullLine + " " + params[x];
274         }
275         unsigned int items = this->TreeRoot->ChildCount();
276         for (unsigned int x = 0; x < items; x++)
277         {
278                 TreeServer* Route = this->TreeRoot->GetChild(x);
279                 if (Route && Route->GetSocket())
280                 {
281                         TreeSocket* Sock = Route->GetSocket();
282                         if (Sock)
283                                 Sock->WriteLine(FullLine);
284                 }
285         }
286         return true;
287 }
288
289 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist &params)
290 {
291         std::string spfx = prefix;
292         std::string scmd = command;
293         return this->DoOneToMany(spfx, scmd, params);
294 }
295
296 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist &params, std::string omit)
297 {
298         std::string spfx = prefix;
299         std::string scmd = command;
300         return this->DoOneToAllButSender(spfx, scmd, params, omit);
301 }
302
303 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist &params, std::string target)
304 {
305         TreeServer* Route = this->BestRouteTo(target);
306         if (Route)
307         {
308                 std::string FullLine = ":" + prefix + " " + command;
309                 unsigned int words = params.size();
310                 for (unsigned int x = 0; x < words; x++)
311                 {
312                         FullLine = FullLine + " " + params[x];
313                 }
314                 if (Route && Route->GetSocket())
315                 {
316                         TreeSocket* Sock = Route->GetSocket();
317                         if (Sock)
318                                 Sock->WriteLine(FullLine);
319                 }
320                 return true;
321         }
322         else
323         {
324                 return false;
325         }
326 }
327
328 void SpanningTreeUtilities::RefreshIPCache()
329 {
330         ValidIPs.clear();
331         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
332         {
333                 Link* L = *i;
334                 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
335                 {
336                         if (L->Name.empty())
337                         {
338                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
339                         }
340                         else
341                         {
342                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
343                         }
344
345                         /* Invalid link block */
346                         continue;
347                 }
348
349                 ValidIPs.push_back(L->IPAddr);
350
351                 if (L->AllowMask.length())
352                         ValidIPs.push_back(L->AllowMask);
353
354                 /* Needs resolving */
355                 bool ipvalid = true;
356                 QueryType start_type = DNS_QUERY_A;
357                 start_type = DNS_QUERY_AAAA;
358                 if (strchr(L->IPAddr.c_str(),':'))
359                 {
360                         in6_addr n;
361                         if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
362                                 ipvalid = false;
363                 }
364                 else
365                 {
366                         in_addr n;
367                         if (inet_aton(L->IPAddr.c_str(),&n) < 1)
368                                 ipvalid = false;
369                 }
370
371                 if (!ipvalid)
372                 {
373                         try
374                         {
375                                 bool cached;
376                                 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
377                                 ServerInstance->AddResolver(sr, cached);
378                         }
379                         catch (...)
380                         {
381                         }
382                 }
383         }
384 }
385
386 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
387 {
388         ConfigReader* Conf = new ConfigReader;
389
390         /* We don't need to worry about these being *unloaded* on the fly, only loaded,
391          * because we 'use' the interface locking the module in memory.
392          */
393         hooks.clear();
394         hooknames.clear();
395         modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
396
397         /* Did we find any modules? */
398         if (ml)
399         {
400                 /* Yes, enumerate them all to find out the hook name */
401                 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
402                 {
403                         /* Make a request to it for its name, its implementing
404                          * BufferedSocketHook so we know its safe to do this
405                          */
406                         std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
407                         /* Build a map of them */
408                         hooks[name.c_str()] = *m;
409                         hooknames.push_back(name);
410                 }
411         }
412
413         if (rebind)
414         {
415                 for (unsigned int i = 0; i < Bindings.size(); i++)
416                 {
417                         delete Bindings[i];
418                 }
419                 Bindings.clear();
420
421                 for (int j = 0; j < Conf->Enumerate("bind"); j++)
422                 {
423                         std::string Type = Conf->ReadValue("bind","type",j);
424                         std::string IP = Conf->ReadValue("bind","address",j);
425                         std::string Port = Conf->ReadValue("bind","port",j);
426                         std::string transport = Conf->ReadValue("bind","transport",j);
427                         if (Type == "servers")
428                         {
429                                 irc::portparser portrange(Port, false);
430                                 int portno = -1;
431
432                                 if (IP == "*")
433                                         IP.clear();
434
435                                 while ((portno = portrange.GetToken()))
436                                 {
437                                         if ((!transport.empty()) && (hooks.find(transport.c_str()) ==  hooks.end()))
438                                         {
439                                                 throw CoreException("Can't find transport type '"+transport+"' for port "+IP+":"+Port+" - maybe you forgot to load it BEFORE m_spanningtree in your config file?");
440                                                 break;
441                                         }
442
443                                         ServerSocketListener *listener = new ServerSocketListener(this, portno, (char *)IP.c_str());
444                                         if (listener->GetFd() == -1)
445                                         {
446                                                 delete listener;
447                                                 continue;
448                                         }
449
450                                         if (!transport.empty())
451                                                 listener->Hook = hooks[transport.c_str()];
452
453                                         Bindings.push_back(listener);
454                                 }
455                         }
456                 }
457         }
458         FlatLinks = Conf->ReadFlag("security","flatlinks",0);
459         HideULines = Conf->ReadFlag("security","hideulines",0);
460         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
461         AllowOptCommon = Conf->ReadFlag("options", "allowmismatch", 0);
462         ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
463         quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
464         PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
465         PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
466
467         if (PingFreq == 0)
468                 PingFreq = 60;
469
470         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
471                 PingWarnTime = 0;
472
473         AutoconnectBlocks.clear();
474         LinkBlocks.clear();
475         ValidIPs.clear();
476         for (int j = 0; j < Conf->Enumerate("link"); ++j)
477         {
478                 reference<Link> L = new Link;
479                 std::string Allow = Conf->ReadValue("link", "allowmask", j);
480                 L->Name = (Conf->ReadValue("link", "name", j)).c_str();
481                 L->AllowMask = Allow;
482                 L->IPAddr = Conf->ReadValue("link", "ipaddr", j);
483                 L->Port = Conf->ReadInteger("link", "port", j, true);
484                 L->SendPass = Conf->ReadValue("link", "sendpass", j);
485                 L->RecvPass = Conf->ReadValue("link", "recvpass", j);
486                 L->Fingerprint = Conf->ReadValue("link", "fingerprint", j);
487                 L->HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
488                 L->Timeout = Conf->ReadInteger("link", "timeout", j, true);
489                 L->Hook = Conf->ReadValue("link", "transport", j);
490                 L->Bind = Conf->ReadValue("link", "bind", j);
491                 L->Hidden = Conf->ReadFlag("link", "hidden", j);
492
493                 if ((!L->Hook.empty()) && (hooks.find(L->Hook.c_str()) ==  hooks.end()))
494                 {
495                         throw CoreException("Can't find transport type '"+L->Hook+"' for link '"+assign(L->Name)+"' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping <link> tag completely.");
496                         continue;
497
498                 }
499
500                 if (L->Name.find('.') == std::string::npos)
501                         throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
502
503                 if (L->Name.length() > 64)
504                         throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
505
506                 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
507                 {
508                         if (Allow.length())
509                                 ValidIPs.push_back(Allow);
510
511                         ValidIPs.push_back(L->IPAddr);
512
513                         /* Needs resolving */
514                         bool ipvalid = true;
515                         QueryType start_type = DNS_QUERY_A;
516                         start_type = DNS_QUERY_AAAA;
517                         if (strchr(L->IPAddr.c_str(),':'))
518                         {
519                                 in6_addr n;
520                                 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
521                                         ipvalid = false;
522                         }
523                         else
524                         {
525                                 in_addr n;
526                                 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
527                                         ipvalid = false;
528                         }
529
530                         if (!ipvalid)
531                         {
532                                 try
533                                 {
534                                         bool cached;
535                                         SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
536                                         ServerInstance->AddResolver(sr, cached);
537                                 }
538                                 catch (...)
539                                 {
540                                 }
541                         }
542                 }
543                 else
544                 {
545                         if (L->IPAddr.empty())
546                         {
547                                 L->IPAddr = "*";
548                                 ValidIPs.push_back("*");
549                                 ServerInstance->Logs->Log("m_spanningtree",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.");
550                         }
551
552                         if (L->RecvPass.empty())
553                         {
554                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
555                         }
556
557                         if (L->SendPass.empty())
558                         {
559                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
560                         }
561
562                         if (L->Name.empty())
563                         {
564                                 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
565                         }
566
567                         if (!L->Port)
568                         {
569                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block " + assign(L->Name) + " has no port defined, you will not be able to /connect it.");
570                         }
571                 }
572
573                 LinkBlocks.push_back(L);
574         }
575
576         for (int j = 0; j < Conf->Enumerate("autoconnect"); ++j)
577         {
578                 reference<Autoconnect> A = new Autoconnect;
579                 A->Period = Conf->ReadInteger("autoconnect", "period", j, true);
580                 A->NextConnectTime = ServerInstance->Time() + A->Period;
581                 A->position = -1;
582                 std::string servers = Conf->ReadValue("autoconnect", "server", j);
583                 irc::spacesepstream ss(servers);
584                 std::string server;
585                 while (ss.GetToken(server))
586                 {
587                         A->servers.push_back(server);
588                 }
589
590                 if (A->Period <= 0)
591                 {
592                         throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
593                 }
594
595                 if (A->servers.empty())
596                 {
597                         throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
598                 }
599
600                 AutoconnectBlocks.push_back(A);
601         }
602
603         delete Conf;
604 }
605
606 Link* SpanningTreeUtilities::FindLink(const std::string& name)
607 {
608         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
609         {
610                 Link* x = *i;
611                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
612                 {
613                         return x;
614                 }
615         }
616         return NULL;
617 }