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