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