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 "socketengine.h"
21 #include "treeserver.h"
23 #include "treesocket.h"
24 #include "resolvers.h"
26 /* $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 */
28 /* Create server sockets off a listener. */
29 void ServerSocketListener::OnAcceptReady(int newsock)
33 std::string incomingip;
34 irc::sockets::satoap(&client, incomingip, port);
36 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), incomingip) != Utils->ValidIPs.end());
39 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
41 if (*i == "*" || irc::sockets::MatchCIDR(incomingip, *i))
50 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
51 ServerInstance->SE->Close(newsock);
56 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
58 new TreeSocket(Utils, newsock, this, &client, &server);
61 /** Yay for fast searches!
62 * This is hundreds of times faster than recursion
63 * or even scanning a linked list, especially when
64 * there are more than a few servers to deal with.
67 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
69 if (ServerInstance->IsSID(ServerName))
70 return this->FindServerID(ServerName);
72 server_hash::iterator iter = serverlist.find(ServerName.c_str());
73 if (iter != serverlist.end())
83 /** Returns the locally connected server we must route a
84 * message through to reach server 'ServerName'. This
85 * only applies to one-to-one and not one-to-many routing.
86 * See the comments for the constructor of TreeServer
89 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
91 if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
93 TreeServer* Found = FindServer(ServerName);
96 return Found->GetRoute();
100 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
101 User *u = ServerInstance->FindNick(ServerName);
104 Found = FindServer(u->server);
106 return Found->GetRoute();
113 /** Find the first server matching a given glob mask.
114 * Theres no find-using-glob method of hash_map [awwww :-(]
115 * so instead, we iterate over the list using an iterator
116 * and match each one until we get a hit. Yes its slow,
119 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
121 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
123 if (InspIRCd::Match(i->first,ServerName))
129 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
131 server_hash::iterator iter = sidlist.find(id);
132 if (iter != sidlist.end())
138 /* A convenient wrapper that returns true if a server exists */
139 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
141 return (FindServer(ServerName) != NULL);
144 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
146 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
148 this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
149 ServerUser = new FakeUser(TreeRoot->GetID());
151 this->ReadConfiguration(true);
154 bool SpanningTreeUtilities::cull()
156 for (unsigned int i = 0; i < Bindings.size(); i++)
161 while (TreeRoot->ChildCount())
163 TreeServer* child_server = TreeRoot->GetChild(0);
166 TreeSocket* sock = child_server->GetSocket();
168 ServerInstance->GlobalCulls.AddItem(sock);
172 ServerUser->uuid = TreeRoot->GetID();
173 if (ServerUser->cull())
178 SpanningTreeUtilities::~SpanningTreeUtilities()
180 for (unsigned int i = 0; i < Bindings.size(); i++)
188 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
190 if (list.find(server) == list.end())
191 list[server] = server;
194 /* returns a list of DIRECT servernames for a specific channel */
195 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
197 const UserMembList *ulist = c->GetUsers();
199 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
201 if (IS_LOCAL(i->first))
204 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
207 if (exempt_list.find(i->first) == exempt_list.end())
209 TreeServer* best = this->BestRouteTo(i->first->server);
211 AddThisServer(best,list);
217 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist ¶ms)
219 TreeServer* omitroute = this->BestRouteTo(omit);
220 unsigned int items =this->TreeRoot->ChildCount();
221 for (unsigned int x = 0; x < items; x++)
223 TreeServer* Route = this->TreeRoot->GetChild(x);
224 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
226 TreeSocket* Sock = Route->GetSocket();
228 Sock->WriteLine(data);
234 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string omit)
236 TreeServer* omitroute = this->BestRouteTo(omit);
237 std::string FullLine = ":" + prefix + " " + command;
238 unsigned int words = params.size();
239 for (unsigned int x = 0; x < words; x++)
241 FullLine = FullLine + " " + params[x];
243 unsigned int items = this->TreeRoot->ChildCount();
244 for (unsigned int x = 0; x < items; x++)
246 TreeServer* Route = this->TreeRoot->GetChild(x);
248 // The route has a socket (its a direct connection)
249 // The route isnt the one to be omitted
250 // The route isnt the path to the one to be omitted
251 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
253 TreeSocket* Sock = Route->GetSocket();
255 Sock->WriteLine(FullLine);
261 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist ¶ms)
263 std::string FullLine = ":" + prefix + " " + command;
264 unsigned int words = params.size();
265 for (unsigned int x = 0; x < words; x++)
267 FullLine = FullLine + " " + params[x];
269 unsigned int items = this->TreeRoot->ChildCount();
270 for (unsigned int x = 0; x < items; x++)
272 TreeServer* Route = this->TreeRoot->GetChild(x);
273 if (Route && Route->GetSocket())
275 TreeSocket* Sock = Route->GetSocket();
277 Sock->WriteLine(FullLine);
283 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist ¶ms)
285 std::string spfx = prefix;
286 std::string scmd = command;
287 return this->DoOneToMany(spfx, scmd, params);
290 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist ¶ms, std::string omit)
292 std::string spfx = prefix;
293 std::string scmd = command;
294 return this->DoOneToAllButSender(spfx, scmd, params, omit);
297 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string target)
299 TreeServer* Route = this->BestRouteTo(target);
302 std::string FullLine = ":" + prefix + " " + command;
303 unsigned int words = params.size();
304 for (unsigned int x = 0; x < words; x++)
306 FullLine = FullLine + " " + params[x];
308 if (Route && Route->GetSocket())
310 TreeSocket* Sock = Route->GetSocket();
312 Sock->WriteLine(FullLine);
322 void SpanningTreeUtilities::RefreshIPCache()
325 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
328 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
332 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
336 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
339 /* Invalid link block */
343 ValidIPs.push_back(L->IPAddr);
345 if (L->AllowMask.length())
346 ValidIPs.push_back(L->AllowMask);
348 /* Needs resolving */
350 QueryType start_type = DNS_QUERY_A;
351 start_type = DNS_QUERY_AAAA;
352 if (strchr(L->IPAddr.c_str(),':'))
355 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
361 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
370 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
371 ServerInstance->AddResolver(sr, cached);
380 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
382 ConfigReader* Conf = new ConfigReader;
386 for (unsigned int i = 0; i < Bindings.size(); i++)
392 for (int j = 0; j < Conf->Enumerate("bind"); j++)
394 std::string Type = Conf->ReadValue("bind","type",j);
395 std::string IP = Conf->ReadValue("bind","address",j);
396 std::string Port = Conf->ReadValue("bind","port",j);
397 std::string ssl = Conf->ReadValue("bind","ssl",j);
398 if (Type == "servers")
400 irc::portparser portrange(Port, false);
406 while ((portno = portrange.GetToken()))
408 ServerSocketListener *listener = new ServerSocketListener(this, portno, IP, ssl);
409 if (listener->GetFd() == -1)
415 Bindings.push_back(listener);
420 FlatLinks = Conf->ReadFlag("security","flatlinks",0);
421 HideULines = Conf->ReadFlag("security","hideulines",0);
422 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
423 AllowOptCommon = Conf->ReadFlag("options", "allowmismatch", 0);
424 ChallengeResponse = !Conf->ReadFlag("security", "disablehmac", 0);
425 quiet_bursts = Conf->ReadFlag("performance", "quietbursts", 0);
426 PingWarnTime = Conf->ReadInteger("options", "pingwarning", 0, true);
427 PingFreq = Conf->ReadInteger("options", "serverpingfreq", 0, true);
432 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
435 AutoconnectBlocks.clear();
438 for (int j = 0; j < Conf->Enumerate("link"); ++j)
440 reference<Link> L = new Link;
441 std::string Allow = Conf->ReadValue("link", "allowmask", j);
442 L->Name = (Conf->ReadValue("link", "name", j)).c_str();
443 L->AllowMask = Allow;
444 L->IPAddr = Conf->ReadValue("link", "ipaddr", j);
445 L->Port = Conf->ReadInteger("link", "port", j, true);
446 L->SendPass = Conf->ReadValue("link", "sendpass", j);
447 L->RecvPass = Conf->ReadValue("link", "recvpass", j);
448 L->Fingerprint = Conf->ReadValue("link", "fingerprint", j);
449 L->HiddenFromStats = Conf->ReadFlag("link", "statshidden", j);
450 L->Timeout = Conf->ReadInteger("link", "timeout", j, true);
451 L->Hook = Conf->ReadValue("link", "transport", j);
452 L->Bind = Conf->ReadValue("link", "bind", j);
453 L->Hidden = Conf->ReadFlag("link", "hidden", j);
455 if (L->Name.find('.') == std::string::npos)
456 throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
458 if (L->Name.length() > 64)
459 throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
461 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
464 ValidIPs.push_back(Allow);
466 ValidIPs.push_back(L->IPAddr);
468 /* Needs resolving */
470 QueryType start_type = DNS_QUERY_A;
471 start_type = DNS_QUERY_AAAA;
472 if (strchr(L->IPAddr.c_str(),':'))
475 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
481 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
490 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
491 ServerInstance->AddResolver(sr, cached);
500 if (L->IPAddr.empty())
503 ValidIPs.push_back("*");
504 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.");
507 if (L->RecvPass.empty())
509 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
512 if (L->SendPass.empty())
514 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
519 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
524 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.");
528 LinkBlocks.push_back(L);
531 for (int j = 0; j < Conf->Enumerate("autoconnect"); ++j)
533 reference<Autoconnect> A = new Autoconnect;
534 A->Period = Conf->ReadInteger("autoconnect", "period", j, true);
535 A->NextConnectTime = ServerInstance->Time() + A->Period;
537 std::string servers = Conf->ReadValue("autoconnect", "server", j);
538 irc::spacesepstream ss(servers);
540 while (ss.GetToken(server))
542 A->servers.push_back(server);
547 throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
550 if (A->servers.empty())
552 throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
555 AutoconnectBlocks.push_back(A);
561 Link* SpanningTreeUtilities::FindLink(const std::string& name)
563 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
566 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))