]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Do not add empty strings to outgoing lines. *needs testing, may break 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-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                 if (!params[x].empty())
302                         FullLine = FullLine + " " + params[x];
303         }
304         unsigned int items = this->TreeRoot->ChildCount();
305         for (unsigned int x = 0; x < items; x++)
306         {
307                 TreeServer* Route = this->TreeRoot->GetChild(x);
308                 // Send the line IF:
309                 // The route has a socket (its a direct connection)
310                 // The route isnt the one to be omitted
311                 // The route isnt the path to the one to be omitted
312                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
313                 {
314                         TreeSocket* Sock = Route->GetSocket();
315                         if (Sock)
316                                 Sock->WriteLine(FullLine);
317                 }
318         }
319         return true;
320 }
321
322 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params)
323 {
324         std::string FullLine = ":" + prefix + " " + command;
325         unsigned int words = params.size();
326         for (unsigned int x = 0; x < words; x++)
327         {
328                 if (!params[x].empty())
329                         FullLine = FullLine + " " + params[x];
330         }
331         unsigned int items = this->TreeRoot->ChildCount();
332         for (unsigned int x = 0; x < items; x++)
333         {
334                 TreeServer* Route = this->TreeRoot->GetChild(x);
335                 if (Route && Route->GetSocket())
336                 {
337                         TreeSocket* Sock = Route->GetSocket();
338                         if (Sock)
339                                 Sock->WriteLine(FullLine);
340                 }
341         }
342         return true;
343 }
344
345 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params)
346 {
347         std::string spfx = prefix;
348         std::string scmd = command;
349         return this->DoOneToMany(spfx, scmd, params);
350 }
351
352 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit)
353 {
354         std::string spfx = prefix;
355         std::string scmd = command;
356         return this->DoOneToAllButSender(spfx, scmd, params, omit);
357 }
358
359 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target)
360 {
361         TreeServer* Route = this->BestRouteTo(target);
362         if (Route)
363         {
364                 std::string FullLine = ":" + prefix + " " + command;
365                 unsigned int words = params.size();
366                 for (unsigned int x = 0; x < words; x++)
367                 {
368                         FullLine = FullLine + " " + params[x];
369                 }
370                 if (Route && Route->GetSocket())
371                 {
372                         TreeSocket* Sock = Route->GetSocket();
373                         if (Sock)
374                                 Sock->WriteLine(FullLine);
375                 }
376                 return true;
377         }
378         else
379         {
380                 return false;
381         }
382 }
383
384 void SpanningTreeUtilities::RefreshIPCache()
385 {
386         ValidIPs.clear();
387         for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
388         {
389                 if ((L->IPAddr != "") && (L->RecvPass != "") && (L->SendPass != "") && (L->Name != "") && (L->Port))
390                 {
391                         ValidIPs.push_back(L->IPAddr);
392
393                         if (L->AllowMask.length())
394                                 ValidIPs.push_back(L->AllowMask);
395
396                         /* Needs resolving */
397                         bool ipvalid = true;
398                         QueryType start_type = DNS_QUERY_A;
399 #ifdef IPV6
400                         start_type = DNS_QUERY_AAAA;
401                         if (strchr(L->IPAddr.c_str(),':'))
402                         {
403                                 in6_addr n;
404                                 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
405                                         ipvalid = false;
406                         }
407                         else
408                         {
409                                 in_addr n;
410                                 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
411                                         ipvalid = false;
412                         }
413 #else
414                         in_addr n;
415                         if (inet_aton(L->IPAddr.c_str(),&n) < 1)
416                                 ipvalid = false;
417 #endif
418                         if (!ipvalid)
419                         {
420                                 try
421                                 {
422                                         bool cached;
423                                         SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
424                                         ServerInstance->AddResolver(sr, cached);
425                                 }
426                                 catch (ModuleException& e)
427                                 {
428                                 }
429                         }
430                 }
431         }
432 }
433
434 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
435 {
436         ConfigReader* Conf = new ConfigReader(ServerInstance);
437         if (rebind)
438         {
439                 for (int j =0; j < Conf->Enumerate("bind"); j++)
440                 {
441                         std::string Type = Conf->ReadValue("bind","type",j);
442                         std::string IP = Conf->ReadValue("bind","address",j);
443                         std::string Port = Conf->ReadValue("bind","port",j);
444                         std::string transport = Conf->ReadValue("bind","transport",j);
445                         if (Type == "servers")
446                         {
447                                 irc::portparser portrange(Port, false);
448                                 int portno = -1;
449                                 while ((portno = portrange.GetToken()))
450                                 {
451                                         if (IP == "*")
452                                                 IP = "";
453
454                                         if ((!transport.empty()) && (hooks.find(transport.c_str()) ==  hooks.end()))
455                                         {
456                                                 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());
457                                                 break;
458                                         }
459
460                                         TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
461                                         if (listener->GetState() == I_LISTENING)
462                                         {
463                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
464                                                 Bindings.push_back(listener);
465                                         }
466                                         else
467                                         {
468                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
469                                                 listener->Close();
470                                                 DELETE(listener);
471                                         }
472                                 }
473                         }
474                 }
475         }
476         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
477         HideULines = Conf->ReadFlag("options","hideulines",0);
478         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
479         EnableTimeSync = Conf->ReadFlag("timesync","enable",0);
480         MasterTime = Conf->ReadFlag("timesync", "master", 0);
481         ChallengeResponse = !Conf->ReadFlag("options", "disablehmac", 0);
482         LinkBlocks.clear();
483         ValidIPs.clear();
484         for (int j =0; j < Conf->Enumerate("link"); j++)
485         {
486                 Link L;
487                 std::string Allow = Conf->ReadValue("link", "allowmask", j);
488                 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
489                 L.AllowMask = Allow;
490                 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
491                 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
492                 L.Port = Conf->ReadInteger("link", "port", j, true);
493                 L.SendPass = Conf->ReadValue("link", "sendpass", j);
494                 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
495                 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
496                 L.HiddenFromStats = Conf->ReadFlag("link", "hidden", j);
497                 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
498                 L.Hook = Conf->ReadValue("link", "transport", j);
499                 L.Bind = Conf->ReadValue("link", "bind", j);
500                 L.Hidden = Conf->ReadFlag("link", "hidden", j);
501
502                 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) ==  hooks.end()))
503                 {
504                         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.",
505                         L.Hook.c_str(), L.Name.c_str());
506                         continue;
507
508                 }
509
510                 L.NextConnectTime = time(NULL) + L.AutoConnect;
511                 /* Bugfix by brain, do not allow people to enter bad configurations */
512                 if (L.Name != ServerInstance->Config->ServerName)
513                 {
514                         if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
515                         {
516                                 ValidIPs.push_back(L.IPAddr);
517
518                                 if (Allow.length())
519                                         ValidIPs.push_back(Allow);
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 (ModuleException& e)
553                                         {
554                                         }
555                                 }
556
557                                 LinkBlocks.push_back(L);
558                         }
559                         else
560                         {
561                                 if (L.IPAddr == "")
562                                 {
563                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
564                                 }
565                                 else if (L.RecvPass == "")
566                                 {
567                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
568                                 }
569                                 else if (L.SendPass == "")
570                                 {
571                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
572                                 }
573                                 else if (L.Name == "")
574                                 {
575                                         ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
576                                 }
577                                 else if (!L.Port)
578                                 {
579                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
580                                 }
581                         }
582                 }
583                 else
584                 {
585                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
586                 }
587         }
588         DELETE(Conf);
589 }
590
591 void SpanningTreeUtilities::DoFailOver(Link* x)
592 {
593         if (x->FailOver.length())
594         {
595                 if (x->FailOver == x->Name)
596                 {
597                         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());
598                         return;
599                 }
600                 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
601                 if (TryThisOne)
602                 {
603                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
604                         Creator->ConnectServer(TryThisOne);
605                 }
606                 else
607                 {
608                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
609                 }
610         }
611 }
612
613 Link* SpanningTreeUtilities::FindLink(const std::string& name)
614 {
615         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
616         {
617                 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
618                 {
619                         return &(*x);
620                 }
621         }
622         return NULL;
623 }
624