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"
19 #include "transport.h"
20 #include "socketengine.h"
22 #include "m_spanningtree/main.h"
23 #include "m_spanningtree/utils.h"
24 #include "m_spanningtree/treeserver.h"
25 #include "m_spanningtree/link.h"
26 #include "m_spanningtree/treesocket.h"
27 #include "m_spanningtree/resolvers.h"
29 /* $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 */
31 /* Create server sockets off a listener. */
32 void ServerSocketListener::OnAcceptReady(const std::string &ipconnectedto, int newsock, const std::string &incomingip)
35 char *ip = (char *)incomingip.c_str(); // XXX ugly cast
37 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
40 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
42 if (*i == "*" || irc::sockets::MatchCIDR(ip, *i))
51 Utils->Creator->RemoteMessage(NULL,"Server connection from %s denied (no link blocks with that IP address)", ip);
52 ServerInstance->SE->Close(newsock);
57 /* we don't need a pointer to this, creating it stores it in the necessary places */
58 new TreeSocket(this->Utils, this->ServerInstance, newsock, ip, this->GetIOHook());
62 /** Yay for fast searches!
63 * This is hundreds of times faster than recursion
64 * or even scanning a linked list, especially when
65 * there are more than a few servers to deal with.
68 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
70 if (this->ServerInstance->IsSID(ServerName))
71 return this->FindServerID(ServerName);
73 server_hash::iterator iter = serverlist.find(ServerName.c_str());
74 if (iter != serverlist.end())
84 /** Returns the locally connected server we must route a
85 * message through to reach server 'ServerName'. This
86 * only applies to one-to-one and not one-to-many routing.
87 * See the comments for the constructor of TreeServer
90 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
92 if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
94 TreeServer* Found = FindServer(ServerName);
97 return Found->GetRoute();
101 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
102 User *u = ServerInstance->FindNick(ServerName);
105 Found = FindServer(u->server);
107 return Found->GetRoute();
114 /** Find the first server matching a given glob mask.
115 * Theres no find-using-glob method of hash_map [awwww :-(]
116 * so instead, we iterate over the list using an iterator
117 * and match each one until we get a hit. Yes its slow,
120 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
122 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
124 if (InspIRCd::Match(i->first,ServerName))
130 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
132 server_hash::iterator iter = sidlist.find(id);
133 if (iter != sidlist.end())
139 /* A convenient wrapper that returns true if a server exists */
140 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
142 return (FindServer(ServerName) != NULL);
145 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
149 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
151 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
153 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
155 /* Did we find any modules? */
158 /* Yes, enumerate them all to find out the hook name */
159 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
161 /* Make a request to it for its name, its implementing
162 * BufferedSocketHook so we know its safe to do this
164 std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
165 /* Build a map of them */
166 hooks[name.c_str()] = *m;
167 hooknames.push_back(name);
171 this->ReadConfiguration(true);
174 SpanningTreeUtilities::~SpanningTreeUtilities()
176 for (unsigned int i = 0; i < Bindings.size(); i++)
181 while (TreeRoot->ChildCount())
183 TreeServer* child_server = TreeRoot->GetChild(0);
186 TreeSocket* sock = child_server->GetSocket();
187 ServerInstance->SE->DelFd(sock);
192 ServerInstance->BufferedSocketCull();
195 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
197 if (list.find(server) == list.end())
198 list[server] = server;
201 /* returns a list of DIRECT servernames for a specific channel */
202 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
204 CUList *ulist = c->GetUsers();
206 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
208 if (IS_LOCAL(i->first))
211 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
214 if (exempt_list.find(i->first) == exempt_list.end())
216 TreeServer* best = this->BestRouteTo(i->first->server);
218 AddThisServer(best,list);
224 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
227 TreeServer* omitroute = this->BestRouteTo(omit);
228 if ((command == "NOTICE") || (command == "PRIVMSG"))
230 if (params.size() >= 2)
233 if (ServerInstance->Modes->FindPrefix(params[0][0]))
236 params[0] = params[0].substr(1, params[0].length()-1);
238 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
240 // special routing for private messages/notices
241 User* d = ServerInstance->FindNick(params[0]);
244 std::deque<std::string> par;
245 par.push_back(params[0]);
246 par.push_back(":"+params[1]);
247 this->DoOneToOne(prefix,command.c_str(),par,d->server);
251 else if (*(params[0].c_str()) == '$')
253 std::deque<std::string> par;
254 par.push_back(params[0]);
255 par.push_back(":"+params[1]);
256 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
261 Channel* c = ServerInstance->FindChan(params[0]);
262 User* u = ServerInstance->FindNick(prefix);
267 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
268 GetListOfServersForChannel(c,list,pfx,elist);
270 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
272 TreeSocket* Sock = i->second->GetSocket();
273 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
275 Sock->WriteLine(data);
283 unsigned int items =this->TreeRoot->ChildCount();
284 for (unsigned int x = 0; x < items; x++)
286 TreeServer* Route = this->TreeRoot->GetChild(x);
287 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
289 TreeSocket* Sock = Route->GetSocket();
291 Sock->WriteLine(data);
297 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
299 TreeServer* omitroute = this->BestRouteTo(omit);
300 std::string FullLine = ":" + prefix + " " + command;
301 unsigned int words = params.size();
302 for (unsigned int x = 0; x < words; x++)
304 FullLine = FullLine + " " + params[x];
306 unsigned int items = this->TreeRoot->ChildCount();
307 for (unsigned int x = 0; x < items; x++)
309 TreeServer* Route = this->TreeRoot->GetChild(x);
311 // The route has a socket (its a direct connection)
312 // The route isnt the one to be omitted
313 // The route isnt the path to the one to be omitted
314 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
316 TreeSocket* Sock = Route->GetSocket();
318 Sock->WriteLine(FullLine);
324 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
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 unsigned int items = this->TreeRoot->ChildCount();
333 for (unsigned int x = 0; x < items; x++)
335 TreeServer* Route = this->TreeRoot->GetChild(x);
336 if (Route && Route->GetSocket())
338 TreeSocket* Sock = Route->GetSocket();
340 Sock->WriteLine(FullLine);
346 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
348 std::string spfx = prefix;
349 std::string scmd = command;
350 return this->DoOneToMany(spfx, scmd, params);
353 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
355 std::string spfx = prefix;
356 std::string scmd = command;
357 return this->DoOneToAllButSender(spfx, scmd, params, omit);
360 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
362 TreeServer* Route = this->BestRouteTo(target);
365 std::string FullLine = ":" + prefix + " " + command;
366 unsigned int words = params.size();
367 for (unsigned int x = 0; x < words; x++)
369 FullLine = FullLine + " " + params[x];
371 if (Route && Route->GetSocket())
373 TreeSocket* Sock = Route->GetSocket();
375 Sock->WriteLine(FullLine);
385 void SpanningTreeUtilities::RefreshIPCache()
388 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
390 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
394 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
398 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
401 /* Invalid link block */
405 ValidIPs.push_back(L->IPAddr);
407 if (L->AllowMask.length())
408 ValidIPs.push_back(L->AllowMask);
410 /* Needs resolving */
412 QueryType start_type = DNS_QUERY_A;
414 start_type = DNS_QUERY_AAAA;
415 if (strchr(L->IPAddr.c_str(),':'))
418 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
425 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
434 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
435 ServerInstance->AddResolver(sr, cached);
444 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
446 ConfigReader* Conf = new ConfigReader(ServerInstance);
449 for (unsigned int i = 0; i < Bindings.size(); i++)
453 ServerInstance->BufferedSocketCull();
456 for (int j = 0; j < Conf->Enumerate("bind"); j++)
458 std::string Type = Conf->ReadValue("bind","type",j);
459 std::string IP = Conf->ReadValue("bind","address",j);
460 std::string Port = Conf->ReadValue("bind","port",j);
461 std::string transport = Conf->ReadValue("bind","transport",j);
462 if (Type == "servers")
464 irc::portparser portrange(Port, false);
470 while ((portno = portrange.GetToken()))
472 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
474 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?");
478 ServerSocketListener *listener = new ServerSocketListener(ServerInstance, this, portno, (char *)IP.c_str());
479 if (listener->GetFd() == -1)
485 if (!transport.empty())
486 listener->AddIOHook(hooks[transport.c_str()]);
488 Bindings.push_back(listener);
493 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
494 HideULines = Conf->ReadFlag("security","hideulines",0);
495 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
496 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
497 quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
498 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
499 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
504 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
509 for (int j = 0; j < Conf->Enumerate("link"); j++)
512 std::string Allow = Conf->ReadValue("link", "allowmask", j);
513 L.Name = (Conf->ReadValue("link", "name", j)).c_str();
515 L.IPAddr = Conf->ReadValue("link", "ipaddr", j);
516 L.FailOver = Conf->ReadValue("link", "failover", j).c_str();
517 L.Port = Conf->ReadInteger("link", "port", j, true);
518 L.SendPass = Conf->ReadValue("link", "sendpass", j);
519 L.RecvPass = Conf->ReadValue("link", "recvpass", j);
520 L.AutoConnect = Conf->ReadInteger("link", "autoconnect", j, true);
521 L.HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
522 L.Timeout = Conf->ReadInteger("link", "timeout", j, true);
523 L.Hook = Conf->ReadValue("link", "transport", j);
524 L.Bind = Conf->ReadValue("link", "bind", j);
525 L.Hidden = Conf->ReadFlag("link", "hidden", j);
527 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
529 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.");
534 L.NextConnectTime = time(NULL) + L.AutoConnect;
536 if (L.Name.find('.') == std::string::npos)
537 throw CoreException("The link name '"+assign(L.Name)+"' is invalid and must contain at least one '.' character");
539 if (L.Name.length() > 64)
540 throw CoreException("The link name '"+assign(L.Name)+"' is longer than 64 characters!");
542 if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
545 ValidIPs.push_back(Allow);
547 ValidIPs.push_back(L.IPAddr);
549 /* Needs resolving */
551 QueryType start_type = DNS_QUERY_A;
553 start_type = DNS_QUERY_AAAA;
554 if (strchr(L.IPAddr.c_str(),':'))
557 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
563 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
568 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
577 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
578 ServerInstance->AddResolver(sr, cached);
587 if (L.IPAddr.empty())
590 ValidIPs.push_back("*");
591 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.");
594 if (L.RecvPass.empty())
596 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', recvpass not defined!");
599 if (L.SendPass.empty())
601 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', sendpass not defined!");
606 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L.IPAddr);
611 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.");
615 LinkBlocks.push_back(L);
620 void SpanningTreeUtilities::DoFailOver(Link* x)
622 if (x->FailOver.length())
624 if (x->FailOver == x->Name)
626 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());
629 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
632 TreeServer* CheckDupe = this->FindServer(x->FailOver.c_str());
635 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Skipping existing failover: %s", 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);
645 Creator->RemoteMessage(NULL,"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
650 Link* SpanningTreeUtilities::FindLink(const std::string& name)
652 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
654 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))