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 /* Create server sockets off a listener. */
35 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
37 if (from->bind_tag->getString("type") != "servers")
38 return MOD_RES_PASSTHRU;
40 std::string incomingip = client->addr();
42 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
44 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
46 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
47 new TreeSocket(newsock, from, client, server);
51 ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
55 /** Yay for fast searches!
56 * This is hundreds of times faster than recursion
57 * or even scanning a linked list, especially when
58 * there are more than a few servers to deal with.
61 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
63 if (InspIRCd::IsSID(ServerName))
64 return this->FindServerID(ServerName);
66 server_hash::iterator iter = serverlist.find(ServerName);
67 if (iter != serverlist.end())
77 /** Returns the locally connected server we must route a
78 * message through to reach server 'ServerName'. This
79 * only applies to one-to-one and not one-to-many routing.
80 * See the comments for the constructor of TreeServer
83 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
85 TreeServer* Found = FindServer(ServerName);
88 return Found->GetRoute();
92 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
93 User *u = ServerInstance->FindNick(ServerName);
96 return TreeServer::Get(u)->GetRoute();
103 /** Find the first server matching a given glob mask.
104 * Theres no find-using-glob method of hash_map [awwww :-(]
105 * so instead, we iterate over the list using an iterator
106 * and match each one until we get a hit. Yes its slow,
109 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
111 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
113 if (InspIRCd::Match(i->first,ServerName))
119 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
121 server_hash::iterator iter = sidlist.find(id);
122 if (iter != sidlist.end())
128 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
129 : Creator(C), TreeRoot(NULL)
131 ServerInstance->Timers.AddTimer(&RefreshTimer);
134 CullResult SpanningTreeUtilities::cull()
136 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
137 while (!children.empty())
139 TreeSocket* sock = children.front()->GetSocket();
143 for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
145 TreeSocket* s = i->first;
150 return classbase::cull();
153 SpanningTreeUtilities::~SpanningTreeUtilities()
158 /* returns a list of DIRECT servernames for a specific channel */
159 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
161 unsigned int minrank = 0;
164 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
166 minrank = mh->GetPrefixRank();
169 const Channel::MemberMap& ulist = c->GetUsers();
170 for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
172 if (IS_LOCAL(i->first))
175 if (minrank && i->second->getRank() < minrank)
178 if (exempt_list.find(i->first) == exempt_list.end())
180 TreeServer* best = TreeServer::Get(i->first);
181 list.insert(best->GetSocket());
187 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
189 const std::string& FullLine = params.str();
191 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
192 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
194 TreeServer* Route = *i;
195 // Send the line if the route isn't the path to the one to be omitted
196 if (Route != omitroute)
198 Route->GetSocket()->WriteLine(FullLine);
203 bool SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, const std::string& target)
205 TreeServer* Route = this->BestRouteTo(target);
209 DoOneToOne(params, Route);
213 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
215 TreeServer* ts = static_cast<TreeServer*>(server);
216 TreeSocket* sock = ts->GetSocket();
218 sock->WriteLine(params);
221 void SpanningTreeUtilities::RefreshIPCache()
224 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
229 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
230 /* Invalid link block */
234 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
236 irc::sockets::sockaddrs dummy;
237 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
238 if ((L->IPAddr == "*") || (ipvalid))
239 ValidIPs.push_back(L->IPAddr);
240 else if (this->Creator->DNS)
242 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
245 this->Creator->DNS->Process(sr);
247 catch (DNS::Exception &)
255 void SpanningTreeUtilities::ReadConfiguration()
257 ConfigTag* security = ServerInstance->Config->ConfValue("security");
258 ConfigTag* options = ServerInstance->Config->ConfValue("options");
259 FlatLinks = security->getBool("flatlinks");
260 HideULines = security->getBool("hideulines");
261 AnnounceTSChange = options->getBool("announcets");
262 AllowOptCommon = options->getBool("allowmismatch");
263 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
264 PingWarnTime = options->getInt("pingwarning");
265 PingFreq = options->getInt("serverpingfreq");
270 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
273 AutoconnectBlocks.clear();
275 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
276 for(ConfigIter i = tags.first; i != tags.second; ++i)
278 ConfigTag* tag = i->second;
279 reference<Link> L = new Link(tag);
280 std::string linkname = tag->getString("name");
281 L->Name = linkname.c_str();
283 irc::spacesepstream sep = tag->getString("allowmask");
284 for (std::string s; sep.GetToken(s);)
285 L->AllowMasks.push_back(s);
287 L->IPAddr = tag->getString("ipaddr");
288 L->Port = tag->getInt("port");
289 L->SendPass = tag->getString("sendpass", tag->getString("password"));
290 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
291 L->Fingerprint = tag->getString("fingerprint");
292 L->HiddenFromStats = tag->getBool("statshidden");
293 L->Timeout = tag->getDuration("timeout", 30);
294 L->Hook = tag->getString("ssl");
295 L->Bind = tag->getString("bind");
296 L->Hidden = tag->getBool("hidden");
299 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
301 if (L->Name.find('.') == std::string::npos)
302 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
304 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
305 throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
307 if (L->RecvPass.empty())
308 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
310 if (L->SendPass.empty())
311 throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
313 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
314 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
316 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
317 throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
319 if (L->IPAddr.empty())
322 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.");
326 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.");
328 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
329 LinkBlocks.push_back(L);
332 tags = ServerInstance->Config->ConfTags("autoconnect");
333 for(ConfigIter i = tags.first; i != tags.second; ++i)
335 ConfigTag* tag = i->second;
336 reference<Autoconnect> A = new Autoconnect(tag);
337 A->Period = tag->getDuration("period", 60, 1);
338 A->NextConnectTime = ServerInstance->Time() + A->Period;
340 irc::spacesepstream ss(tag->getString("server"));
342 while (ss.GetToken(server))
344 A->servers.push_back(server);
347 if (A->servers.empty())
349 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
352 AutoconnectBlocks.push_back(A);
355 for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
356 i->second->CheckULine();
361 Link* SpanningTreeUtilities::FindLink(const std::string& name)
363 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
366 if (InspIRCd::Match(x->Name.c_str(), name.c_str(), rfc_case_insensitive_map))
374 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)
376 CmdBuilder msg(prefix, message_type);
379 msg.push_raw(status);
380 msg.push_raw(target->name).push_last(text);
383 this->GetListOfServersForChannel(target, list, status, exempt_list);
384 for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
386 TreeSocket* Sock = *i;
388 Sock->WriteLine(msg);