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 /** Returns the locally connected server we must route a
57 * message through to reach server 'ServerName'. This
58 * only applies to one-to-one and not one-to-many routing.
59 * See the comments for the constructor of TreeServer
62 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
64 if (ServerName.c_str() == TreeRoot->GetName())
66 TreeServer* Found = FindServer(ServerName);
69 return Found->GetRoute();
77 /** Find the first server matching a given glob mask.
78 * Theres no find-using-glob method of hash_map [awwww :-(]
79 * so instead, we iterate over the list using an iterator
80 * and match each one until we get a hit. Yes its slow,
83 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
85 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
87 if (match(i->first.c_str(),ServerName.c_str()))
93 /* A convenient wrapper that returns true if a server exists */
94 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
96 return (FindServer(ServerName) != NULL);
99 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
105 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
107 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
109 /* Did we find any modules? */
112 /* Yes, enumerate them all to find out the hook name */
113 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
115 /* Make a request to it for its name, its implementing
116 * InspSocketHook so we know its safe to do this
118 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
119 /* Build a map of them */
120 hooks[name.c_str()] = *m;
121 hooknames.push_back(name);
125 this->ReadConfiguration(true);
128 SpanningTreeUtilities::~SpanningTreeUtilities()
130 for (unsigned int i = 0; i < Bindings.size(); i++)
132 ServerInstance->SE->DelFd(Bindings[i]);
133 Bindings[i]->Close();
136 while (TreeRoot->ChildCount())
138 TreeServer* child_server = TreeRoot->GetChild(0);
141 TreeSocket* sock = child_server->GetSocket();
142 ServerInstance->SE->DelFd(sock);
150 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
152 if (list.find(server) == list.end())
153 list[server] = server;
156 /* returns a list of DIRECT servernames for a specific channel */
157 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
163 ulist = c->GetOppedUsers();
166 ulist = c->GetHalfoppedUsers();
169 ulist = c->GetVoicedUsers();
172 ulist = c->GetUsers();
175 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
177 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
179 TreeServer* best = this->BestRouteTo(i->second->server);
181 AddThisServer(best,list);
187 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
190 TreeServer* omitroute = this->BestRouteTo(omit);
191 if ((command == "NOTICE") || (command == "PRIVMSG"))
193 if (params.size() >= 2)
196 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
199 params[0] = params[0].substr(1, params[0].length()-1);
201 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
203 // special routing for private messages/notices
204 userrec* d = ServerInstance->FindNick(params[0]);
207 std::deque<std::string> par;
208 par.push_back(params[0]);
209 par.push_back(":"+params[1]);
210 this->DoOneToOne(prefix,command.c_str(),par,d->server);
214 else if (*(params[0].c_str()) == '$')
216 std::deque<std::string> par;
217 par.push_back(params[0]);
218 par.push_back(":"+params[1]);
219 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
224 chanrec* c = ServerInstance->FindChan(params[0]);
225 userrec* u = ServerInstance->FindNick(prefix);
230 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
231 GetListOfServersForChannel(c,list,pfx,elist);
233 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
235 TreeSocket* Sock = i->second->GetSocket();
236 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
238 Sock->WriteLine(data);
246 unsigned int items =this->TreeRoot->ChildCount();
247 for (unsigned int x = 0; x < items; x++)
249 TreeServer* Route = this->TreeRoot->GetChild(x);
250 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
252 TreeSocket* Sock = Route->GetSocket();
254 Sock->WriteLine(data);
260 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
262 TreeServer* omitroute = this->BestRouteTo(omit);
263 std::string FullLine = ":" + prefix + " " + command;
264 unsigned int words = params.size();
265 for (unsigned int x = 0; x < words; x++)
267 FullLine = FullLine + " " + params[x];
269 unsigned int items = this->TreeRoot->ChildCount();
270 for (unsigned int x = 0; x < items; x++)
272 TreeServer* Route = this->TreeRoot->GetChild(x);
274 // The route has a socket (its a direct connection)
275 // The route isnt the one to be omitted
276 // The route isnt the path to the one to be omitted
277 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
279 TreeSocket* Sock = Route->GetSocket();
281 Sock->WriteLine(FullLine);
287 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
289 std::string FullLine = ":" + prefix + " " + command;
290 unsigned int words = params.size();
291 for (unsigned int x = 0; x < words; x++)
293 FullLine = FullLine + " " + params[x];
295 unsigned int items = this->TreeRoot->ChildCount();
296 for (unsigned int x = 0; x < items; x++)
298 TreeServer* Route = this->TreeRoot->GetChild(x);
299 if (Route && Route->GetSocket())
301 TreeSocket* Sock = Route->GetSocket();
303 Sock->WriteLine(FullLine);
309 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
311 std::string spfx = prefix;
312 std::string scmd = command;
313 return this->DoOneToMany(spfx, scmd, params);
316 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
318 std::string spfx = prefix;
319 std::string scmd = command;
320 return this->DoOneToAllButSender(spfx, scmd, params, omit);
323 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
325 TreeServer* Route = this->BestRouteTo(target);
328 std::string FullLine = ":" + prefix + " " + command;
329 unsigned int words = params.size();
330 for (unsigned int x = 0; x < words; x++)
332 FullLine = FullLine + " " + params[x];
334 if (Route && Route->GetSocket())
336 TreeSocket* Sock = Route->GetSocket();
338 Sock->WriteLine(FullLine);
348 void SpanningTreeUtilities::RefreshIPCache()
351 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
353 if ((L->IPAddr != "") && (L->RecvPass != "") && (L->SendPass != "") && (L->Name != "") && (L->Port))
355 ValidIPs.push_back(L->IPAddr);
357 if (L->AllowMask.length())
358 ValidIPs.push_back(L->AllowMask);
360 /* Needs resolving */
362 QueryType start_type = DNS_QUERY_A;
364 start_type = DNS_QUERY_AAAA;
365 if (strchr(L->IPAddr.c_str(),':'))
368 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
374 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
379 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
387 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
388 ServerInstance->AddResolver(sr, cached);
390 catch (ModuleException& e)
398 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
400 ConfigReader* Conf = new ConfigReader(ServerInstance);
403 for (int j =0; j < Conf->Enumerate("bind"); j++)
405 std::string Type = Conf->ReadValue("bind","type",j);
406 std::string IP = Conf->ReadValue("bind","address",j);
407 std::string Port = Conf->ReadValue("bind","port",j);
408 std::string transport = Conf->ReadValue("bind","transport",j);
409 if (Type == "servers")
411 irc::portparser portrange(Port, false);
413 while ((portno = portrange.GetToken()))
418 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
420 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());
424 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
425 if (listener->GetState() == I_LISTENING)
427 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
428 Bindings.push_back(listener);
432 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
440 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
441 HideULines = Conf->ReadFlag("options","hideulines",0);
442 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
443 EnableTimeSync = Conf->ReadFlag("timesync","enable",0);
444 MasterTime = Conf->ReadFlag("timesync", "master", 0);
447 for (int j =0; j < Conf->Enumerate("link"); j++)
450 std::string Allow = Conf->ReadValue("link", "allowmask", j);
451 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
453 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
454 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
455 L.Port = Conf->ReadInteger("link", "port", j, true);
456 L.SendPass = Conf->ReadValue("link", "sendpass", j);
457 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
458 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
459 L.HiddenFromStats = Conf->ReadFlag("link", "hidden", j);
460 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
461 L.Hook = Conf->ReadValue("link", "transport", j);
462 L.Bind = Conf->ReadValue("link", "bind", j);
463 L.Hidden = Conf->ReadFlag("link", "hidden", j);
465 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
467 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.",
468 L.Hook.c_str(), L.Name.c_str());
473 L.NextConnectTime = time(NULL) + L.AutoConnect;
474 /* Bugfix by brain, do not allow people to enter bad configurations */
475 if (L.Name != ServerInstance->Config->ServerName)
477 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
479 ValidIPs.push_back(L.IPAddr);
482 ValidIPs.push_back(Allow);
484 /* Needs resolving */
486 QueryType start_type = DNS_QUERY_A;
488 start_type = DNS_QUERY_AAAA;
489 if (strchr(L.IPAddr.c_str(),':'))
492 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
498 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
503 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
512 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
513 ServerInstance->AddResolver(sr, cached);
515 catch (ModuleException& e)
520 LinkBlocks.push_back(L);
526 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
528 else if (L.RecvPass == "")
530 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
532 else if (L.SendPass == "")
534 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
536 else if (L.Name == "")
538 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
542 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
548 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
554 void SpanningTreeUtilities::DoFailOver(Link* x)
556 if (x->FailOver.length())
558 if (x->FailOver == x->Name)
560 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());
563 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
566 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
567 Creator->ConnectServer(TryThisOne);
571 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
576 Link* SpanningTreeUtilities::FindLink(const std::string& name)
578 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
580 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))