1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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 "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
20 #include "transport.h"
21 #include "socketengine.h"
23 #include "m_spanningtree/main.h"
24 #include "m_spanningtree/utils.h"
25 #include "m_spanningtree/treeserver.h"
26 #include "m_spanningtree/link.h"
27 #include "m_spanningtree/treesocket.h"
28 #include "m_spanningtree/resolvers.h"
30 /* $ModDep: m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
32 /** Yay for fast searches!
33 * This is hundreds of times faster than recursion
34 * or even scanning a linked list, especially when
35 * there are more than a few servers to deal with.
38 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
40 if (this->ServerInstance->IsSID(ServerName))
41 return this->FindServerID(ServerName);
43 server_hash::iterator iter = serverlist.find(ServerName.c_str());
44 if (iter != serverlist.end())
54 /** Returns the locally connected server we must route a
55 * message through to reach server 'ServerName'. This
56 * only applies to one-to-one and not one-to-many routing.
57 * See the comments for the constructor of TreeServer
60 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
62 if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
64 TreeServer* Found = FindServer(ServerName);
67 return Found->GetRoute();
71 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
72 User *u = ServerInstance->FindNick(ServerName);
75 Found = FindServer(u->server);
77 return Found->GetRoute();
84 /** Find the first server matching a given glob mask.
85 * Theres no find-using-glob method of hash_map [awwww :-(]
86 * so instead, we iterate over the list using an iterator
87 * and match each one until we get a hit. Yes its slow,
90 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
92 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
94 if (match(i->first,ServerName))
100 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
102 server_hash::iterator iter = sidlist.find(id);
103 if (iter != sidlist.end())
109 /* A convenient wrapper that returns true if a server exists */
110 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
112 return (FindServer(ServerName) != NULL);
115 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
119 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
121 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
123 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
125 /* Did we find any modules? */
128 /* Yes, enumerate them all to find out the hook name */
129 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
131 /* Make a request to it for its name, its implementing
132 * BufferedSocketHook so we know its safe to do this
134 std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
135 /* Build a map of them */
136 hooks[name.c_str()] = *m;
137 hooknames.push_back(name);
141 this->ReadConfiguration(true);
144 SpanningTreeUtilities::~SpanningTreeUtilities()
146 for (unsigned int i = 0; i < Bindings.size(); i++)
148 ServerInstance->SE->DelFd(Bindings[i]);
149 Bindings[i]->Close();
151 while (TreeRoot->ChildCount())
153 TreeServer* child_server = TreeRoot->GetChild(0);
156 TreeSocket* sock = child_server->GetSocket();
157 ServerInstance->SE->DelFd(sock);
162 ServerInstance->BufferedSocketCull();
165 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
167 if (list.find(server) == list.end())
168 list[server] = server;
171 /* returns a list of DIRECT servernames for a specific channel */
172 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
174 CUList *ulist = c->GetUsers();
176 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
178 if (IS_LOCAL(i->first))
181 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
184 if (exempt_list.find(i->first) == exempt_list.end())
186 TreeServer* best = this->BestRouteTo(i->first->server);
188 AddThisServer(best,list);
194 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
197 TreeServer* omitroute = this->BestRouteTo(omit);
198 if ((command == "NOTICE") || (command == "PRIVMSG"))
200 if (params.size() >= 2)
203 if (ServerInstance->Modes->FindPrefix(params[0][0]))
206 params[0] = params[0].substr(1, params[0].length()-1);
208 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
210 // special routing for private messages/notices
211 User* d = ServerInstance->FindNick(params[0]);
214 std::deque<std::string> par;
215 par.push_back(params[0]);
216 par.push_back(":"+params[1]);
217 this->DoOneToOne(prefix,command.c_str(),par,d->server);
221 else if (*(params[0].c_str()) == '$')
223 std::deque<std::string> par;
224 par.push_back(params[0]);
225 par.push_back(":"+params[1]);
226 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
231 Channel* c = ServerInstance->FindChan(params[0]);
232 User* u = ServerInstance->FindNick(prefix);
237 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
238 GetListOfServersForChannel(c,list,pfx,elist);
240 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
242 TreeSocket* Sock = i->second->GetSocket();
243 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
245 Sock->WriteLine(data);
253 unsigned int items =this->TreeRoot->ChildCount();
254 for (unsigned int x = 0; x < items; x++)
256 TreeServer* Route = this->TreeRoot->GetChild(x);
257 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
259 TreeSocket* Sock = Route->GetSocket();
261 Sock->WriteLine(data);
267 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
269 TreeServer* omitroute = this->BestRouteTo(omit);
270 std::string FullLine = ":" + prefix + " " + command;
271 unsigned int words = params.size();
272 for (unsigned int x = 0; x < words; x++)
274 FullLine = FullLine + " " + params[x];
276 unsigned int items = this->TreeRoot->ChildCount();
277 for (unsigned int x = 0; x < items; x++)
279 TreeServer* Route = this->TreeRoot->GetChild(x);
281 // The route has a socket (its a direct connection)
282 // The route isnt the one to be omitted
283 // The route isnt the path to the one to be omitted
284 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
286 TreeSocket* Sock = Route->GetSocket();
288 Sock->WriteLine(FullLine);
294 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
296 std::string FullLine = ":" + prefix + " " + command;
297 unsigned int words = params.size();
298 for (unsigned int x = 0; x < words; x++)
300 FullLine = FullLine + " " + params[x];
302 unsigned int items = this->TreeRoot->ChildCount();
303 for (unsigned int x = 0; x < items; x++)
305 TreeServer* Route = this->TreeRoot->GetChild(x);
306 if (Route && Route->GetSocket())
308 TreeSocket* Sock = Route->GetSocket();
310 Sock->WriteLine(FullLine);
316 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
318 std::string spfx = prefix;
319 std::string scmd = command;
320 return this->DoOneToMany(spfx, scmd, params);
323 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
325 std::string spfx = prefix;
326 std::string scmd = command;
327 return this->DoOneToAllButSender(spfx, scmd, params, omit);
330 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
332 TreeServer* Route = this->BestRouteTo(target);
335 std::string FullLine = ":" + prefix + " " + command;
336 unsigned int words = params.size();
337 for (unsigned int x = 0; x < words; x++)
339 FullLine = FullLine + " " + params[x];
341 if (Route && Route->GetSocket())
343 TreeSocket* Sock = Route->GetSocket();
345 Sock->WriteLine(FullLine);
355 void SpanningTreeUtilities::RefreshIPCache()
358 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
360 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
364 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
368 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
371 /* Invalid link block */
375 ValidIPs.push_back(L->IPAddr);
377 if (L->AllowMask.length())
378 ValidIPs.push_back(L->AllowMask);
380 /* Needs resolving */
382 QueryType start_type = DNS_QUERY_A;
384 start_type = DNS_QUERY_AAAA;
385 if (strchr(L->IPAddr.c_str(),':'))
388 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
395 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
404 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
405 ServerInstance->AddResolver(sr, cached);
414 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
416 ConfigReader* Conf = new ConfigReader(ServerInstance);
419 for (unsigned int i = 0; i < Bindings.size(); i++)
421 ServerInstance->SE->DelFd(Bindings[i]);
422 Bindings[i]->Close();
424 ServerInstance->BufferedSocketCull();
427 for (int j = 0; j < Conf->Enumerate("bind"); j++)
429 std::string Type = Conf->ReadValue("bind","type",j);
430 std::string IP = Conf->ReadValue("bind","address",j);
431 std::string Port = Conf->ReadValue("bind","port",j);
432 std::string transport = Conf->ReadValue("bind","transport",j);
433 if (Type == "servers")
435 irc::portparser portrange(Port, false);
441 while ((portno = portrange.GetToken()))
443 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
445 throw CoreException("Can't find transport type '"+transport+"' for port "+IP+":"+Port+" - maybe you forgot to load it BEFORE m_spanningtree in your config file?");
449 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
450 if (listener->GetState() == I_LISTENING)
452 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
453 Bindings.push_back(listener);
457 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
464 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
465 HideULines = Conf->ReadFlag("security","hideulines",0);
466 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
467 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
468 quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
469 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
470 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
475 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
480 for (int j = 0; j < Conf->Enumerate("link"); j++)
483 std::string Allow = Conf->ReadValue("link", "allowmask", j);
484 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
486 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
487 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
488 L.Port = Conf->ReadInteger("link", "port", j, true);
489 L.SendPass = Conf->ReadValue("link", "sendpass", j);
490 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
491 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
492 L.HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
493 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
494 L.Hook = Conf->ReadValue("link", "transport", j);
495 L.Bind = Conf->ReadValue("link", "bind", j);
496 L.Hidden = Conf->ReadFlag("link", "hidden", j);
498 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
500 throw CoreException("Can't find transport type '"+L.Hook+"' for link '"+assign(L.Name)+"' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping <link> tag completely.");
505 L.NextConnectTime = time(NULL) + L.AutoConnect;
506 /* Bugfix by brain, do not allow people to enter bad configurations */
507 if (L.Name != ServerInstance->Config->ServerName)
509 if (L.Name.find('.') == std::string::npos)
510 throw CoreException("The link name '"+assign(L.Name)+"' is invalid and must contain at least one '.' character");
512 if (L.Name.length() > 64)
513 throw CoreException("The link name '"+assign(L.Name)+"' is longer than 64 characters!");
515 if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
518 ValidIPs.push_back(Allow);
520 ValidIPs.push_back(L.IPAddr);
522 /* Needs resolving */
524 QueryType start_type = DNS_QUERY_A;
526 start_type = DNS_QUERY_AAAA;
527 if (strchr(L.IPAddr.c_str(),':'))
530 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
536 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
541 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
550 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
551 ServerInstance->AddResolver(sr, cached);
560 if (L.IPAddr.empty())
563 ValidIPs.push_back("*");
564 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block " + assign(L.Name) + " has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want.");
567 if (L.RecvPass.empty())
569 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', recvpass not defined!");
572 if (L.SendPass.empty())
574 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', sendpass not defined!");
579 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L.IPAddr);
584 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block " + assign(L.Name) + " has no port defined, you will not be able to /connect it.");
589 LinkBlocks.push_back(L);
593 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', link tag has the same server name as the local server!");
599 void SpanningTreeUtilities::DoFailOver(Link* x)
601 if (x->FailOver.length())
603 if (x->FailOver == x->Name)
605 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());
608 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
611 TreeServer* CheckDupe = this->FindServer(x->FailOver.c_str());
614 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Skipping existing failover: %s", x->FailOver.c_str());
618 Creator->RemoteMessage(NULL,"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
619 Creator->ConnectServer(TryThisOne);
624 Creator->RemoteMessage(NULL,"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
629 Link* SpanningTreeUtilities::FindLink(const std::string& name)
631 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
633 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))