]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
fix some unitialised vectors and tidy up a bit.
[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         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
111
112         this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
113
114         modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
115
116         /* Did we find any modules? */
117         if (ml)
118         {
119                 /* Yes, enumerate them all to find out the hook name */
120                 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
121                 {
122                         /* Make a request to it for its name, its implementing
123                          * BufferedSocketHook so we know its safe to do this
124                          */
125                         std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
126                         /* Build a map of them */
127                         hooks[name.c_str()] = *m;
128                         hooknames.push_back(name);
129                 }
130         }
131
132         this->ReadConfiguration(true);
133 }
134
135 SpanningTreeUtilities::~SpanningTreeUtilities()
136 {
137         for (unsigned int i = 0; i < Bindings.size(); i++)
138         {
139                 ServerInstance->SE->DelFd(Bindings[i]);
140                 Bindings[i]->Close();
141         }
142         while (TreeRoot->ChildCount())
143         {
144                 TreeServer* child_server = TreeRoot->GetChild(0);
145                 if (child_server)
146                 {
147                         TreeSocket* sock = child_server->GetSocket();
148                         ServerInstance->SE->DelFd(sock);
149                         sock->Close();
150                 }
151         }
152         delete TreeRoot;
153         ServerInstance->BufferedSocketCull();
154 }
155
156 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
157 {
158         if (list.find(server) == list.end())
159                 list[server] = server;
160 }
161
162 /* returns a list of DIRECT servernames for a specific channel */
163 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
164 {
165         CUList *ulist = c->GetUsers();
166
167         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
168         {
169                 if (IS_LOCAL(i->first))
170                         continue;
171
172                 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
173                         continue;
174
175                 if (exempt_list.find(i->first) == exempt_list.end())
176                 {
177                         TreeServer* best = this->BestRouteTo(i->first->server);
178                         if (best)
179                                 AddThisServer(best,list);
180                 }
181         }
182         return;
183 }
184
185 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params)
186 {
187         char pfx = 0;
188         TreeServer* omitroute = this->BestRouteTo(omit);
189         if ((command == "NOTICE") || (command == "PRIVMSG"))
190         {
191                 if (params.size() >= 2)
192                 {
193                         /* Prefixes */
194                         if (ServerInstance->Modes->FindPrefix(params[0][0]))
195                         {
196                                 pfx = params[0][0];
197                                 params[0] = params[0].substr(1, params[0].length()-1);
198                         }
199                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
200                         {
201                                 // special routing for private messages/notices
202                                 User* d = ServerInstance->FindNick(params[0]);
203                                 if (d)
204                                 {
205                                         std::deque<std::string> par;
206                                         par.push_back(params[0]);
207                                         par.push_back(":"+params[1]);
208                                         this->DoOneToOne(prefix,command.c_str(),par,d->server);
209                                         return true;
210                                 }
211                         }
212                         else if (*(params[0].c_str()) == '$')
213                         {
214                                 std::deque<std::string> par;
215                                 par.push_back(params[0]);
216                                 par.push_back(":"+params[1]);
217                                 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
218                                 return true;
219                         }
220                         else
221                         {
222                                 Channel* c = ServerInstance->FindChan(params[0]);
223                                 User* u = ServerInstance->FindNick(prefix);
224                                 if (c)
225                                 {
226                                         CUList elist;
227                                         TreeServerList list;
228                                         FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
229                                         GetListOfServersForChannel(c,list,pfx,elist);
230
231                                         for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
232                                         {
233                                                 TreeSocket* Sock = i->second->GetSocket();
234                                                 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
235                                                 {
236                                                         Sock->WriteLine(data);
237                                                 }
238                                         }
239                                         return true;
240                                 }
241                         }
242                 }
243         }
244         unsigned int items =this->TreeRoot->ChildCount();
245         for (unsigned int x = 0; x < items; x++)
246         {
247                 TreeServer* Route = this->TreeRoot->GetChild(x);
248                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
249                 {
250                         TreeSocket* Sock = Route->GetSocket();
251                         if (Sock)
252                                 Sock->WriteLine(data);
253                 }
254         }
255         return true;
256 }
257
258 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit)
259 {
260         TreeServer* omitroute = this->BestRouteTo(omit);
261         std::string FullLine = ":" + prefix + " " + command;
262         unsigned int words = params.size();
263         for (unsigned int x = 0; x < words; x++)
264         {
265                 FullLine = FullLine + " " + params[x];
266         }
267         unsigned int items = this->TreeRoot->ChildCount();
268         for (unsigned int x = 0; x < items; x++)
269         {
270                 TreeServer* Route = this->TreeRoot->GetChild(x);
271                 // Send the line IF:
272                 // The route has a socket (its a direct connection)
273                 // The route isnt the one to be omitted
274                 // The route isnt the path to the one to be omitted
275                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
276                 {
277                         TreeSocket* Sock = Route->GetSocket();
278                         if (Sock)
279                                 Sock->WriteLine(FullLine);
280                 }
281         }
282         return true;
283 }
284
285 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params)
286 {
287         std::string FullLine = ":" + prefix + " " + command;
288         unsigned int words = params.size();
289         for (unsigned int x = 0; x < words; x++)
290         {
291                 FullLine = FullLine + " " + params[x];
292         }
293         unsigned int items = this->TreeRoot->ChildCount();
294         for (unsigned int x = 0; x < items; x++)
295         {
296                 TreeServer* Route = this->TreeRoot->GetChild(x);
297                 if (Route && Route->GetSocket())
298                 {
299                         TreeSocket* Sock = Route->GetSocket();
300                         if (Sock)
301                                 Sock->WriteLine(FullLine);
302                 }
303         }
304         return true;
305 }
306
307 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params)
308 {
309         std::string spfx = prefix;
310         std::string scmd = command;
311         return this->DoOneToMany(spfx, scmd, params);
312 }
313
314 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit)
315 {
316         std::string spfx = prefix;
317         std::string scmd = command;
318         return this->DoOneToAllButSender(spfx, scmd, params, omit);
319 }
320
321 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target)
322 {
323         TreeServer* Route = this->BestRouteTo(target);
324         if (Route)
325         {
326                 std::string FullLine = ":" + prefix + " " + command;
327                 unsigned int words = params.size();
328                 for (unsigned int x = 0; x < words; x++)
329                 {
330                         FullLine = FullLine + " " + params[x];
331                 }
332                 if (Route && Route->GetSocket())
333                 {
334                         TreeSocket* Sock = Route->GetSocket();
335                         if (Sock)
336                                 Sock->WriteLine(FullLine);
337                 }
338                 return true;
339         }
340         else
341         {
342                 return false;
343         }
344 }
345
346 void SpanningTreeUtilities::RefreshIPCache()
347 {
348         ValidIPs.clear();
349         for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
350         {
351                 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
352                 {
353                         ValidIPs.push_back(L->IPAddr);
354
355                         if (L->AllowMask.length())
356                                 ValidIPs.push_back(L->AllowMask);
357
358                         /* Needs resolving */
359                         bool ipvalid = true;
360                         QueryType start_type = DNS_QUERY_A;
361 #ifdef IPV6
362                         start_type = DNS_QUERY_AAAA;
363                         if (strchr(L->IPAddr.c_str(),':'))
364                         {
365                                 in6_addr n;
366                                 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
367                                         ipvalid = false;
368                         }
369                         else
370 #endif
371                         {
372                                 in_addr n;
373                                 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
374                                         ipvalid = false;
375                         }
376                         if (!ipvalid)
377                         {
378                                 try
379                                 {
380                                         bool cached;
381                                         SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
382                                         ServerInstance->AddResolver(sr, cached);
383                                 }
384                                 catch (...)
385                                 {
386                                 }
387                         }
388                 }
389         }
390 }
391
392 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
393 {
394         ConfigReader* Conf = new ConfigReader(ServerInstance);
395         if (rebind)
396         {
397                 for (unsigned int i = 0; i < Bindings.size(); i++)
398                 {
399                         ServerInstance->SE->DelFd(Bindings[i]);
400                         Bindings[i]->Close();
401                 }
402                 ServerInstance->BufferedSocketCull();
403                 Bindings.clear();
404
405                 for (int j = 0; j < Conf->Enumerate("bind"); j++)
406                 {
407                         std::string Type = Conf->ReadValue("bind","type",j);
408                         std::string IP = Conf->ReadValue("bind","address",j);
409                         std::string Port = Conf->ReadValue("bind","port",j);
410                         std::string transport = Conf->ReadValue("bind","transport",j);
411                         if (Type == "servers")
412                         {
413                                 irc::portparser portrange(Port, false);
414                                 int portno = -1;
415
416                                 if (IP == "*")
417                                         IP.clear();
418
419                                 while ((portno = portrange.GetToken()))
420                                 {
421                                         if ((!transport.empty()) && (hooks.find(transport.c_str()) ==  hooks.end()))
422                                         {
423                                                 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?");
424                                                 break;
425                                         }
426
427                                         TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
428                                         if (listener->GetState() == I_LISTENING)
429                                         {
430                                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
431                                                 Bindings.push_back(listener);
432                                         }
433                                         else
434                                         {
435                                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
436                                                 listener->Close();
437                                         }
438                                 }
439                         }
440                 }
441         }
442         FlatLinks = Conf->ReadFlag("security","flatlinks",0);
443         HideULines = Conf->ReadFlag("security","hideulines",0);
444         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
445         ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
446         quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
447         PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
448         PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
449
450         if (PingFreq == 0)
451                 PingFreq = 60;
452
453         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
454                 PingWarnTime = 0;
455
456         LinkBlocks.clear();
457         ValidIPs.clear();
458         for (int j = 0; j < Conf->Enumerate("link"); j++)
459         {
460                 Link L;
461                 std::string Allow = Conf->ReadValue("link", "allowmask", j);
462                 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
463                 L.AllowMask = Allow;
464                 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
465                 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
466                 L.Port = Conf->ReadInteger("link", "port", j, true);
467                 L.SendPass = Conf->ReadValue("link", "sendpass", j);
468                 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
469                 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
470                 L.HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
471                 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
472                 L.Hook = Conf->ReadValue("link", "transport", j);
473                 L.Bind = Conf->ReadValue("link", "bind", j);
474                 L.Hidden = Conf->ReadFlag("link", "hidden", j);
475
476                 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) ==  hooks.end()))
477                 {
478                         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.");
479                         continue;
480
481                 }
482
483                 L.NextConnectTime = time(NULL) + L.AutoConnect;
484                 /* Bugfix by brain, do not allow people to enter bad configurations */
485                 if (L.Name != ServerInstance->Config->ServerName)
486                 {
487                         if (L.Name.find('.') == std::string::npos)
488                                 throw CoreException("The link name '"+assign(L.Name)+"' is invalid and must contain at least one '.' character");
489
490                         if (L.Name.length() > 64)
491                                 throw CoreException("The link name '"+assign(L.Name)+"' is longer than 64 characters!");
492
493                         if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
494                         {
495                                 if (Allow.length())
496                                         ValidIPs.push_back(Allow);
497
498                                 ValidIPs.push_back(L.IPAddr);
499
500                                 /* Needs resolving */
501                                 bool ipvalid = true;
502                                 QueryType start_type = DNS_QUERY_A;
503 #ifdef IPV6
504                                 start_type = DNS_QUERY_AAAA;
505                                 if (strchr(L.IPAddr.c_str(),':'))
506                                 {
507                                         in6_addr n;
508                                         if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
509                                                 ipvalid = false;
510                                 }
511                                 else
512                                 {
513                                         in_addr n;
514                                         if (inet_aton(L.IPAddr.c_str(),&n) < 1)
515                                                 ipvalid = false;
516                                 }
517 #else
518                                 in_addr n;
519                                 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
520                                         ipvalid = false;
521 #endif
522
523                                 if (!ipvalid)
524                                 {
525                                         try
526                                         {
527                                                 bool cached;
528                                                 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
529                                                 ServerInstance->AddResolver(sr, cached);
530                                         }
531                                         catch (...)
532                                         {
533                                         }
534                                 }
535                         }
536                         else
537                         {
538                                 if (L.IPAddr.empty())
539                                 {
540                                         L.IPAddr = "*";
541                                         ValidIPs.push_back("*");
542                                         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.");
543                                 }
544
545                                 if (L.RecvPass.empty())
546                                 {
547                                         throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', recvpass not defined!");
548                                 }
549
550                                 if (L.SendPass.empty())
551                                 {
552                                         throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', sendpass not defined!");
553                                 }
554
555                                 if (L.Name.empty())
556                                 {
557                                         throw CoreException("Invalid configuration, link tag without a name! IP address: "+L.IPAddr);
558                                 }
559
560                                 if (!L.Port)
561                                 {
562                                         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.");
563                                 }
564                         }
565
566
567                         LinkBlocks.push_back(L);
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->Logs->Log("m_spanningtree",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 }