]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
5862d95e7a7faa870eb408f595634737e8701910
[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                 }
175         }
176
177         ServerUser->uuid = TreeRoot->GetID();
178         if (ServerUser->cull())
179                 delete ServerUser;
180         return true;
181 }
182
183 SpanningTreeUtilities::~SpanningTreeUtilities()
184 {
185         for (unsigned int i = 0; i < Bindings.size(); i++)
186         {
187                 delete Bindings[i];
188         }
189
190         delete TreeRoot;
191 }
192
193 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
194 {
195         if (list.find(server) == list.end())
196                 list[server] = server;
197 }
198
199 /* returns a list of DIRECT servernames for a specific channel */
200 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
201 {
202         const UserMembList *ulist = c->GetUsers();
203
204         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
205         {
206                 if (IS_LOCAL(i->first))
207                         continue;
208
209                 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
210                         continue;
211
212                 if (exempt_list.find(i->first) == exempt_list.end())
213                 {
214                         TreeServer* best = this->BestRouteTo(i->first->server);
215                         if (best)
216                                 AddThisServer(best,list);
217                 }
218         }
219         return;
220 }
221
222 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist &params)
223 {
224         char pfx = 0;
225         TreeServer* omitroute = this->BestRouteTo(omit);
226         if ((command == "NOTICE") || (command == "PRIVMSG"))
227         {
228                 if (params.size() >= 2)
229                 {
230                         /* Prefixes */
231                         if (ServerInstance->Modes->FindPrefix(params[0][0]))
232                         {
233                                 pfx = params[0][0];
234                                 params[0] = params[0].substr(1, params[0].length()-1);
235                         }
236                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
237                         {
238                                 // special routing for private messages/notices
239                                 User* d = ServerInstance->FindNick(params[0]);
240                                 if (d)
241                                 {
242                                         parameterlist par;
243                                         par.push_back(params[0]);
244                                         par.push_back(":"+params[1]);
245                                         this->DoOneToOne(prefix,command.c_str(),par,d->server);
246                                         return true;
247                                 }
248                         }
249                         else if (*(params[0].c_str()) == '$')
250                         {
251                                 parameterlist par;
252                                 par.push_back(params[0]);
253                                 par.push_back(":"+params[1]);
254                                 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
255                                 return true;
256                         }
257                         else
258                         {
259                                 Channel* c = ServerInstance->FindChan(params[0]);
260                                 User* u = ServerInstance->FindNick(prefix);
261                                 if (c)
262                                 {
263                                         CUList elist;
264                                         TreeServerList list;
265                                         FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
266                                         GetListOfServersForChannel(c,list,pfx,elist);
267
268                                         for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
269                                         {
270                                                 TreeSocket* Sock = i->second->GetSocket();
271                                                 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
272                                                 {
273                                                         Sock->WriteLine(data);
274                                                 }
275                                         }
276                                         return true;
277                                 }
278                         }
279                 }
280         }
281         unsigned int items =this->TreeRoot->ChildCount();
282         for (unsigned int x = 0; x < items; x++)
283         {
284                 TreeServer* Route = this->TreeRoot->GetChild(x);
285                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
286                 {
287                         TreeSocket* Sock = Route->GetSocket();
288                         if (Sock)
289                                 Sock->WriteLine(data);
290                 }
291         }
292         return true;
293 }
294
295 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist &params, std::string omit)
296 {
297         TreeServer* omitroute = this->BestRouteTo(omit);
298         std::string FullLine = ":" + prefix + " " + command;
299         unsigned int words = params.size();
300         for (unsigned int x = 0; x < words; x++)
301         {
302                 FullLine = FullLine + " " + params[x];
303         }
304         unsigned int items = this->TreeRoot->ChildCount();
305         for (unsigned int x = 0; x < items; x++)
306         {
307                 TreeServer* Route = this->TreeRoot->GetChild(x);
308                 // Send the line IF:
309                 // The route has a socket (its a direct connection)
310                 // The route isnt the one to be omitted
311                 // The route isnt the path to the one to be omitted
312                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
313                 {
314                         TreeSocket* Sock = Route->GetSocket();
315                         if (Sock)
316                                 Sock->WriteLine(FullLine);
317                 }
318         }
319         return true;
320 }
321
322 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist &params)
323 {
324         std::string FullLine = ":" + prefix + " " + command;
325         unsigned int words = params.size();
326         for (unsigned int x = 0; x < words; x++)
327         {
328                 FullLine = FullLine + " " + params[x];
329         }
330         unsigned int items = this->TreeRoot->ChildCount();
331         for (unsigned int x = 0; x < items; x++)
332         {
333                 TreeServer* Route = this->TreeRoot->GetChild(x);
334                 if (Route && Route->GetSocket())
335                 {
336                         TreeSocket* Sock = Route->GetSocket();
337                         if (Sock)
338                                 Sock->WriteLine(FullLine);
339                 }
340         }
341         return true;
342 }
343
344 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist &params)
345 {
346         std::string spfx = prefix;
347         std::string scmd = command;
348         return this->DoOneToMany(spfx, scmd, params);
349 }
350
351 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist &params, std::string omit)
352 {
353         std::string spfx = prefix;
354         std::string scmd = command;
355         return this->DoOneToAllButSender(spfx, scmd, params, omit);
356 }
357
358 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist &params, std::string target)
359 {
360         TreeServer* Route = this->BestRouteTo(target);
361         if (Route)
362         {
363                 std::string FullLine = ":" + prefix + " " + command;
364                 unsigned int words = params.size();
365                 for (unsigned int x = 0; x < words; x++)
366                 {
367                         FullLine = FullLine + " " + params[x];
368                 }
369                 if (Route && Route->GetSocket())
370                 {
371                         TreeSocket* Sock = Route->GetSocket();
372                         if (Sock)
373                                 Sock->WriteLine(FullLine);
374                 }
375                 return true;
376         }
377         else
378         {
379                 return false;
380         }
381 }
382
383 void SpanningTreeUtilities::RefreshIPCache()
384 {
385         ValidIPs.clear();
386         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
387         {
388                 Link* L = *i;
389                 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
390                 {
391                         if (L->Name.empty())
392                         {
393                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
394                         }
395                         else
396                         {
397                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
398                         }
399
400                         /* Invalid link block */
401                         continue;
402                 }
403
404                 ValidIPs.push_back(L->IPAddr);
405
406                 if (L->AllowMask.length())
407                         ValidIPs.push_back(L->AllowMask);
408
409                 /* Needs resolving */
410                 bool ipvalid = true;
411                 QueryType start_type = DNS_QUERY_A;
412                 start_type = DNS_QUERY_AAAA;
413                 if (strchr(L->IPAddr.c_str(),':'))
414                 {
415                         in6_addr n;
416                         if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
417                                 ipvalid = false;
418                 }
419                 else
420                 {
421                         in_addr n;
422                         if (inet_aton(L->IPAddr.c_str(),&n) < 1)
423                                 ipvalid = false;
424                 }
425
426                 if (!ipvalid)
427                 {
428                         try
429                         {
430                                 bool cached;
431                                 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
432                                 ServerInstance->AddResolver(sr, cached);
433                         }
434                         catch (...)
435                         {
436                         }
437                 }
438         }
439 }
440
441 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
442 {
443         ConfigReader* Conf = new ConfigReader;
444
445         /* We don't need to worry about these being *unloaded* on the fly, only loaded,
446          * because we 'use' the interface locking the module in memory.
447          */
448         hooks.clear();
449         hooknames.clear();
450         modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
451
452         /* Did we find any modules? */
453         if (ml)
454         {
455                 /* Yes, enumerate them all to find out the hook name */
456                 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
457                 {
458                         /* Make a request to it for its name, its implementing
459                          * BufferedSocketHook so we know its safe to do this
460                          */
461                         std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
462                         /* Build a map of them */
463                         hooks[name.c_str()] = *m;
464                         hooknames.push_back(name);
465                 }
466         }
467
468         if (rebind)
469         {
470                 for (unsigned int i = 0; i < Bindings.size(); i++)
471                 {
472                         delete Bindings[i];
473                 }
474                 Bindings.clear();
475
476                 for (int j = 0; j < Conf->Enumerate("bind"); j++)
477                 {
478                         std::string Type = Conf->ReadValue("bind","type",j);
479                         std::string IP = Conf->ReadValue("bind","address",j);
480                         std::string Port = Conf->ReadValue("bind","port",j);
481                         std::string transport = Conf->ReadValue("bind","transport",j);
482                         if (Type == "servers")
483                         {
484                                 irc::portparser portrange(Port, false);
485                                 int portno = -1;
486
487                                 if (IP == "*")
488                                         IP.clear();
489
490                                 while ((portno = portrange.GetToken()))
491                                 {
492                                         if ((!transport.empty()) && (hooks.find(transport.c_str()) ==  hooks.end()))
493                                         {
494                                                 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?");
495                                                 break;
496                                         }
497
498                                         ServerSocketListener *listener = new ServerSocketListener(this, portno, (char *)IP.c_str());
499                                         if (listener->GetFd() == -1)
500                                         {
501                                                 delete listener;
502                                                 continue;
503                                         }
504
505                                         if (!transport.empty())
506                                                 listener->Hook = hooks[transport.c_str()];
507
508                                         Bindings.push_back(listener);
509                                 }
510                         }
511                 }
512         }
513         FlatLinks = Conf->ReadFlag("security","flatlinks",0);
514         HideULines = Conf->ReadFlag("security","hideulines",0);
515         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
516         AllowOptCommon = Conf->ReadFlag("options", "allowmismatch", 0);
517         ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
518         quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
519         PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
520         PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
521
522         if (PingFreq == 0)
523                 PingFreq = 60;
524
525         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
526                 PingWarnTime = 0;
527
528         AutoconnectBlocks.clear();
529         LinkBlocks.clear();
530         ValidIPs.clear();
531         for (int j = 0; j < Conf->Enumerate("link"); ++j)
532         {
533                 reference<Link> L = new Link;
534                 std::string Allow = Conf->ReadValue("link", "allowmask", j);
535                 L->Name = (Conf->ReadValue("link", "name", j)).c_str();
536                 L->AllowMask = Allow;
537                 L->IPAddr = Conf->ReadValue("link", "ipaddr", j);
538                 L->Port = Conf->ReadInteger("link", "port", j, true);
539                 L->SendPass = Conf->ReadValue("link", "sendpass", j);
540                 L->RecvPass = Conf->ReadValue("link", "recvpass", j);
541                 L->Fingerprint = Conf->ReadValue("link", "fingerprint", j);
542                 L->HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
543                 L->Timeout = Conf->ReadInteger("link", "timeout", j, true);
544                 L->Hook = Conf->ReadValue("link", "transport", j);
545                 L->Bind = Conf->ReadValue("link", "bind", j);
546                 L->Hidden = Conf->ReadFlag("link", "hidden", j);
547
548                 if ((!L->Hook.empty()) && (hooks.find(L->Hook.c_str()) ==  hooks.end()))
549                 {
550                         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.");
551                         continue;
552
553                 }
554
555                 if (L->Name.find('.') == std::string::npos)
556                         throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
557
558                 if (L->Name.length() > 64)
559                         throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
560
561                 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
562                 {
563                         if (Allow.length())
564                                 ValidIPs.push_back(Allow);
565
566                         ValidIPs.push_back(L->IPAddr);
567
568                         /* Needs resolving */
569                         bool ipvalid = true;
570                         QueryType start_type = DNS_QUERY_A;
571                         start_type = DNS_QUERY_AAAA;
572                         if (strchr(L->IPAddr.c_str(),':'))
573                         {
574                                 in6_addr n;
575                                 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
576                                         ipvalid = false;
577                         }
578                         else
579                         {
580                                 in_addr n;
581                                 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
582                                         ipvalid = false;
583                         }
584
585                         if (!ipvalid)
586                         {
587                                 try
588                                 {
589                                         bool cached;
590                                         SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
591                                         ServerInstance->AddResolver(sr, cached);
592                                 }
593                                 catch (...)
594                                 {
595                                 }
596                         }
597                 }
598                 else
599                 {
600                         if (L->IPAddr.empty())
601                         {
602                                 L->IPAddr = "*";
603                                 ValidIPs.push_back("*");
604                                 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.");
605                         }
606
607                         if (L->RecvPass.empty())
608                         {
609                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
610                         }
611
612                         if (L->SendPass.empty())
613                         {
614                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
615                         }
616
617                         if (L->Name.empty())
618                         {
619                                 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
620                         }
621
622                         if (!L->Port)
623                         {
624                                 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.");
625                         }
626                 }
627
628                 LinkBlocks.push_back(L);
629         }
630
631         for (int j = 0; j < Conf->Enumerate("autoconnect"); ++j)
632         {
633                 reference<Autoconnect> A = new Autoconnect;
634                 A->Period = Conf->ReadInteger("autoconnect", "period", j, true);
635                 A->NextConnectTime = ServerInstance->Time() + A->Period;
636                 A->position = -1;
637                 std::string servers = Conf->ReadValue("autoconnect", "server", j);
638                 irc::spacesepstream ss(servers);
639                 std::string server;
640                 while (ss.GetToken(server))
641                 {
642                         A->servers.push_back(server);
643                 }
644
645                 if (A->Period <= 0)
646                 {
647                         throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
648                 }
649
650                 if (A->servers.empty())
651                 {
652                         throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
653                 }
654
655                 AutoconnectBlocks.push_back(A);
656         }
657
658         delete Conf;
659 }
660
661 Link* SpanningTreeUtilities::FindLink(const std::string& name)
662 {
663         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
664         {
665                 Link* x = *i;
666                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
667                 {
668                         return x;
669                 }
670         }
671         return NULL;
672 }