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 /** Find the first server matching a given glob mask.
71 * We iterate over the list and match each one until we get a hit.
73 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
75 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
77 if (InspIRCd::Match(i->first,ServerName))
83 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
85 server_hash::iterator iter = sidlist.find(id);
86 if (iter != sidlist.end())
92 TreeServer* SpanningTreeUtilities::FindRouteTarget(const std::string& target)
94 TreeServer* const server = FindServer(target);
98 User* const user = ServerInstance->FindNick(target);
100 return TreeServer::Get(user);
105 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
106 : Creator(C), TreeRoot(NULL)
107 , 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
109 ServerInstance->Timers.AddTimer(&RefreshTimer);
112 CullResult SpanningTreeUtilities::cull()
114 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
115 while (!children.empty())
117 TreeSocket* sock = children.front()->GetSocket();
121 for(TimeoutList::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
123 TreeSocket* s = i->first;
128 return classbase::cull();
131 SpanningTreeUtilities::~SpanningTreeUtilities()
136 // Returns a list of DIRECT servers for a specific channel
137 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
139 unsigned int minrank = 0;
142 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
144 minrank = mh->GetPrefixRank();
147 const Channel::MemberMap& ulist = c->GetUsers();
148 for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
150 if (IS_LOCAL(i->first))
153 if (minrank && i->second->getRank() < minrank)
156 if (exempt_list.find(i->first) == exempt_list.end())
158 TreeServer* best = TreeServer::Get(i->first);
159 list.insert(best->GetSocket());
165 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
167 const std::string& FullLine = params.str();
169 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
170 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
172 TreeServer* Route = *i;
173 // Send the line if the route isn't the path to the one to be omitted
174 if (Route != omitroute)
176 Route->GetSocket()->WriteLine(FullLine);
181 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
183 TreeServer* ts = static_cast<TreeServer*>(server);
184 TreeSocket* sock = ts->GetSocket();
186 sock->WriteLine(params);
189 void SpanningTreeUtilities::RefreshIPCache()
192 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
197 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
198 /* Invalid link block */
202 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
204 irc::sockets::sockaddrs dummy;
205 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
206 if ((L->IPAddr == "*") || (ipvalid))
207 ValidIPs.push_back(L->IPAddr);
208 else if (this->Creator->DNS)
210 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
213 this->Creator->DNS->Process(sr);
215 catch (DNS::Exception &)
223 void SpanningTreeUtilities::ReadConfiguration()
225 ConfigTag* security = ServerInstance->Config->ConfValue("security");
226 ConfigTag* options = ServerInstance->Config->ConfValue("options");
227 FlatLinks = security->getBool("flatlinks");
228 HideULines = security->getBool("hideulines");
229 AnnounceTSChange = options->getBool("announcets");
230 AllowOptCommon = options->getBool("allowmismatch");
231 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
232 PingWarnTime = options->getDuration("pingwarning", 15);
233 PingFreq = options->getDuration("serverpingfreq", 60, 1);
235 if (PingWarnTime >= PingFreq)
238 AutoconnectBlocks.clear();
240 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
241 for(ConfigIter i = tags.first; i != tags.second; ++i)
243 ConfigTag* tag = i->second;
244 reference<Link> L = new Link(tag);
245 std::string linkname = tag->getString("name");
246 L->Name = linkname.c_str();
248 irc::spacesepstream sep = tag->getString("allowmask");
249 for (std::string s; sep.GetToken(s);)
250 L->AllowMasks.push_back(s);
252 L->IPAddr = tag->getString("ipaddr");
253 L->Port = tag->getInt("port", 0);
254 L->SendPass = tag->getString("sendpass", tag->getString("password"));
255 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
256 L->Fingerprint = tag->getString("fingerprint");
257 L->HiddenFromStats = tag->getBool("statshidden");
258 L->Timeout = tag->getDuration("timeout", 30);
259 L->Hook = tag->getString("ssl");
260 L->Bind = tag->getString("bind");
261 L->Hidden = tag->getBool("hidden");
264 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
266 if (L->Name.find('.') == std::string::npos)
267 throw ModuleException("The link name '"+L->Name+"' is invalid as it must contain at least one '.' character");
269 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
270 throw ModuleException("The link name '"+L->Name+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
272 if (L->RecvPass.empty())
273 throw ModuleException("Invalid configuration for server '"+L->Name+"', recvpass not defined");
275 if (L->SendPass.empty())
276 throw ModuleException("Invalid configuration for server '"+L->Name+"', sendpass not defined");
278 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
279 throw ModuleException("Link block '" + L->Name + "' has a password set that contains a space character which is invalid");
281 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
282 throw ModuleException("Link block '" + L->Name + "' has a password set that begins with a colon (:) which is invalid");
284 if (L->IPAddr.empty())
287 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want.");
291 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no port defined, you will not be able to /connect it.");
293 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
294 LinkBlocks.push_back(L);
297 tags = ServerInstance->Config->ConfTags("autoconnect");
298 for(ConfigIter i = tags.first; i != tags.second; ++i)
300 ConfigTag* tag = i->second;
301 reference<Autoconnect> A = new Autoconnect(tag);
302 A->Period = tag->getDuration("period", 60, 1);
303 A->NextConnectTime = ServerInstance->Time() + A->Period;
305 irc::spacesepstream ss(tag->getString("server"));
307 while (ss.GetToken(server))
309 A->servers.push_back(server);
312 if (A->servers.empty())
314 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
317 AutoconnectBlocks.push_back(A);
320 for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
321 i->second->CheckULine();
326 Link* SpanningTreeUtilities::FindLink(const std::string& name)
328 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
331 if (InspIRCd::Match(x->Name, name, ascii_case_insensitive_map))
339 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)
341 CmdBuilder msg(prefix, message_type);
344 msg.push_raw(status);
345 msg.push_raw(target->name).push_last(text);
348 this->GetListOfServersForChannel(target, list, status, exempt_list);
349 for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
351 TreeSocket* Sock = *i;
353 Sock->WriteLine(msg);