1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #include "configreader.h"
18 #include "commands/cmd_whois.h"
19 #include "commands/cmd_stats.h"
24 #include "transport.h"
25 #include "socketengine.h"
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"
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 */
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.
42 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
44 server_hash::iterator iter;
45 iter = serverlist.find(ServerName.c_str());
46 if (iter != serverlist.end())
56 TreeSocket* SpanningTreeUtilities::FindBurstingServer(const std::string &ServerName)
58 std::map<irc::string,TreeSocket*>::iterator iter;
59 iter = burstingserverlist.find(ServerName.c_str());
60 if (iter != burstingserverlist.end())
70 void SpanningTreeUtilities::AddBurstingServer(const std::string &ServerName, TreeSocket* s)
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;
78 void SpanningTreeUtilities::DelBurstingServer(TreeSocket* s)
80 for (std::map<irc::string,TreeSocket*>::iterator iter = burstingserverlist.begin(); iter != burstingserverlist.end(); iter++)
82 if (iter->second == s)
84 burstingserverlist.erase(iter);
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
96 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
98 if (ServerName.c_str() == TreeRoot->GetName())
100 TreeServer* Found = FindServer(ServerName);
103 return Found->GetRoute();
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,
117 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
119 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
121 if (match(i->first.c_str(),ServerName.c_str()))
127 /* A convenient wrapper that returns true if a server exists */
128 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
130 return (FindServer(ServerName) != NULL);
133 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
139 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
141 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
143 /* Did we find any modules? */
146 /* Yes, enumerate them all to find out the hook name */
147 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
149 /* Make a request to it for its name, its implementing
150 * InspSocketHook so we know its safe to do this
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);
159 this->ReadConfiguration(true);
162 SpanningTreeUtilities::~SpanningTreeUtilities()
164 for (unsigned int i = 0; i < Bindings.size(); i++)
166 ServerInstance->SE->DelFd(Bindings[i]);
167 Bindings[i]->Close();
170 while (TreeRoot->ChildCount())
172 TreeServer* child_server = TreeRoot->GetChild(0);
175 TreeSocket* sock = child_server->GetSocket();
176 ServerInstance->SE->DelFd(sock);
184 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
186 if (list.find(server) == list.end())
187 list[server] = server;
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)
197 ulist = c->GetOppedUsers();
200 ulist = c->GetHalfoppedUsers();
203 ulist = c->GetVoicedUsers();
206 ulist = c->GetUsers();
209 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
211 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
213 TreeServer* best = this->BestRouteTo(i->second->server);
215 AddThisServer(best,list);
221 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
224 TreeServer* omitroute = this->BestRouteTo(omit);
225 if ((command == "NOTICE") || (command == "PRIVMSG"))
227 if (params.size() >= 2)
230 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
233 params[0] = params[0].substr(1, params[0].length()-1);
235 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
237 // special routing for private messages/notices
238 userrec* d = ServerInstance->FindNick(params[0]);
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);
248 else if (*(params[0].c_str()) == '$')
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());
258 chanrec* c = ServerInstance->FindChan(params[0]);
259 userrec* u = ServerInstance->FindNick(prefix);
264 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
265 GetListOfServersForChannel(c,list,pfx,elist);
267 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
269 TreeSocket* Sock = i->second->GetSocket();
270 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
272 Sock->WriteLine(data);
280 unsigned int items =this->TreeRoot->ChildCount();
281 for (unsigned int x = 0; x < items; x++)
283 TreeServer* Route = this->TreeRoot->GetChild(x);
284 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
286 TreeSocket* Sock = Route->GetSocket();
288 Sock->WriteLine(data);
294 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
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++)
301 if (!params[x].empty())
302 FullLine = FullLine + " " + params[x];
304 unsigned int items = this->TreeRoot->ChildCount();
305 for (unsigned int x = 0; x < items; x++)
307 TreeServer* Route = this->TreeRoot->GetChild(x);
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))
314 TreeSocket* Sock = Route->GetSocket();
316 Sock->WriteLine(FullLine);
322 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
324 std::string FullLine = ":" + prefix + " " + command;
325 unsigned int words = params.size();
326 for (unsigned int x = 0; x < words; x++)
328 if (!params[x].empty())
329 FullLine = FullLine + " " + params[x];
331 unsigned int items = this->TreeRoot->ChildCount();
332 for (unsigned int x = 0; x < items; x++)
334 TreeServer* Route = this->TreeRoot->GetChild(x);
335 if (Route && Route->GetSocket())
337 TreeSocket* Sock = Route->GetSocket();
339 Sock->WriteLine(FullLine);
345 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
347 std::string spfx = prefix;
348 std::string scmd = command;
349 return this->DoOneToMany(spfx, scmd, params);
352 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
354 std::string spfx = prefix;
355 std::string scmd = command;
356 return this->DoOneToAllButSender(spfx, scmd, params, omit);
359 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
361 TreeServer* Route = this->BestRouteTo(target);
364 std::string FullLine = ":" + prefix + " " + command;
365 unsigned int words = params.size();
366 for (unsigned int x = 0; x < words; x++)
368 FullLine = FullLine + " " + params[x];
370 if (Route && Route->GetSocket())
372 TreeSocket* Sock = Route->GetSocket();
374 Sock->WriteLine(FullLine);
384 void SpanningTreeUtilities::RefreshIPCache()
387 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
389 if ((L->IPAddr != "") && (L->RecvPass != "") && (L->SendPass != "") && (L->Name != "") && (L->Port))
391 ValidIPs.push_back(L->IPAddr);
393 if (L->AllowMask.length())
394 ValidIPs.push_back(L->AllowMask);
396 /* Needs resolving */
398 QueryType start_type = DNS_QUERY_A;
400 start_type = DNS_QUERY_AAAA;
401 if (strchr(L->IPAddr.c_str(),':'))
404 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
410 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
415 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
423 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
424 ServerInstance->AddResolver(sr, cached);
426 catch (ModuleException& e)
434 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
436 ConfigReader* Conf = new ConfigReader(ServerInstance);
439 for (int j =0; j < Conf->Enumerate("bind"); j++)
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")
447 irc::portparser portrange(Port, false);
449 while ((portno = portrange.GetToken()))
454 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
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());
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)
463 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
464 Bindings.push_back(listener);
468 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
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);
484 for (int j =0; j < Conf->Enumerate("link"); j++)
487 std::string Allow = Conf->ReadValue("link", "allowmask", j);
488 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
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);
502 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
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());
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)
514 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
516 ValidIPs.push_back(L.IPAddr);
519 ValidIPs.push_back(Allow);
521 /* Needs resolving */
523 QueryType start_type = DNS_QUERY_A;
525 start_type = DNS_QUERY_AAAA;
526 if (strchr(L.IPAddr.c_str(),':'))
529 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
535 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
540 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
549 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
550 ServerInstance->AddResolver(sr, cached);
552 catch (ModuleException& e)
557 LinkBlocks.push_back(L);
563 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
565 else if (L.RecvPass == "")
567 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
569 else if (L.SendPass == "")
571 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
573 else if (L.Name == "")
575 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
579 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
585 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
591 void SpanningTreeUtilities::DoFailOver(Link* x)
593 if (x->FailOver.length())
595 if (x->FailOver == x->Name)
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());
600 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
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);
608 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
613 Link* SpanningTreeUtilities::FindLink(const std::string& name)
615 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
617 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))