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"
30 #include "commandbuilder.h"
32 SpanningTreeUtilities* Utils = NULL;
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 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
56 if (InspIRCd::IsSID(ServerName))
57 return this->FindServerID(ServerName);
59 server_hash::iterator iter = serverlist.find(ServerName);
60 if (iter != serverlist.end())
70 /** Returns the locally connected server we must route a
71 * message through to reach server 'ServerName'. This
72 * only applies to one-to-one and not one-to-many routing.
73 * See the comments for the constructor of TreeServer
76 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
78 TreeServer* Found = FindServer(ServerName);
81 return Found->GetRoute();
85 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
86 User *u = ServerInstance->FindNick(ServerName);
89 return TreeServer::Get(u)->GetRoute();
96 /** Find the first server matching a given glob mask.
97 * We iterate over the list and match each one until we get a hit.
99 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
101 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
103 if (InspIRCd::Match(i->first,ServerName))
109 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
111 server_hash::iterator iter = sidlist.find(id);
112 if (iter != sidlist.end())
118 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
119 : Creator(C), TreeRoot(NULL)
120 , PingFreq(60) // XXX: TreeServer constructor reads this and TreeRoot is created before the config is read, so init it to something (value doesn't matter) to avoid a valgrind warning in TimerManager on unload
122 ServerInstance->Timers.AddTimer(&RefreshTimer);
125 CullResult SpanningTreeUtilities::cull()
127 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
128 while (!children.empty())
130 TreeSocket* sock = children.front()->GetSocket();
134 for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
136 TreeSocket* s = i->first;
141 return classbase::cull();
144 SpanningTreeUtilities::~SpanningTreeUtilities()
149 // Returns a list of DIRECT servers for a specific channel
150 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
152 unsigned int minrank = 0;
155 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
157 minrank = mh->GetPrefixRank();
160 const Channel::MemberMap& ulist = c->GetUsers();
161 for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
163 if (IS_LOCAL(i->first))
166 if (minrank && i->second->getRank() < minrank)
169 if (exempt_list.find(i->first) == exempt_list.end())
171 TreeServer* best = TreeServer::Get(i->first);
172 list.insert(best->GetSocket());
178 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
180 const std::string& FullLine = params.str();
182 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
183 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
185 TreeServer* Route = *i;
186 // Send the line if the route isn't the path to the one to be omitted
187 if (Route != omitroute)
189 Route->GetSocket()->WriteLine(FullLine);
194 bool SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, const std::string& target)
196 TreeServer* Route = this->BestRouteTo(target);
200 DoOneToOne(params, Route);
204 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
206 TreeServer* ts = static_cast<TreeServer*>(server);
207 TreeSocket* sock = ts->GetSocket();
209 sock->WriteLine(params);
212 void SpanningTreeUtilities::RefreshIPCache()
215 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
220 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
221 /* Invalid link block */
225 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
227 irc::sockets::sockaddrs dummy;
228 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
229 if ((L->IPAddr == "*") || (ipvalid))
230 ValidIPs.push_back(L->IPAddr);
231 else if (this->Creator->DNS)
233 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
236 this->Creator->DNS->Process(sr);
238 catch (DNS::Exception &)
246 void SpanningTreeUtilities::ReadConfiguration()
248 ConfigTag* security = ServerInstance->Config->ConfValue("security");
249 ConfigTag* options = ServerInstance->Config->ConfValue("options");
250 FlatLinks = security->getBool("flatlinks");
251 HideULines = security->getBool("hideulines");
252 AnnounceTSChange = options->getBool("announcets");
253 AllowOptCommon = options->getBool("allowmismatch");
254 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
255 PingWarnTime = options->getInt("pingwarning");
256 PingFreq = options->getInt("serverpingfreq");
261 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
264 AutoconnectBlocks.clear();
266 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
267 for(ConfigIter i = tags.first; i != tags.second; ++i)
269 ConfigTag* tag = i->second;
270 reference<Link> L = new Link(tag);
271 std::string linkname = tag->getString("name");
272 L->Name = linkname.c_str();
274 irc::spacesepstream sep = tag->getString("allowmask");
275 for (std::string s; sep.GetToken(s);)
276 L->AllowMasks.push_back(s);
278 L->IPAddr = tag->getString("ipaddr");
279 L->Port = tag->getInt("port");
280 L->SendPass = tag->getString("sendpass", tag->getString("password"));
281 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
282 L->Fingerprint = tag->getString("fingerprint");
283 L->HiddenFromStats = tag->getBool("statshidden");
284 L->Timeout = tag->getDuration("timeout", 30);
285 L->Hook = tag->getString("ssl");
286 L->Bind = tag->getString("bind");
287 L->Hidden = tag->getBool("hidden");
290 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
292 if (L->Name.find('.') == std::string::npos)
293 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
295 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
296 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
298 if (L->RecvPass.empty())
299 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
301 if (L->SendPass.empty())
302 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
304 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
305 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
307 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
308 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
310 if (L->IPAddr.empty())
313 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.");
317 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.");
319 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
320 LinkBlocks.push_back(L);
323 tags = ServerInstance->Config->ConfTags("autoconnect");
324 for(ConfigIter i = tags.first; i != tags.second; ++i)
326 ConfigTag* tag = i->second;
327 reference<Autoconnect> A = new Autoconnect(tag);
328 A->Period = tag->getDuration("period", 60, 1);
329 A->NextConnectTime = ServerInstance->Time() + A->Period;
331 irc::spacesepstream ss(tag->getString("server"));
333 while (ss.GetToken(server))
335 A->servers.push_back(server);
338 if (A->servers.empty())
340 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
343 AutoconnectBlocks.push_back(A);
346 for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
347 i->second->CheckULine();
352 Link* SpanningTreeUtilities::FindLink(const std::string& name)
354 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
357 if (InspIRCd::Match(x->Name.c_str(), name.c_str(), rfc_case_insensitive_map))
365 void SpanningTreeUtilities::SendChannelMessage(const std::string& prefix, Channel* target, const std::string& text, char status, const CUList& exempt_list, const char* message_type, TreeSocket* omit)
367 CmdBuilder msg(prefix, message_type);
370 msg.push_raw(status);
371 msg.push_raw(target->name).push_last(text);
374 this->GetListOfServersForChannel(target, list, status, exempt_list);
375 for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
377 TreeSocket* Sock = *i;
379 Sock->WriteLine(msg);