1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
17 #include "../transport.h"
18 #include "socketengine.h"
22 #include "treeserver.h"
24 #include "treesocket.h"
25 #include "resolvers.h"
27 /* $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 */
29 /* Create server sockets off a listener. */
30 void ServerSocketListener::OnAcceptReady(int newsock)
34 std::string incomingip;
35 irc::sockets::satoap(&client, incomingip, port);
36 char *ip = const_cast<char*>(incomingip.c_str());
38 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
41 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
43 if (*i == "*" || irc::sockets::MatchCIDR(ip, *i))
52 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", ip);
53 ServerInstance->SE->Close(newsock);
58 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
59 TreeSocket* ts = new TreeSocket(Utils, newsock, ip, NULL, Hook);
62 Hook->OnStreamSocketAccept(ts, &client, &server);
67 /** Yay for fast searches!
68 * This is hundreds of times faster than recursion
69 * or even scanning a linked list, especially when
70 * there are more than a few servers to deal with.
73 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
75 if (ServerInstance->IsSID(ServerName))
76 return this->FindServerID(ServerName);
78 server_hash::iterator iter = serverlist.find(ServerName.c_str());
79 if (iter != serverlist.end())
89 /** Returns the locally connected server we must route a
90 * message through to reach server 'ServerName'. This
91 * only applies to one-to-one and not one-to-many routing.
92 * See the comments for the constructor of TreeServer
95 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
97 if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
99 TreeServer* Found = FindServer(ServerName);
102 return Found->GetRoute();
106 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
107 User *u = ServerInstance->FindNick(ServerName);
110 Found = FindServer(u->server);
112 return Found->GetRoute();
119 /** Find the first server matching a given glob mask.
120 * Theres no find-using-glob method of hash_map [awwww :-(]
121 * so instead, we iterate over the list using an iterator
122 * and match each one until we get a hit. Yes its slow,
125 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
127 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
129 if (InspIRCd::Match(i->first,ServerName))
135 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
137 server_hash::iterator iter = sidlist.find(id);
138 if (iter != sidlist.end())
144 /* A convenient wrapper that returns true if a server exists */
145 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
147 return (FindServer(ServerName) != NULL);
150 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
152 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
154 this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
155 ServerUser = new FakeUser(TreeRoot->GetID());
157 this->ReadConfiguration(true);
160 bool SpanningTreeUtilities::cull()
162 for (unsigned int i = 0; i < Bindings.size(); i++)
167 while (TreeRoot->ChildCount())
169 TreeServer* child_server = TreeRoot->GetChild(0);
172 TreeSocket* sock = child_server->GetSocket();
177 ServerUser->uuid = TreeRoot->GetID();
178 if (ServerUser->cull())
183 SpanningTreeUtilities::~SpanningTreeUtilities()
185 for (unsigned int i = 0; i < Bindings.size(); i++)
193 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
195 if (list.find(server) == list.end())
196 list[server] = server;
199 /* returns a list of DIRECT servernames for a specific channel */
200 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
202 const UserMembList *ulist = c->GetUsers();
204 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
206 if (IS_LOCAL(i->first))
209 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
212 if (exempt_list.find(i->first) == exempt_list.end())
214 TreeServer* best = this->BestRouteTo(i->first->server);
216 AddThisServer(best,list);
222 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist ¶ms)
225 TreeServer* omitroute = this->BestRouteTo(omit);
226 if ((command == "NOTICE") || (command == "PRIVMSG"))
228 if (params.size() >= 2)
231 if (ServerInstance->Modes->FindPrefix(params[0][0]))
234 params[0] = params[0].substr(1, params[0].length()-1);
236 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
238 // special routing for private messages/notices
239 User* d = ServerInstance->FindNick(params[0]);
243 par.push_back(params[0]);
244 par.push_back(":"+params[1]);
245 this->DoOneToOne(prefix,command.c_str(),par,d->server);
249 else if (*(params[0].c_str()) == '$')
252 par.push_back(params[0]);
253 par.push_back(":"+params[1]);
254 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
259 Channel* c = ServerInstance->FindChan(params[0]);
260 User* u = ServerInstance->FindNick(prefix);
265 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
266 GetListOfServersForChannel(c,list,pfx,elist);
268 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
270 TreeSocket* Sock = i->second->GetSocket();
271 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
273 Sock->WriteLine(data);
281 unsigned int items =this->TreeRoot->ChildCount();
282 for (unsigned int x = 0; x < items; x++)
284 TreeServer* Route = this->TreeRoot->GetChild(x);
285 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
287 TreeSocket* Sock = Route->GetSocket();
289 Sock->WriteLine(data);
295 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string omit)
297 TreeServer* omitroute = this->BestRouteTo(omit);
298 std::string FullLine = ":" + prefix + " " + command;
299 unsigned int words = params.size();
300 for (unsigned int x = 0; x < words; x++)
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, parameterlist ¶ms)
324 std::string FullLine = ":" + prefix + " " + command;
325 unsigned int words = params.size();
326 for (unsigned int x = 0; x < words; x++)
328 FullLine = FullLine + " " + params[x];
330 unsigned int items = this->TreeRoot->ChildCount();
331 for (unsigned int x = 0; x < items; x++)
333 TreeServer* Route = this->TreeRoot->GetChild(x);
334 if (Route && Route->GetSocket())
336 TreeSocket* Sock = Route->GetSocket();
338 Sock->WriteLine(FullLine);
344 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist ¶ms)
346 std::string spfx = prefix;
347 std::string scmd = command;
348 return this->DoOneToMany(spfx, scmd, params);
351 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist ¶ms, std::string omit)
353 std::string spfx = prefix;
354 std::string scmd = command;
355 return this->DoOneToAllButSender(spfx, scmd, params, omit);
358 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string target)
360 TreeServer* Route = this->BestRouteTo(target);
363 std::string FullLine = ":" + prefix + " " + command;
364 unsigned int words = params.size();
365 for (unsigned int x = 0; x < words; x++)
367 FullLine = FullLine + " " + params[x];
369 if (Route && Route->GetSocket())
371 TreeSocket* Sock = Route->GetSocket();
373 Sock->WriteLine(FullLine);
383 void SpanningTreeUtilities::RefreshIPCache()
386 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
388 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
392 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
396 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
399 /* Invalid link block */
403 ValidIPs.push_back(L->IPAddr);
405 if (L->AllowMask.length())
406 ValidIPs.push_back(L->AllowMask);
408 /* Needs resolving */
410 QueryType start_type = DNS_QUERY_A;
411 start_type = DNS_QUERY_AAAA;
412 if (strchr(L->IPAddr.c_str(),':'))
415 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
421 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
430 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, *L, cached, start_type);
431 ServerInstance->AddResolver(sr, cached);
440 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
442 ConfigReader* Conf = new ConfigReader;
444 /* We don't need to worry about these being *unloaded* on the fly, only loaded,
445 * because we 'use' the interface locking the module in memory.
449 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
451 /* Did we find any modules? */
454 /* Yes, enumerate them all to find out the hook name */
455 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
457 /* Make a request to it for its name, its implementing
458 * BufferedSocketHook so we know its safe to do this
460 std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
461 /* Build a map of them */
462 hooks[name.c_str()] = *m;
463 hooknames.push_back(name);
469 for (unsigned int i = 0; i < Bindings.size(); i++)
475 for (int j = 0; j < Conf->Enumerate("bind"); j++)
477 std::string Type = Conf->ReadValue("bind","type",j);
478 std::string IP = Conf->ReadValue("bind","address",j);
479 std::string Port = Conf->ReadValue("bind","port",j);
480 std::string transport = Conf->ReadValue("bind","transport",j);
481 if (Type == "servers")
483 irc::portparser portrange(Port, false);
489 while ((portno = portrange.GetToken()))
491 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
493 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?");
497 ServerSocketListener *listener = new ServerSocketListener(this, portno, (char *)IP.c_str());
498 if (listener->GetFd() == -1)
504 if (!transport.empty())
505 listener->Hook = hooks[transport.c_str()];
507 Bindings.push_back(listener);
512 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
513 HideULines = Conf->ReadFlag("security","hideulines",0);
514 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
515 AllowOptCommon = Conf->ReadFlag("options", "allowmismatch", 0);
516 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
517 quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
518 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
519 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
524 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
527 AutoconnectBlocks.clear();
530 for (int j = 0; j < Conf->Enumerate("link"); ++j)
533 std::string Allow = Conf->ReadValue("link", "allowmask", j);
534 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
536 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
537 L.Port = Conf->ReadInteger("link", "port", j, true);
538 L.SendPass = Conf->ReadValue("link", "sendpass", j);
539 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
540 L.Fingerprint = Conf->ReadValue("link", "fingerprint", j);
541 L.HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
542 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
543 L.Hook = Conf->ReadValue("link", "transport", j);
544 L.Bind = Conf->ReadValue("link", "bind", j);
545 L.Hidden = Conf->ReadFlag("link", "hidden", j);
547 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
549 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.");
554 if (L.Name.find('.') == std::string::npos)
555 throw CoreException("The link name '"+assign(L.Name)+"' is invalid and must contain at least one '.' character");
557 if (L.Name.length() > 64)
558 throw CoreException("The link name '"+assign(L.Name)+"' is longer than 64 characters!");
560 if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
563 ValidIPs.push_back(Allow);
565 ValidIPs.push_back(L.IPAddr);
567 /* Needs resolving */
569 QueryType start_type = DNS_QUERY_A;
570 start_type = DNS_QUERY_AAAA;
571 if (strchr(L.IPAddr.c_str(),':'))
574 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
580 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
589 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L.IPAddr, L, cached, start_type);
590 ServerInstance->AddResolver(sr, cached);
599 if (L.IPAddr.empty())
602 ValidIPs.push_back("*");
603 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.");
606 if (L.RecvPass.empty())
608 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', recvpass not defined!");
611 if (L.SendPass.empty())
613 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', sendpass not defined!");
618 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L.IPAddr);
623 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.");
627 LinkBlocks.push_back(L);
630 for (int j = 0; j < Conf->Enumerate("autoconnect"); ++j)
633 A.Period = Conf->ReadInteger("autoconnect", "period", j, true);
634 A.Server = Conf->ReadValue("autoconnect", "server", j);
635 A.FailOver = Conf->ReadValue("autoconnect", "failover", j).c_str();
637 // Fix: Only trip autoconnects if this wouldn't delay autoconnect..
638 if (A.NextConnectTime > ((time_t)(ServerInstance->Time() + A.Period)))
639 A.NextConnectTime = ServerInstance->Time() + A.Period;
643 throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
646 if (A.Server.empty())
648 throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
651 AutoconnectBlocks.push_back(A);
657 void SpanningTreeUtilities::DoFailOver(Autoconnect* x)
659 if (x && x->FailOver.length())
661 if (x->FailOver == x->Server)
663 ServerInstance->SNO->WriteToSnoMask('l', "FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Server.c_str());
666 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
669 TreeServer* CheckDupe = this->FindServer(x->FailOver.c_str());
672 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Skipping existing failover: %s", x->FailOver.c_str());
676 ServerInstance->SNO->WriteToSnoMask('l', "FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Server.c_str(), TryThisOne->Name.c_str());
677 Creator->ConnectServer(TryThisOne, NULL);
682 ServerInstance->SNO->WriteToSnoMask('l', "FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Server.c_str());
687 Link* SpanningTreeUtilities::FindLink(const std::string& name)
689 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x != LinkBlocks.end(); x++)
691 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))