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();
174 ServerInstance->GlobalCulls.AddItem(sock);
178 ServerUser->uuid = TreeRoot->GetID();
179 if (ServerUser->cull())
184 SpanningTreeUtilities::~SpanningTreeUtilities()
186 for (unsigned int i = 0; i < Bindings.size(); i++)
194 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
196 if (list.find(server) == list.end())
197 list[server] = server;
200 /* returns a list of DIRECT servernames for a specific channel */
201 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
203 const UserMembList *ulist = c->GetUsers();
205 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
207 if (IS_LOCAL(i->first))
210 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
213 if (exempt_list.find(i->first) == exempt_list.end())
215 TreeServer* best = this->BestRouteTo(i->first->server);
217 AddThisServer(best,list);
223 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 unsigned int items =this->TreeRoot->ChildCount();
227 for (unsigned int x = 0; x < items; x++)
229 TreeServer* Route = this->TreeRoot->GetChild(x);
230 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
232 TreeSocket* Sock = Route->GetSocket();
234 Sock->WriteLine(data);
240 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string omit)
242 TreeServer* omitroute = this->BestRouteTo(omit);
243 std::string FullLine = ":" + prefix + " " + command;
244 unsigned int words = params.size();
245 for (unsigned int x = 0; x < words; x++)
247 FullLine = FullLine + " " + params[x];
249 unsigned int items = this->TreeRoot->ChildCount();
250 for (unsigned int x = 0; x < items; x++)
252 TreeServer* Route = this->TreeRoot->GetChild(x);
254 // The route has a socket (its a direct connection)
255 // The route isnt the one to be omitted
256 // The route isnt the path to the one to be omitted
257 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
259 TreeSocket* Sock = Route->GetSocket();
261 Sock->WriteLine(FullLine);
267 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist ¶ms)
269 std::string FullLine = ":" + prefix + " " + command;
270 unsigned int words = params.size();
271 for (unsigned int x = 0; x < words; x++)
273 FullLine = FullLine + " " + params[x];
275 unsigned int items = this->TreeRoot->ChildCount();
276 for (unsigned int x = 0; x < items; x++)
278 TreeServer* Route = this->TreeRoot->GetChild(x);
279 if (Route && Route->GetSocket())
281 TreeSocket* Sock = Route->GetSocket();
283 Sock->WriteLine(FullLine);
289 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist ¶ms)
291 std::string spfx = prefix;
292 std::string scmd = command;
293 return this->DoOneToMany(spfx, scmd, params);
296 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist ¶ms, std::string omit)
298 std::string spfx = prefix;
299 std::string scmd = command;
300 return this->DoOneToAllButSender(spfx, scmd, params, omit);
303 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string target)
305 TreeServer* Route = this->BestRouteTo(target);
308 std::string FullLine = ":" + prefix + " " + command;
309 unsigned int words = params.size();
310 for (unsigned int x = 0; x < words; x++)
312 FullLine = FullLine + " " + params[x];
314 if (Route && Route->GetSocket())
316 TreeSocket* Sock = Route->GetSocket();
318 Sock->WriteLine(FullLine);
328 void SpanningTreeUtilities::RefreshIPCache()
331 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
334 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
338 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
342 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
345 /* Invalid link block */
349 ValidIPs.push_back(L->IPAddr);
351 if (L->AllowMask.length())
352 ValidIPs.push_back(L->AllowMask);
354 /* Needs resolving */
356 QueryType start_type = DNS_QUERY_A;
357 start_type = DNS_QUERY_AAAA;
358 if (strchr(L->IPAddr.c_str(),':'))
361 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
367 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
376 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
377 ServerInstance->AddResolver(sr, cached);
386 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
388 ConfigReader* Conf = new ConfigReader;
390 /* We don't need to worry about these being *unloaded* on the fly, only loaded,
391 * because we 'use' the interface locking the module in memory.
395 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
397 /* Did we find any modules? */
400 /* Yes, enumerate them all to find out the hook name */
401 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
403 /* Make a request to it for its name, its implementing
404 * BufferedSocketHook so we know its safe to do this
406 std::string name = BufferedSocketNameRequest((Module*)Creator, *m).Send();
407 /* Build a map of them */
408 hooks[name.c_str()] = *m;
409 hooknames.push_back(name);
415 for (unsigned int i = 0; i < Bindings.size(); i++)
421 for (int j = 0; j < Conf->Enumerate("bind"); j++)
423 std::string Type = Conf->ReadValue("bind","type",j);
424 std::string IP = Conf->ReadValue("bind","address",j);
425 std::string Port = Conf->ReadValue("bind","port",j);
426 std::string transport = Conf->ReadValue("bind","transport",j);
427 if (Type == "servers")
429 irc::portparser portrange(Port, false);
435 while ((portno = portrange.GetToken()))
437 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
439 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?");
443 ServerSocketListener *listener = new ServerSocketListener(this, portno, (char *)IP.c_str());
444 if (listener->GetFd() == -1)
450 if (!transport.empty())
451 listener->Hook = hooks[transport.c_str()];
453 Bindings.push_back(listener);
458 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
459 HideULines = Conf->ReadFlag("security","hideulines",0);
460 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
461 AllowOptCommon = Conf->ReadFlag("options", "allowmismatch", 0);
462 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
463 quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
464 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
465 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
470 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
473 AutoconnectBlocks.clear();
476 for (int j = 0; j < Conf->Enumerate("link"); ++j)
478 reference<Link> L = new Link;
479 std::string Allow = Conf->ReadValue("link", "allowmask", j);
480 L->Name = (Conf->ReadValue("link", "name", j)).c_str();
481 L->AllowMask = Allow;
482 L->IPAddr = Conf->ReadValue("link", "ipaddr", j);
483 L->Port = Conf->ReadInteger("link", "port", j, true);
484 L->SendPass = Conf->ReadValue("link", "sendpass", j);
485 L->RecvPass = Conf->ReadValue("link", "recvpass", j);
486 L->Fingerprint = Conf->ReadValue("link", "fingerprint", j);
487 L->HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
488 L->Timeout = Conf->ReadInteger("link", "timeout", j, true);
489 L->Hook = Conf->ReadValue("link", "transport", j);
490 L->Bind = Conf->ReadValue("link", "bind", j);
491 L->Hidden = Conf->ReadFlag("link", "hidden", j);
493 if ((!L->Hook.empty()) && (hooks.find(L->Hook.c_str()) == hooks.end()))
495 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.");
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;
516 start_type = DNS_QUERY_AAAA;
517 if (strchr(L->IPAddr.c_str(),':'))
520 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
526 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
535 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
536 ServerInstance->AddResolver(sr, cached);
545 if (L->IPAddr.empty())
548 ValidIPs.push_back("*");
549 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.");
552 if (L->RecvPass.empty())
554 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
557 if (L->SendPass.empty())
559 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
564 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
569 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.");
573 LinkBlocks.push_back(L);
576 for (int j = 0; j < Conf->Enumerate("autoconnect"); ++j)
578 reference<Autoconnect> A = new Autoconnect;
579 A->Period = Conf->ReadInteger("autoconnect", "period", j, true);
580 A->NextConnectTime = ServerInstance->Time() + A->Period;
582 std::string servers = Conf->ReadValue("autoconnect", "server", j);
583 irc::spacesepstream ss(servers);
585 while (ss.GetToken(server))
587 A->servers.push_back(server);
592 throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
595 if (A->servers.empty())
597 throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
600 AutoconnectBlocks.push_back(A);
606 Link* SpanningTreeUtilities::FindLink(const std::string& name)
608 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
611 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))