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