2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2009 Craig Edwards <craigedwards@brainbox.cc>
6 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
7 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "treeserver.h"
28 #include "treesocket.h"
29 #include "resolvers.h"
31 SpanningTreeUtilities* Utils = NULL;
33 /* Create server sockets off a listener. */
34 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
36 if (from->bind_tag->getString("type") != "servers")
37 return MOD_RES_PASSTHRU;
39 std::string incomingip = client->addr();
41 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
43 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
45 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
46 new TreeSocket(newsock, from, client, server);
50 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
54 /** Yay for fast searches!
55 * This is hundreds of times faster than recursion
56 * or even scanning a linked list, especially when
57 * there are more than a few servers to deal with.
60 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
62 if (InspIRCd::IsSID(ServerName))
63 return this->FindServerID(ServerName);
65 server_hash::iterator iter = serverlist.find(ServerName);
66 if (iter != serverlist.end())
76 /** Returns the locally connected server we must route a
77 * message through to reach server 'ServerName'. This
78 * only applies to one-to-one and not one-to-many routing.
79 * See the comments for the constructor of TreeServer
82 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
84 TreeServer* Found = FindServer(ServerName);
87 return Found->GetRoute();
91 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
92 User *u = ServerInstance->FindNick(ServerName);
95 Found = FindServer(u->server);
97 return Found->GetRoute();
104 /** Find the first server matching a given glob mask.
105 * Theres no find-using-glob method of hash_map [awwww :-(]
106 * so instead, we iterate over the list using an iterator
107 * and match each one until we get a hit. Yes its slow,
110 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
112 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
114 if (InspIRCd::Match(i->first,ServerName))
120 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
122 server_hash::iterator iter = sidlist.find(id);
123 if (iter != sidlist.end())
129 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
130 : Creator(C), TreeRoot(NULL)
132 ServerInstance->Timers->AddTimer(&RefreshTimer);
134 this->ReadConfiguration();
137 CullResult SpanningTreeUtilities::cull()
139 while (TreeRoot->ChildCount())
141 TreeServer* child_server = TreeRoot->GetChild(0);
144 TreeSocket* sock = child_server->GetSocket();
149 for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
151 TreeSocket* s = i->first;
156 return classbase::cull();
159 SpanningTreeUtilities::~SpanningTreeUtilities()
164 /* returns a list of DIRECT servernames for a specific channel */
165 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
167 unsigned int minrank = 0;
170 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
172 minrank = mh->GetPrefixRank();
175 const UserMembList *ulist = c->GetUsers();
177 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
179 if (IS_LOCAL(i->first))
182 if (minrank && i->second->getRank() < minrank)
185 if (exempt_list.find(i->first) == exempt_list.end())
187 TreeServer* best = this->BestRouteTo(i->first->server);
195 std::string SpanningTreeUtilities::ConstructLine(const std::string& prefix, const std::string& command, const parameterlist& params)
197 std::string FullLine;
198 FullLine.reserve(1024);
199 FullLine = ":" + prefix + " " + command;
200 for (parameterlist::const_iterator x = params.begin(); x != params.end(); ++x)
202 FullLine.push_back(' ');
208 void SpanningTreeUtilities::DoOneToAllButSender(const std::string& prefix, const std::string& command, const parameterlist& params, TreeServer* omitroute)
210 std::string FullLine = ConstructLine(prefix, command, params);
212 unsigned int items = this->TreeRoot->ChildCount();
213 for (unsigned int x = 0; x < items; x++)
215 TreeServer* Route = this->TreeRoot->GetChild(x);
216 // Send the line if the route isn't the path to the one to be omitted
217 if (Route != omitroute)
219 Route->GetSocket()->WriteLine(FullLine);
224 bool SpanningTreeUtilities::DoOneToOne(const std::string& prefix, const std::string& command, const parameterlist& params, const std::string& target)
226 TreeServer* Route = this->BestRouteTo(target);
230 Route->GetSocket()->WriteLine(ConstructLine(prefix, command, params));
234 void SpanningTreeUtilities::RefreshIPCache()
237 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
242 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
243 /* Invalid link block */
247 if (L->AllowMask.length())
248 ValidIPs.push_back(L->AllowMask);
250 irc::sockets::sockaddrs dummy;
251 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
252 if ((L->IPAddr == "*") || (ipvalid))
253 ValidIPs.push_back(L->IPAddr);
254 else if (this->Creator->DNS)
256 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
259 this->Creator->DNS->Process(sr);
261 catch (DNS::Exception &)
269 void SpanningTreeUtilities::ReadConfiguration()
271 ConfigTag* security = ServerInstance->Config->ConfValue("security");
272 ConfigTag* options = ServerInstance->Config->ConfValue("options");
273 FlatLinks = security->getBool("flatlinks");
274 HideULines = security->getBool("hideulines");
275 AnnounceTSChange = options->getBool("announcets");
276 AllowOptCommon = options->getBool("allowmismatch");
277 ChallengeResponse = !security->getBool("disablehmac");
278 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
279 PingWarnTime = options->getInt("pingwarning");
280 PingFreq = options->getInt("serverpingfreq");
285 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
288 AutoconnectBlocks.clear();
290 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
291 for(ConfigIter i = tags.first; i != tags.second; ++i)
293 ConfigTag* tag = i->second;
294 reference<Link> L = new Link(tag);
295 std::string linkname = tag->getString("name");
296 L->Name = linkname.c_str();
297 L->AllowMask = tag->getString("allowmask");
298 L->IPAddr = tag->getString("ipaddr");
299 L->Port = tag->getInt("port");
300 L->SendPass = tag->getString("sendpass", tag->getString("password"));
301 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
302 L->Fingerprint = tag->getString("fingerprint");
303 L->HiddenFromStats = tag->getBool("statshidden");
304 L->Timeout = tag->getDuration("timeout", 30);
305 L->Hook = tag->getString("ssl");
306 L->Bind = tag->getString("bind");
307 L->Hidden = tag->getBool("hidden");
310 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
312 if (L->Name.find('.') == std::string::npos)
313 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
315 if (L->Name.length() > 64)
316 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters");
318 if (L->RecvPass.empty())
319 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
321 if (L->SendPass.empty())
322 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
324 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
325 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
327 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
328 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
330 if (L->IPAddr.empty())
333 ServerInstance->Logs->Log(MODNAME, LOG_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.");
337 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + assign(L->Name) + "' has no port defined, you will not be able to /connect it.");
339 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
340 LinkBlocks.push_back(L);
343 tags = ServerInstance->Config->ConfTags("autoconnect");
344 for(ConfigIter i = tags.first; i != tags.second; ++i)
346 ConfigTag* tag = i->second;
347 reference<Autoconnect> A = new Autoconnect(tag);
348 A->Period = tag->getDuration("period", 60, 1);
349 A->NextConnectTime = ServerInstance->Time() + A->Period;
351 irc::spacesepstream ss(tag->getString("server"));
353 while (ss.GetToken(server))
355 A->servers.push_back(server);
358 if (A->servers.empty())
360 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
363 AutoconnectBlocks.push_back(A);
369 Link* SpanningTreeUtilities::FindLink(const std::string& name)
371 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
374 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
382 void SpanningTreeUtilities::SendChannelMessage(const std::string& prefix, Channel* target, const std::string &text, char status, const CUList& exempt_list, const char* message_type)
384 std::string raw(":");
385 raw.append(prefix).append(1, ' ').append(message_type).push_back(' ');
387 raw.push_back(status);
388 raw.append(target->name).append(" :").append(text);
391 this->GetListOfServersForChannel(target, list, status, exempt_list);
392 for (TreeServerList::iterator i = list.begin(); i != list.end(); ++i)
394 TreeSocket* Sock = (*i)->GetSocket();
396 Sock->WriteLine(raw);