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 CullResult SpanningTreeUtilities::cull()
156 for (unsigned int i = 0; i < ServerInstance->ports.size(); i++)
158 if (ServerInstance->ports[i]->type == "servers")
159 ServerInstance->ports[i]->cull();
162 while (TreeRoot->ChildCount())
164 TreeServer* child_server = TreeRoot->GetChild(0);
167 TreeSocket* sock = child_server->GetSocket();
169 ServerInstance->GlobalCulls.AddItem(sock);
173 ServerUser->uuid = TreeRoot->GetID();
176 return classbase::cull();
179 SpanningTreeUtilities::~SpanningTreeUtilities()
181 for (unsigned int i = 0; i < ServerInstance->ports.size(); i++)
183 if (ServerInstance->ports[i]->type == "servers")
184 delete ServerInstance->ports[i];
190 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
192 if (list.find(server) == list.end())
193 list[server] = server;
196 /* returns a list of DIRECT servernames for a specific channel */
197 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
199 const UserMembList *ulist = c->GetUsers();
201 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
203 if (IS_LOCAL(i->first))
206 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
209 if (exempt_list.find(i->first) == exempt_list.end())
211 TreeServer* best = this->BestRouteTo(i->first->server);
213 AddThisServer(best,list);
219 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist ¶ms)
221 TreeServer* omitroute = this->BestRouteTo(omit);
222 unsigned int items =this->TreeRoot->ChildCount();
223 for (unsigned int x = 0; x < items; x++)
225 TreeServer* Route = this->TreeRoot->GetChild(x);
226 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
228 TreeSocket* Sock = Route->GetSocket();
230 Sock->WriteLine(data);
236 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string omit)
238 TreeServer* omitroute = this->BestRouteTo(omit);
239 std::string FullLine = ":" + prefix + " " + command;
240 unsigned int words = params.size();
241 for (unsigned int x = 0; x < words; x++)
243 FullLine = FullLine + " " + params[x];
245 unsigned int items = this->TreeRoot->ChildCount();
246 for (unsigned int x = 0; x < items; x++)
248 TreeServer* Route = this->TreeRoot->GetChild(x);
250 // The route has a socket (its a direct connection)
251 // The route isnt the one to be omitted
252 // The route isnt the path to the one to be omitted
253 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
255 TreeSocket* Sock = Route->GetSocket();
257 Sock->WriteLine(FullLine);
263 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist ¶ms)
265 std::string FullLine = ":" + prefix + " " + command;
266 unsigned int words = params.size();
267 for (unsigned int x = 0; x < words; x++)
269 FullLine = FullLine + " " + params[x];
271 unsigned int items = this->TreeRoot->ChildCount();
272 for (unsigned int x = 0; x < items; x++)
274 TreeServer* Route = this->TreeRoot->GetChild(x);
275 if (Route && Route->GetSocket())
277 TreeSocket* Sock = Route->GetSocket();
279 Sock->WriteLine(FullLine);
285 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist ¶ms)
287 std::string spfx = prefix;
288 std::string scmd = command;
289 return this->DoOneToMany(spfx, scmd, params);
292 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist ¶ms, std::string omit)
294 std::string spfx = prefix;
295 std::string scmd = command;
296 return this->DoOneToAllButSender(spfx, scmd, params, omit);
299 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string target)
301 TreeServer* Route = this->BestRouteTo(target);
304 std::string FullLine = ":" + prefix + " " + command;
305 unsigned int words = params.size();
306 for (unsigned int x = 0; x < words; x++)
308 FullLine = FullLine + " " + params[x];
310 if (Route && Route->GetSocket())
312 TreeSocket* Sock = Route->GetSocket();
314 Sock->WriteLine(FullLine);
324 void SpanningTreeUtilities::RefreshIPCache()
327 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
330 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
334 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
338 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
341 /* Invalid link block */
345 ValidIPs.push_back(L->IPAddr);
347 if (L->AllowMask.length())
348 ValidIPs.push_back(L->AllowMask);
350 /* Needs resolving */
352 QueryType start_type = DNS_QUERY_A;
353 start_type = DNS_QUERY_AAAA;
354 if (strchr(L->IPAddr.c_str(),':'))
357 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
363 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
372 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
373 ServerInstance->AddResolver(sr, cached);
382 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
388 for (int j = 0; j < Conf.Enumerate("bind"); j++)
390 std::string Type = Conf.ReadValue("bind","type",j);
391 std::string IP = Conf.ReadValue("bind","address",j);
392 std::string Port = Conf.ReadValue("bind","port",j);
393 std::string ssl = Conf.ReadValue("bind","ssl",j);
394 if (Type == "servers")
396 irc::portparser portrange(Port, false);
402 while ((portno = portrange.GetToken()))
404 ServerSocketListener *listener = new ServerSocketListener(this, portno, IP, ssl);
405 if (listener->GetFd() == -1)
411 ServerInstance->ports.push_back(listener);
416 FlatLinks = Conf.ReadFlag("security","flatlinks",0);
417 HideULines = Conf.ReadFlag("security","hideulines",0);
418 AnnounceTSChange = Conf.ReadFlag("options","announcets",0);
419 AllowOptCommon = Conf.ReadFlag("options", "allowmismatch", 0);
420 ChallengeResponse = !Conf.ReadFlag("security", "disablehmac", 0);
421 quiet_bursts = Conf.ReadFlag("performance", "quietbursts", 0);
422 PingWarnTime = Conf.ReadInteger("options", "pingwarning", 0, true);
423 PingFreq = Conf.ReadInteger("options", "serverpingfreq", 0, true);
428 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
431 AutoconnectBlocks.clear();
434 for (int j = 0; j < Conf.Enumerate("link"); ++j)
436 reference<Link> L = new Link;
437 std::string Allow = Conf.ReadValue("link", "allowmask", j);
438 L->Name = (Conf.ReadValue("link", "name", j)).c_str();
439 L->AllowMask = Allow;
440 L->IPAddr = Conf.ReadValue("link", "ipaddr", j);
441 L->Port = Conf.ReadInteger("link", "port", j, true);
442 L->SendPass = Conf.ReadValue("link", "sendpass", j);
443 L->RecvPass = Conf.ReadValue("link", "recvpass", j);
444 L->Fingerprint = Conf.ReadValue("link", "fingerprint", j);
445 L->HiddenFromStats = Conf.ReadFlag("link", "statshidden", j);
446 L->Timeout = Conf.ReadInteger("link", "timeout", j, true);
447 L->Hook = Conf.ReadValue("link", "ssl", j);
448 L->Bind = Conf.ReadValue("link", "bind", j);
449 L->Hidden = Conf.ReadFlag("link", "hidden", j);
451 if (L->Name.find('.') == std::string::npos)
452 throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
454 if (L->Name.length() > 64)
455 throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
457 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
460 ValidIPs.push_back(Allow);
462 ValidIPs.push_back(L->IPAddr);
464 /* Needs resolving */
466 QueryType start_type = DNS_QUERY_A;
467 start_type = DNS_QUERY_AAAA;
468 if (strchr(L->IPAddr.c_str(),':'))
471 if (inet_pton(AF_INET6, L->IPAddr.c_str(), &n) < 1)
477 if (inet_aton(L->IPAddr.c_str(),&n) < 1)
486 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, start_type);
487 ServerInstance->AddResolver(sr, cached);
496 if (L->IPAddr.empty())
499 ValidIPs.push_back("*");
500 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.");
503 if (L->RecvPass.empty())
505 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
508 if (L->SendPass.empty())
510 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
515 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
520 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.");
524 LinkBlocks.push_back(L);
527 for (int j = 0; j < Conf.Enumerate("autoconnect"); ++j)
529 reference<Autoconnect> A = new Autoconnect;
530 A->Period = Conf.ReadInteger("autoconnect", "period", j, true);
531 A->NextConnectTime = ServerInstance->Time() + A->Period;
533 std::string servers = Conf.ReadValue("autoconnect", "server", j);
534 irc::spacesepstream ss(servers);
536 while (ss.GetToken(server))
538 A->servers.push_back(server);
543 throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
546 if (A->servers.empty())
548 throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
551 AutoconnectBlocks.push_back(A);
555 Link* SpanningTreeUtilities::FindLink(const std::string& name)
557 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
560 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))