1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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 this->ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", ip);
52 ServerInstance->SE->Close(newsock);
57 if (this->GetIOHook())
59 this->GetIOHook()->OnRawSocketAccept(newsock, incomingip.c_str(), this->bind_port);
62 /* we don't need a pointer to this, creating it stores it in the necessary places */
63 new TreeSocket(this->Utils, this->ServerInstance, newsock, ip, this->GetIOHook());
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 (this->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(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
154 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
156 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
158 this->ReadConfiguration(true);
161 SpanningTreeUtilities::~SpanningTreeUtilities()
163 for (unsigned int i = 0; i < Bindings.size(); i++)
168 while (TreeRoot->ChildCount())
170 TreeServer* child_server = TreeRoot->GetChild(0);
173 TreeSocket* sock = child_server->GetSocket();
174 ServerInstance->SE->DelFd(sock);
179 ServerInstance->BufferedSocketCull();
182 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
184 if (list.find(server) == list.end())
185 list[server] = server;
188 /* returns a list of DIRECT servernames for a specific channel */
189 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
191 CUList *ulist = c->GetUsers();
193 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
195 if (IS_LOCAL(i->first))
198 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
201 if (exempt_list.find(i->first) == exempt_list.end())
203 TreeServer* best = this->BestRouteTo(i->first->server);
205 AddThisServer(best,list);
211 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
214 TreeServer* omitroute = this->BestRouteTo(omit);
215 if ((command == "NOTICE") || (command == "PRIVMSG"))
217 if (params.size() >= 2)
220 if (ServerInstance->Modes->FindPrefix(params[0][0]))
223 params[0] = params[0].substr(1, params[0].length()-1);
225 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
227 // special routing for private messages/notices
228 User* d = ServerInstance->FindNick(params[0]);
231 std::deque<std::string> par;
232 par.push_back(params[0]);
233 par.push_back(":"+params[1]);
234 this->DoOneToOne(prefix,command.c_str(),par,d->server);
238 else if (*(params[0].c_str()) == '$')
240 std::deque<std::string> par;
241 par.push_back(params[0]);
242 par.push_back(":"+params[1]);
243 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
248 Channel* c = ServerInstance->FindChan(params[0]);
249 User* u = ServerInstance->FindNick(prefix);
254 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist, params[1]));
255 GetListOfServersForChannel(c,list,pfx,elist);
257 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
259 TreeSocket* Sock = i->second->GetSocket();
260 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
262 Sock->WriteLine(data);
270 unsigned int items =this->TreeRoot->ChildCount();
271 for (unsigned int x = 0; x < items; x++)
273 TreeServer* Route = this->TreeRoot->GetChild(x);
274 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
276 TreeSocket* Sock = Route->GetSocket();
278 Sock->WriteLine(data);
284 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
286 TreeServer* omitroute = this->BestRouteTo(omit);
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);
298 // The route has a socket (its a direct connection)
299 // The route isnt the one to be omitted
300 // The route isnt the path to the one to be omitted
301 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
303 TreeSocket* Sock = Route->GetSocket();
305 Sock->WriteLine(FullLine);
311 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
313 std::string FullLine = ":" + prefix + " " + command;
314 unsigned int words = params.size();
315 for (unsigned int x = 0; x < words; x++)
317 FullLine = FullLine + " " + params[x];
319 unsigned int items = this->TreeRoot->ChildCount();
320 for (unsigned int x = 0; x < items; x++)
322 TreeServer* Route = this->TreeRoot->GetChild(x);
323 if (Route && Route->GetSocket())
325 TreeSocket* Sock = Route->GetSocket();
327 Sock->WriteLine(FullLine);
333 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
335 std::string spfx = prefix;
336 std::string scmd = command;
337 return this->DoOneToMany(spfx, scmd, params);
340 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
342 std::string spfx = prefix;
343 std::string scmd = command;
344 return this->DoOneToAllButSender(spfx, scmd, params, omit);
347 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
349 TreeServer* Route = this->BestRouteTo(target);
352 std::string FullLine = ":" + prefix + " " + command;
353 unsigned int words = params.size();
354 for (unsigned int x = 0; x < words; x++)
356 FullLine = FullLine + " " + params[x];
358 if (Route && Route->GetSocket())
360 TreeSocket* Sock = Route->GetSocket();
362 Sock->WriteLine(FullLine);
372 void SpanningTreeUtilities::RefreshIPCache()
375 for (std::vector<Link>::iterator L = LinkBlocks.begin(); L != LinkBlocks.end(); L++)
377 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
381 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
385 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
388 /* Invalid link block */
392 ValidIPs.push_back(L->IPAddr);
394 if (L->AllowMask.length())
395 ValidIPs.push_back(L->AllowMask);
397 /* Needs resolving */
399 QueryType start_type = DNS_QUERY_A;
401 start_type = DNS_QUERY_AAAA;
402 if (strchr(L->IPAddr.c_str(),':'))
405 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
412 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
421 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L->IPAddr, *L, cached, start_type);
422 ServerInstance->AddResolver(sr, cached);
431 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
433 ConfigReader* Conf = new ConfigReader(ServerInstance);
435 /* We don't need to worry about these being *unloaded* on the fly, only loaded,
436 * because we 'use' the interface locking the module in memory.
440 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
442 /* Did we find any modules? */
445 /* Yes, enumerate them all to find out the hook name */
446 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
448 /* Make a request to it for its name, its implementing
449 * BufferedSocketHook so we know its safe to do this
451 std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
452 /* Build a map of them */
453 hooks[name.c_str()] = *m;
454 hooknames.push_back(name);
460 for (unsigned int i = 0; i < Bindings.size(); i++)
464 ServerInstance->BufferedSocketCull();
467 for (int j = 0; j < Conf->Enumerate("bind"); j++)
469 std::string Type = Conf->ReadValue("bind","type",j);
470 std::string IP = Conf->ReadValue("bind","address",j);
471 std::string Port = Conf->ReadValue("bind","port",j);
472 std::string transport = Conf->ReadValue("bind","transport",j);
473 if (Type == "servers")
475 irc::portparser portrange(Port, false);
481 while ((portno = portrange.GetToken()))
483 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
485 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?");
489 ServerSocketListener *listener = new ServerSocketListener(ServerInstance, this, portno, (char *)IP.c_str());
490 if (listener->GetFd() == -1)
496 if (!transport.empty())
497 listener->AddIOHook(hooks[transport.c_str()]);
499 Bindings.push_back(listener);
504 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
505 HideULines = Conf->ReadFlag("security","hideulines",0);
506 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
507 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
508 quiet_bursts = Conf->ReadFlag("performance", "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 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.");
545 // Fix: Only trip autoconnects if this wouldn't delay autoconnect..
546 if (L.NextConnectTime > ((time_t)(ServerInstance->Time() + L.AutoConnect)))
547 L.NextConnectTime = ServerInstance->Time() + L.AutoConnect;
549 if (L.Name.find('.') == std::string::npos)
550 throw CoreException("The link name '"+assign(L.Name)+"' is invalid and must contain at least one '.' character");
552 if (L.Name.length() > 64)
553 throw CoreException("The link name '"+assign(L.Name)+"' is longer than 64 characters!");
555 if ((!L.IPAddr.empty()) && (!L.RecvPass.empty()) && (!L.SendPass.empty()) && (!L.Name.empty()) && (L.Port))
558 ValidIPs.push_back(Allow);
560 ValidIPs.push_back(L.IPAddr);
562 /* Needs resolving */
564 QueryType start_type = DNS_QUERY_A;
566 start_type = DNS_QUERY_AAAA;
567 if (strchr(L.IPAddr.c_str(),':'))
570 if (inet_pton(AF_INET6, L.IPAddr.c_str(), &n) < 1)
576 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
581 if (inet_aton(L.IPAddr.c_str(),&n) < 1)
590 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached, start_type);
591 ServerInstance->AddResolver(sr, cached);
600 if (L.IPAddr.empty())
603 ValidIPs.push_back("*");
604 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.");
607 if (L.RecvPass.empty())
609 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', recvpass not defined!");
612 if (L.SendPass.empty())
614 throw CoreException("Invalid configuration for server '"+assign(L.Name)+"', sendpass not defined!");
619 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L.IPAddr);
624 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.");
628 LinkBlocks.push_back(L);
633 void SpanningTreeUtilities::DoFailOver(Link* x)
635 if (x->FailOver.length())
637 if (x->FailOver == x->Name)
639 this->ServerInstance->SNO->WriteToSnoMask('l', "FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
642 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
645 TreeServer* CheckDupe = this->FindServer(x->FailOver.c_str());
648 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Skipping existing failover: %s", x->FailOver.c_str());
652 this->ServerInstance->SNO->WriteToSnoMask('l', "FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
653 Creator->ConnectServer(TryThisOne);
658 this->ServerInstance->SNO->WriteToSnoMask('l', "FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
663 Link* SpanningTreeUtilities::FindLink(const std::string& name)
665 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
667 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))