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"
31 #include "modules/server.h"
33 SpanningTreeUtilities* Utils = NULL;
35 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
37 if (!stdalgo::string::equalsci(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 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
57 if (InspIRCd::IsSID(ServerName))
58 return this->FindServerID(ServerName);
60 server_hash::iterator iter = serverlist.find(ServerName);
61 if (iter != serverlist.end())
71 /** Find the first server matching a given glob mask.
72 * We iterate over the list and match each one until we get a hit.
74 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
76 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
78 if (InspIRCd::Match(i->first,ServerName))
84 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
86 server_hash::iterator iter = sidlist.find(id);
87 if (iter != sidlist.end())
93 TreeServer* SpanningTreeUtilities::FindRouteTarget(const std::string& target)
95 TreeServer* const server = FindServer(target);
99 User* const user = ServerInstance->FindNick(target);
101 return TreeServer::Get(user);
106 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
107 : Creator(C), TreeRoot(NULL)
108 , 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
110 ServerInstance->Timers.AddTimer(&RefreshTimer);
113 CullResult SpanningTreeUtilities::cull()
115 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
116 while (!children.empty())
118 TreeSocket* sock = children.front()->GetSocket();
122 for(TimeoutList::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
124 TreeSocket* s = i->first;
129 return classbase::cull();
132 SpanningTreeUtilities::~SpanningTreeUtilities()
137 // Returns a list of DIRECT servers for a specific channel
138 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
140 unsigned int minrank = 0;
143 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
145 minrank = mh->GetPrefixRank();
148 TreeServer::ChildServers children = TreeRoot->GetChildren();
149 const Channel::MemberMap& ulist = c->GetUsers();
150 for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
152 if (IS_LOCAL(i->first))
155 if (minrank && i->second->getRank() < minrank)
158 if (exempt_list.find(i->first) == exempt_list.end())
160 TreeServer* best = TreeServer::Get(i->first);
161 list.insert(best->GetSocket());
163 TreeServer::ChildServers::iterator citer = std::find(children.begin(), children.end(), best);
164 if (citer != children.end())
165 children.erase(citer);
169 // Check whether the servers which do not have users in the channel might need this message. This
170 // is used to keep the chanhistory module synchronised between servers.
171 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
174 FIRST_MOD_RESULT_CUSTOM(Creator->GetEventProvider(), ServerEventListener, OnBroadcastMessage, result, (c, *i));
175 if (result == MOD_RES_ALLOW)
176 list.insert((*i)->GetSocket());
180 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
182 const std::string& FullLine = params.str();
184 const TreeServer::ChildServers& children = TreeRoot->GetChildren();
185 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
187 TreeServer* Route = *i;
188 // Send the line if the route isn't the path to the one to be omitted
189 if (Route != omitroute)
191 Route->GetSocket()->WriteLine(FullLine);
196 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
198 TreeServer* ts = static_cast<TreeServer*>(server);
199 TreeSocket* sock = ts->GetSocket();
201 sock->WriteLine(params);
204 void SpanningTreeUtilities::RefreshIPCache()
207 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
212 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
213 /* Invalid link block */
217 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
219 irc::sockets::sockaddrs dummy;
220 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
221 if ((L->IPAddr == "*") || (ipvalid))
222 ValidIPs.push_back(L->IPAddr);
223 else if (this->Creator->DNS)
225 SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
228 this->Creator->DNS->Process(sr);
230 catch (DNS::Exception &)
238 void SpanningTreeUtilities::ReadConfiguration()
240 ConfigTag* security = ServerInstance->Config->ConfValue("security");
241 ConfigTag* options = ServerInstance->Config->ConfValue("options");
242 FlatLinks = security->getBool("flatlinks");
243 HideULines = security->getBool("hideulines");
244 HideSplits = security->getBool("hidesplits");
245 AnnounceTSChange = options->getBool("announcets");
246 AllowOptCommon = options->getBool("allowmismatch");
247 quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
248 PingWarnTime = options->getDuration("pingwarning", 15);
249 PingFreq = options->getDuration("serverpingfreq", 60, 1);
251 if (PingWarnTime >= PingFreq)
254 AutoconnectBlocks.clear();
256 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
257 for(ConfigIter i = tags.first; i != tags.second; ++i)
259 ConfigTag* tag = i->second;
260 reference<Link> L = new Link(tag);
261 std::string linkname = tag->getString("name");
262 L->Name = linkname.c_str();
264 irc::spacesepstream sep = tag->getString("allowmask");
265 for (std::string s; sep.GetToken(s);)
266 L->AllowMasks.push_back(s);
268 L->IPAddr = tag->getString("ipaddr");
269 L->Port = tag->getUInt("port", 0);
270 L->SendPass = tag->getString("sendpass", tag->getString("password"));
271 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
272 L->Fingerprint = tag->getString("fingerprint");
273 L->HiddenFromStats = tag->getBool("statshidden");
274 L->Timeout = tag->getDuration("timeout", 30);
275 L->Hook = tag->getString("ssl");
276 L->Bind = tag->getString("bind");
277 L->Hidden = tag->getBool("hidden");
280 throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
282 if (L->Name.find('.') == std::string::npos)
283 throw ModuleException("The link name '"+L->Name+"' is invalid as it must contain at least one '.' character");
285 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
286 throw ModuleException("The link name '"+L->Name+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
288 if (L->RecvPass.empty())
289 throw ModuleException("Invalid configuration for server '"+L->Name+"', recvpass not defined");
291 if (L->SendPass.empty())
292 throw ModuleException("Invalid configuration for server '"+L->Name+"', sendpass not defined");
294 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
295 throw ModuleException("Link block '" + L->Name + "' has a password set that contains a space character which is invalid");
297 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
298 throw ModuleException("Link block '" + L->Name + "' has a password set that begins with a colon (:) which is invalid");
300 if (L->IPAddr.empty())
303 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.");
307 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + L->Name + "' has no port defined, you will not be able to /connect it.");
309 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
310 LinkBlocks.push_back(L);
313 tags = ServerInstance->Config->ConfTags("autoconnect");
314 for(ConfigIter i = tags.first; i != tags.second; ++i)
316 ConfigTag* tag = i->second;
317 reference<Autoconnect> A = new Autoconnect(tag);
318 A->Period = tag->getDuration("period", 60, 1);
319 A->NextConnectTime = ServerInstance->Time() + A->Period;
321 irc::spacesepstream ss(tag->getString("server"));
323 while (ss.GetToken(server))
325 A->servers.push_back(server);
328 if (A->servers.empty())
330 throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
333 AutoconnectBlocks.push_back(A);
336 for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
337 i->second->CheckULine();
342 Link* SpanningTreeUtilities::FindLink(const std::string& name)
344 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
347 if (InspIRCd::Match(x->Name, name, ascii_case_insensitive_map))
355 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)
357 CmdBuilder msg(prefix, message_type);
360 msg.push_raw(status);
361 msg.push_raw(target->name).push_last(text);
364 this->GetListOfServersForChannel(target, list, status, exempt_list);
365 for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
367 TreeSocket* Sock = *i;
369 Sock->WriteLine(msg);