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/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 */
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();
75 /** Find the first server matching a given glob mask.
76 * Theres no find-using-glob method of hash_map [awwww :-(]
77 * so instead, we iterate over the list using an iterator
78 * and match each one until we get a hit. Yes its slow,
81 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
83 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
85 if (match(i->first,ServerName))
91 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
93 server_hash::iterator iter = sidlist.find(id);
94 if (iter != sidlist.end())
100 /* A convenient wrapper that returns true if a server exists */
101 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
103 return (FindServer(ServerName) != NULL);
106 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
110 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
112 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
114 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
116 /* Did we find any modules? */
119 /* Yes, enumerate them all to find out the hook name */
120 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
122 /* Make a request to it for its name, its implementing
123 * BufferedSocketHook so we know its safe to do this
125 std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
126 /* Build a map of them */
127 hooks[name.c_str()] = *m;
128 hooknames.push_back(name);
132 this->ReadConfiguration(true);
135 SpanningTreeUtilities::~SpanningTreeUtilities()
137 for (unsigned int i = 0; i < Bindings.size(); i++)
139 ServerInstance->SE->DelFd(Bindings[i]);
140 Bindings[i]->Close();
142 while (TreeRoot->ChildCount())
144 TreeServer* child_server = TreeRoot->GetChild(0);
147 TreeSocket* sock = child_server->GetSocket();
148 ServerInstance->SE->DelFd(sock);
153 ServerInstance->BufferedSocketCull();
156 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
158 if (list.find(server) == list.end())
159 list[server] = server;
162 /* returns a list of DIRECT servernames for a specific channel */
163 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
165 CUList *ulist = c->GetUsers();
167 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
169 if (IS_LOCAL(i->first))
172 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
175 if (exempt_list.find(i->first) == exempt_list.end())
177 TreeServer* best = this->BestRouteTo(i->first->server);
179 AddThisServer(best,list);
185 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
188 TreeServer* omitroute = this->BestRouteTo(omit);
189 if ((command == "NOTICE") || (command == "PRIVMSG"))
191 if (params.size() >= 2)
194 if (ServerInstance->Modes->FindPrefix(params[0][0]))
197 params[0] = params[0].substr(1, params[0].length()-1);
199 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
201 // special routing for private messages/notices
202 User* d = ServerInstance->FindNick(params[0]);
205 std::deque<std::string> par;
206 par.push_back(params[0]);
207 par.push_back(":"+params[1]);
208 this->DoOneToOne(prefix,command.c_str(),par,d->server);
212 else if (*(params[0].c_str()) == '$')
214 std::deque<std::string> par;
215 par.push_back(params[0]);
216 par.push_back(":"+params[1]);
217 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
222 Channel* c = ServerInstance->FindChan(params[0]);
223 User* u = ServerInstance->FindNick(prefix);
228 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
229 GetListOfServersForChannel(c,list,pfx,elist);
231 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
233 TreeSocket* Sock = i->second->GetSocket();
234 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
236 Sock->WriteLine(data);
244 unsigned int items =this->TreeRoot->ChildCount();
245 for (unsigned int x = 0; x < items; x++)
247 TreeServer* Route = this->TreeRoot->GetChild(x);
248 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
250 TreeSocket* Sock = Route->GetSocket();
252 Sock->WriteLine(data);
258 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
260 TreeServer* omitroute = this->BestRouteTo(omit);
261 std::string FullLine = ":" + prefix + " " + command;
262 unsigned int words = params.size();
263 for (unsigned int x = 0; x < words; x++)
265 FullLine = FullLine + " " + params[x];
267 unsigned int items = this->TreeRoot->ChildCount();
268 for (unsigned int x = 0; x < items; x++)
270 TreeServer* Route = this->TreeRoot->GetChild(x);
272 // The route has a socket (its a direct connection)
273 // The route isnt the one to be omitted
274 // The route isnt the path to the one to be omitted
275 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
277 TreeSocket* Sock = Route->GetSocket();
279 Sock->WriteLine(FullLine);
285 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
287 std::string FullLine = ":" + prefix + " " + command;
288 unsigned int words = params.size();
289 for (unsigned int x = 0; x < words; x++)
291 FullLine = FullLine + " " + params[x];
293 unsigned int items = this->TreeRoot->ChildCount();
294 for (unsigned int x = 0; x < items; x++)
296 TreeServer* Route = this->TreeRoot->GetChild(x);
297 if (Route && Route->GetSocket())
299 TreeSocket* Sock = Route->GetSocket();
301 Sock->WriteLine(FullLine);
307 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
309 std::string spfx = prefix;
310 std::string scmd = command;
311 return this->DoOneToMany(spfx, scmd, params);
314 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
316 std::string spfx = prefix;
317 std::string scmd = command;
318 return this->DoOneToAllButSender(spfx, scmd, params, omit);
321 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
323 TreeServer* Route = this->BestRouteTo(target);
326 std::string FullLine = ":" + prefix + " " + command;
327 unsigned int words = params.size();
328 for (unsigned int x = 0; x < words; x++)
330 FullLine = FullLine + " " + params[x];
332 if (Route && Route->GetSocket())
334 TreeSocket* Sock = Route->GetSocket();
336 Sock->WriteLine(FullLine);
346 void SpanningTreeUtilities::RefreshIPCache()
349 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
351 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
355 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
359 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
362 /* Invalid link block */
366 ValidIPs.push_back(L->IPAddr);
368 if (L->AllowMask.length())
369 ValidIPs.push_back(L->AllowMask);
371 /* Needs resolving */
373 QueryType start_type = DNS_QUERY_A;
375 start_type = DNS_QUERY_AAAA;
376 if (strchr(L->IPAddr.c_str(),':'))
379 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
386 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
395 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
396 ServerInstance->AddResolver(sr, cached);
405 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
407 ConfigReader* Conf = new ConfigReader(ServerInstance);
410 for (unsigned int i = 0; i < Bindings.size(); i++)
412 ServerInstance->SE->DelFd(Bindings[i]);
413 Bindings[i]->Close();
415 ServerInstance->BufferedSocketCull();
418 for (int j = 0; j < Conf->Enumerate("bind"); j++)
420 std::string Type = Conf->ReadValue("bind","type",j);
421 std::string IP = Conf->ReadValue("bind","address",j);
422 std::string Port = Conf->ReadValue("bind","port",j);
423 std::string transport = Conf->ReadValue("bind","transport",j);
424 if (Type == "servers")
426 irc::portparser portrange(Port, false);
432 while ((portno = portrange.GetToken()))
434 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
436 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?");
440 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
441 if (listener->GetState() == I_LISTENING)
443 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
444 Bindings.push_back(listener);
448 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Warning: Failed to bind server port: %s:%d: %s",IP.c_str(), portno, strerror(errno));
455 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
456 HideULines = Conf->ReadFlag("security","hideulines",0);
457 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
458 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
459 quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
460 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
461 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
466 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
471 for (int j = 0; j < Conf->Enumerate("link"); j++)
474 std::string Allow = Conf->ReadValue("link", "allowmask", j);
475 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
477 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
478 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
479 L.Port = Conf->ReadInteger("link", "port", j, true);
480 L.SendPass = Conf->ReadValue("link", "sendpass", j);
481 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
482 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
483 L.HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
484 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
485 L.Hook = Conf->ReadValue("link", "transport", j);
486 L.Bind = Conf->ReadValue("link", "bind", j);
487 L.Hidden = Conf->ReadFlag("link", "hidden", j);
489 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
491 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.");
496 L.NextConnectTime = time(NULL) + L.AutoConnect;
497 /* Bugfix by brain, do not allow people to enter bad configurations */
498 if (L.Name != ServerInstance->Config->ServerName)
500 if (L.Name.find('.') == std::string::npos)
501 throw CoreException("The link name '"+assign(L.Name)+"' is invalid and must contain at least one '.' character");
503 if (L.Name.length() > 64)
504 throw CoreException("The link name '"+assign(L.Name)+"' is longer than 64 characters!");
506 if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
509 ValidIPs.push_back(Allow);
511 ValidIPs.push_back(L.IPAddr);
513 /* Needs resolving */
515 QueryType start_type = DNS_QUERY_A;
517 start_type = DNS_QUERY_AAAA;
518 if (strchr(L.IPAddr.c_str(),':'))
521 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
527 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
532 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
541 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
542 ServerInstance->AddResolver(sr, cached);
551 if (L.IPAddr.empty())
554 ValidIPs.push_back("*");
555 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.");
558 if (L.RecvPass.empty())
560 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', recvpass not defined!");
563 if (L.SendPass.empty())
565 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', sendpass not defined!");
570 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L.IPAddr);
575 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.");
580 LinkBlocks.push_back(L);
584 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', link tag has the same server name as the local server!");
590 void SpanningTreeUtilities::DoFailOver(Link* x)
592 if (x->FailOver.length())
594 if (x->FailOver == x->Name)
596 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());
599 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
602 TreeServer* CheckDupe = this->FindServer(x->FailOver.c_str());
605 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Skipping existing failover: %s", x->FailOver.c_str());
609 Creator->RemoteMessage(NULL,"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
610 Creator->ConnectServer(TryThisOne);
615 Creator->RemoteMessage(NULL,"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
620 Link* SpanningTreeUtilities::FindLink(const std::string& name)
622 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
624 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))