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 /* Create server sockets off a listener. */
27 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
29 if (from->bind_tag->getString("type") != "servers")
30 return MOD_RES_PASSTHRU;
34 std::string incomingip;
35 irc::sockets::satoap(client, incomingip, port);
37 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), incomingip) != 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(incomingip, *i))
51 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
56 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
58 new TreeSocket(Utils, newsock, from, client, server);
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 (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(ModuleSpanningTree* C) : Creator(C)
147 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
149 this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
150 ServerUser = new FakeUser(TreeRoot->GetID());
152 this->ReadConfiguration();
155 CullResult SpanningTreeUtilities::cull()
157 while (TreeRoot->ChildCount())
159 TreeServer* child_server = TreeRoot->GetChild(0);
162 TreeSocket* sock = child_server->GetSocket();
164 ServerInstance->GlobalCulls.AddItem(sock);
168 ServerUser->uuid = TreeRoot->GetID();
171 return classbase::cull();
174 SpanningTreeUtilities::~SpanningTreeUtilities()
179 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
181 if (list.find(server) == list.end())
182 list[server] = server;
185 /* returns a list of DIRECT servernames for a specific channel */
186 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
188 const UserMembList *ulist = c->GetUsers();
190 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
192 if (IS_LOCAL(i->first))
195 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
198 if (exempt_list.find(i->first) == exempt_list.end())
200 TreeServer* best = this->BestRouteTo(i->first->server);
202 AddThisServer(best,list);
208 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist ¶ms)
210 TreeServer* omitroute = this->BestRouteTo(omit);
211 unsigned int items =this->TreeRoot->ChildCount();
212 for (unsigned int x = 0; x < items; x++)
214 TreeServer* Route = this->TreeRoot->GetChild(x);
215 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
217 TreeSocket* Sock = Route->GetSocket();
219 Sock->WriteLine(data);
225 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string omit)
227 TreeServer* omitroute = this->BestRouteTo(omit);
228 std::string FullLine = ":" + prefix + " " + command;
229 unsigned int words = params.size();
230 for (unsigned int x = 0; x < words; x++)
232 FullLine = FullLine + " " + params[x];
234 unsigned int items = this->TreeRoot->ChildCount();
235 for (unsigned int x = 0; x < items; x++)
237 TreeServer* Route = this->TreeRoot->GetChild(x);
239 // The route has a socket (its a direct connection)
240 // The route isnt the one to be omitted
241 // The route isnt the path to the one to be omitted
242 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
244 TreeSocket* Sock = Route->GetSocket();
246 Sock->WriteLine(FullLine);
252 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist ¶ms)
254 std::string FullLine = ":" + prefix + " " + command;
255 unsigned int words = params.size();
256 for (unsigned int x = 0; x < words; x++)
258 FullLine = FullLine + " " + params[x];
260 unsigned int items = this->TreeRoot->ChildCount();
261 for (unsigned int x = 0; x < items; x++)
263 TreeServer* Route = this->TreeRoot->GetChild(x);
264 if (Route && Route->GetSocket())
266 TreeSocket* Sock = Route->GetSocket();
268 Sock->WriteLine(FullLine);
274 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist ¶ms)
276 std::string spfx = prefix;
277 std::string scmd = command;
278 return this->DoOneToMany(spfx, scmd, params);
281 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist ¶ms, std::string omit)
283 std::string spfx = prefix;
284 std::string scmd = command;
285 return this->DoOneToAllButSender(spfx, scmd, params, omit);
288 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string target)
290 TreeServer* Route = this->BestRouteTo(target);
293 std::string FullLine = ":" + prefix + " " + command;
294 unsigned int words = params.size();
295 for (unsigned int x = 0; x < words; x++)
297 FullLine = FullLine + " " + params[x];
299 if (Route && Route->GetSocket())
301 TreeSocket* Sock = Route->GetSocket();
303 Sock->WriteLine(FullLine);
313 void SpanningTreeUtilities::RefreshIPCache()
316 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
319 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
323 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
327 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
330 /* Invalid link block */
334 if (L->AllowMask.length())
335 ValidIPs.push_back(L->AllowMask);
337 irc::sockets::sockaddrs dummy;
338 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, &dummy);
340 ValidIPs.push_back(L->IPAddr);
346 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
347 ServerInstance->AddResolver(sr, cached);
356 void SpanningTreeUtilities::ReadConfiguration()
360 FlatLinks = Conf.ReadFlag("security","flatlinks",0);
361 HideULines = Conf.ReadFlag("security","hideulines",0);
362 AnnounceTSChange = Conf.ReadFlag("options","announcets",0);
363 AllowOptCommon = Conf.ReadFlag("options", "allowmismatch", 0);
364 ChallengeResponse = !Conf.ReadFlag("security", "disablehmac", 0);
365 quiet_bursts = Conf.ReadFlag("performance", "quietbursts", 0);
366 PingWarnTime = Conf.ReadInteger("options", "pingwarning", 0, true);
367 PingFreq = Conf.ReadInteger("options", "serverpingfreq", 0, true);
372 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
375 AutoconnectBlocks.clear();
378 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
379 for(ConfigIter i = tags.first; i != tags.second; ++i)
381 ConfigTag* tag = i->second;
382 reference<Link> L = new Link(tag);
383 L->Name = tag->getString("name").c_str();
384 L->AllowMask = tag->getString("allowmask");
385 L->IPAddr = tag->getString("ipaddr");
386 L->Port = tag->getInt("port");
387 L->SendPass = tag->getString("sendpass");
388 L->RecvPass = tag->getString("recvpass");
389 L->Fingerprint = tag->getString("fingerprint");
390 L->HiddenFromStats = tag->getBool("statshidden");
391 L->Timeout = tag->getInt("timeout");
392 L->Hook = tag->getString("ssl");
393 L->Bind = tag->getString("bind");
394 L->Hidden = tag->getBool("hidden");
396 if (L->Name.find('.') == std::string::npos)
397 throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
399 if (L->Name.length() > 64)
400 throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
402 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
404 ValidIPs.push_back(L->IPAddr);
408 if (L->IPAddr.empty())
411 ValidIPs.push_back("*");
412 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.");
415 if (L->RecvPass.empty())
417 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
420 if (L->SendPass.empty())
422 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
427 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
432 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.");
436 LinkBlocks.push_back(L);
439 tags = ServerInstance->Config->ConfTags("autoconnect");
440 for(ConfigIter i = tags.first; i != tags.second; ++i)
442 ConfigTag* tag = i->second;
443 reference<Autoconnect> A = new Autoconnect(tag);
444 A->Period = tag->getInt("period");
445 A->NextConnectTime = ServerInstance->Time() + A->Period;
447 irc::spacesepstream ss(tag->getString("server"));
449 while (ss.GetToken(server))
451 A->servers.push_back(server);
456 throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
459 if (A->servers.empty())
461 throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
464 AutoconnectBlocks.push_back(A);
470 Link* SpanningTreeUtilities::FindLink(const std::string& name)
472 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
475 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))