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 * ---------------------------------------------------
15 #include "configreader.h"
19 #include "commands/cmd_whois.h"
20 #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 = serverlist.find(ServerName.c_str());
45 if (iter != serverlist.end())
55 TreeServer* SpanningTreeUtilities::FindRemoteBurstServer(TreeServer* Server)
57 server_hash::iterator iter = RemoteServersBursting.find(Server->GetName().c_str());
58 if (iter != RemoteServersBursting.end())
64 TreeSocket* SpanningTreeUtilities::FindBurstingServer(const std::string &ServerName)
66 std::map<irc::string,TreeSocket*>::iterator iter;
67 iter = burstingserverlist.find(ServerName.c_str());
68 if (iter != burstingserverlist.end())
78 void SpanningTreeUtilities::SetRemoteBursting(TreeServer* Server, bool bursting)
80 server_hash::iterator iter = RemoteServersBursting.find(Server->GetName().c_str());
83 if (iter == RemoteServersBursting.end())
84 RemoteServersBursting.insert(make_pair(Server->GetName(), Server));
89 if (iter != RemoteServersBursting.end())
90 RemoteServersBursting.erase(iter);
93 ServerInstance->Log(DEBUG,"Server %s is %sbursting nicknames", Server->GetName().c_str(), bursting ? "" : "no longer ");
96 void SpanningTreeUtilities::AddBurstingServer(const std::string &ServerName, TreeSocket* s)
98 std::map<irc::string,TreeSocket*>::iterator iter = burstingserverlist.find(ServerName.c_str());
99 if (iter == burstingserverlist.end())
100 burstingserverlist[ServerName.c_str()] = s;
103 void SpanningTreeUtilities::DelBurstingServer(TreeSocket* s)
105 for (std::map<irc::string,TreeSocket*>::iterator iter = burstingserverlist.begin(); iter != burstingserverlist.end(); iter++)
107 if (iter->second == s)
109 burstingserverlist.erase(iter);
115 /** Returns the locally connected server we must route a
116 * message through to reach server 'ServerName'. This
117 * only applies to one-to-one and not one-to-many routing.
118 * See the comments for the constructor of TreeServer
121 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
123 if (ServerName.c_str() == TreeRoot->GetName())
125 TreeServer* Found = FindServer(ServerName);
128 return Found->GetRoute();
136 /** Find the first server matching a given glob mask.
137 * Theres no find-using-glob method of hash_map [awwww :-(]
138 * so instead, we iterate over the list using an iterator
139 * and match each one until we get a hit. Yes its slow,
142 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
144 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
146 if (match(i->first.c_str(),ServerName.c_str()))
152 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
154 server_hash::iterator iter = sidlist.find(id);
155 if (iter != sidlist.end())
161 /* A convenient wrapper that returns true if a server exists */
162 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
164 return (FindServer(ServerName) != NULL);
167 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
173 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
175 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
177 /* Did we find any modules? */
180 /* Yes, enumerate them all to find out the hook name */
181 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
183 /* Make a request to it for its name, its implementing
184 * InspSocketHook so we know its safe to do this
186 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
187 /* Build a map of them */
188 hooks[name.c_str()] = *m;
189 hooknames.push_back(name);
193 this->ReadConfiguration(true);
196 SpanningTreeUtilities::~SpanningTreeUtilities()
198 for (unsigned int i = 0; i < Bindings.size(); i++)
200 ServerInstance->SE->DelFd(Bindings[i]);
201 Bindings[i]->Close();
203 while (TreeRoot->ChildCount())
205 TreeServer* child_server = TreeRoot->GetChild(0);
208 TreeSocket* sock = child_server->GetSocket();
209 ServerInstance->SE->DelFd(sock);
214 ServerInstance->InspSocketCull();
217 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
219 if (list.find(server) == list.end())
220 list[server] = server;
223 /* returns a list of DIRECT servernames for a specific channel */
224 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
230 ulist = c->GetOppedUsers();
233 ulist = c->GetHalfoppedUsers();
236 ulist = c->GetVoicedUsers();
239 ulist = c->GetUsers();
242 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
244 if ((i->first->GetFd() < 0) && (exempt_list.find(i->first) == exempt_list.end()))
246 TreeServer* best = this->BestRouteTo(i->first->server);
248 AddThisServer(best,list);
254 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
257 TreeServer* omitroute = this->BestRouteTo(omit);
258 if ((command == "NOTICE") || (command == "PRIVMSG"))
260 if (params.size() >= 2)
263 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
266 params[0] = params[0].substr(1, params[0].length()-1);
268 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
270 // special routing for private messages/notices
271 userrec* d = ServerInstance->FindNick(params[0]);
274 std::deque<std::string> par;
275 par.push_back(params[0]);
276 par.push_back(":"+params[1]);
277 this->DoOneToOne(prefix,command.c_str(),par,d->server);
281 else if (*(params[0].c_str()) == '$')
283 std::deque<std::string> par;
284 par.push_back(params[0]);
285 par.push_back(":"+params[1]);
286 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
291 chanrec* c = ServerInstance->FindChan(params[0]);
292 userrec* u = ServerInstance->FindNick(prefix);
297 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
298 GetListOfServersForChannel(c,list,pfx,elist);
300 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
302 TreeSocket* Sock = i->second->GetSocket();
303 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
305 Sock->WriteLine(data);
313 unsigned int items =this->TreeRoot->ChildCount();
314 for (unsigned int x = 0; x < items; x++)
316 TreeServer* Route = this->TreeRoot->GetChild(x);
317 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
319 TreeSocket* Sock = Route->GetSocket();
321 Sock->WriteLine(data);
327 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
329 TreeServer* omitroute = this->BestRouteTo(omit);
330 std::string FullLine = ":" + prefix + " " + command;
331 unsigned int words = params.size();
332 for (unsigned int x = 0; x < words; x++)
334 FullLine = FullLine + " " + params[x];
336 unsigned int items = this->TreeRoot->ChildCount();
337 for (unsigned int x = 0; x < items; x++)
339 TreeServer* Route = this->TreeRoot->GetChild(x);
341 // The route has a socket (its a direct connection)
342 // The route isnt the one to be omitted
343 // The route isnt the path to the one to be omitted
344 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
346 TreeSocket* Sock = Route->GetSocket();
348 Sock->WriteLine(FullLine);
354 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
356 std::string FullLine = ":" + prefix + " " + command;
357 unsigned int words = params.size();
358 for (unsigned int x = 0; x < words; x++)
360 FullLine = FullLine + " " + params[x];
362 unsigned int items = this->TreeRoot->ChildCount();
363 for (unsigned int x = 0; x < items; x++)
365 TreeServer* Route = this->TreeRoot->GetChild(x);
366 if (Route && Route->GetSocket())
368 TreeSocket* Sock = Route->GetSocket();
370 Sock->WriteLine(FullLine);
376 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
378 std::string spfx = prefix;
379 std::string scmd = command;
380 return this->DoOneToMany(spfx, scmd, params);
383 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
385 std::string spfx = prefix;
386 std::string scmd = command;
387 return this->DoOneToAllButSender(spfx, scmd, params, omit);
390 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
392 TreeServer* Route = this->BestRouteTo(target);
395 std::string FullLine = ":" + prefix + " " + command;
396 unsigned int words = params.size();
397 for (unsigned int x = 0; x < words; x++)
399 FullLine = FullLine + " " + params[x];
401 if (Route && Route->GetSocket())
403 TreeSocket* Sock = Route->GetSocket();
405 Sock->WriteLine(FullLine);
415 void SpanningTreeUtilities::RefreshIPCache()
418 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
420 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
422 ValidIPs.push_back(L->IPAddr);
424 if (L->AllowMask.length())
425 ValidIPs.push_back(L->AllowMask);
427 /* Needs resolving */
429 QueryType start_type = DNS_QUERY_A;
431 start_type = DNS_QUERY_AAAA;
432 if (strchr(L->IPAddr.c_str(),':'))
435 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
442 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
450 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
451 ServerInstance->AddResolver(sr, cached);
461 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
463 ConfigReader* Conf = new ConfigReader(ServerInstance);
466 for (int j = 0; j < Conf->Enumerate("bind"); j++)
468 std::string Type = Conf->ReadValue("bind","type",j);
469 std::string IP = Conf->ReadValue("bind","address",j);
470 std::string Port = Conf->ReadValue("bind","port",j);
471 std::string transport = Conf->ReadValue("bind","transport",j);
472 if (Type == "servers")
474 irc::portparser portrange(Port, false);
476 while ((portno = portrange.GetToken()))
481 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
483 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());
487 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
488 if (listener->GetState() == I_LISTENING)
490 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
491 Bindings.push_back(listener);
495 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
502 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
503 HideULines = Conf->ReadFlag("options","hideulines",0);
504 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
505 EnableTimeSync = Conf->ReadFlag("timesync","enable",0);
506 MasterTime = Conf->ReadFlag("timesync", "master", 0);
507 ChallengeResponse = !Conf->ReadFlag("options", "disablehmac", 0);
508 quiet_bursts = Conf->ReadFlag("options", "quietbursts", 0);
509 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
510 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
515 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
520 for (int j = 0; j < Conf->Enumerate("link"); j++)
523 std::string Allow = Conf->ReadValue("link", "allowmask", j);
524 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
526 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
527 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
528 L.Port = Conf->ReadInteger("link", "port", j, true);
529 L.SendPass = Conf->ReadValue("link", "sendpass", j);
530 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
531 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
532 L.HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
533 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
534 L.Hook = Conf->ReadValue("link", "transport", j);
535 L.Bind = Conf->ReadValue("link", "bind", j);
536 L.Hidden = Conf->ReadFlag("link", "hidden", j);
538 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
540 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.",
541 L.Hook.c_str(), L.Name.c_str());
546 L.NextConnectTime = time(NULL) + L.AutoConnect;
547 /* Bugfix by brain, do not allow people to enter bad configurations */
548 if (L.Name != ServerInstance->Config->ServerName)
550 if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
552 ValidIPs.push_back(L.IPAddr);
555 ValidIPs.push_back(Allow);
557 /* Needs resolving */
559 QueryType start_type = DNS_QUERY_A;
561 start_type = DNS_QUERY_AAAA;
562 if (strchr(L.IPAddr.c_str(),':'))
565 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
571 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
576 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
585 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
586 ServerInstance->AddResolver(sr, cached);
593 LinkBlocks.push_back(L);
597 if (L.IPAddr.empty())
599 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
601 else if (L.RecvPass.empty())
603 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
605 else if (L.SendPass.empty())
607 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
609 else if (L.Name.empty())
611 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
615 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
621 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
627 void SpanningTreeUtilities::DoFailOver(Link* x)
629 if (x->FailOver.length())
631 if (x->FailOver == x->Name)
633 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());
636 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
639 Creator->RemoteMessage(NULL,"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
640 Creator->ConnectServer(TryThisOne);
644 Creator->RemoteMessage(NULL,"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
649 Link* SpanningTreeUtilities::FindLink(const std::string& name)
651 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
653 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))