]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Move Channel::UserList() from core to cmd_names
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / utils.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
8  *
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.
12  *
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
16  * details.
17  *
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/>.
20  */
21
22
23 #include "inspircd.h"
24
25 #include "main.h"
26 #include "utils.h"
27 #include "treeserver.h"
28 #include "treesocket.h"
29 #include "resolvers.h"
30 #include "commandbuilder.h"
31
32 SpanningTreeUtilities* Utils = NULL;
33
34 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
35 {
36         if (from->bind_tag->getString("type") != "servers")
37                 return MOD_RES_PASSTHRU;
38
39         std::string incomingip = client->addr();
40
41         for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
42         {
43                 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
44                 {
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);
47                         return MOD_RES_ALLOW;
48                 }
49         }
50         ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
51         return MOD_RES_DENY;
52 }
53
54 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
55 {
56         if (InspIRCd::IsSID(ServerName))
57                 return this->FindServerID(ServerName);
58
59         server_hash::iterator iter = serverlist.find(ServerName);
60         if (iter != serverlist.end())
61         {
62                 return iter->second;
63         }
64         else
65         {
66                 return NULL;
67         }
68 }
69
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
74  * for more details.
75  */
76 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
77 {
78         TreeServer* Found = FindServer(ServerName);
79         if (Found)
80         {
81                 return Found->GetRoute();
82         }
83         else
84         {
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);
87                 if (u)
88                 {
89                         return TreeServer::Get(u)->GetRoute();
90                 }
91
92                 return NULL;
93         }
94 }
95
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.
98  */
99 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
100 {
101         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
102         {
103                 if (InspIRCd::Match(i->first,ServerName))
104                         return i->second;
105         }
106         return NULL;
107 }
108
109 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
110 {
111         server_hash::iterator iter = sidlist.find(id);
112         if (iter != sidlist.end())
113                 return iter->second;
114         else
115                 return NULL;
116 }
117
118 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C)
119         : Creator(C), TreeRoot(NULL)
120 {
121         ServerInstance->Timers.AddTimer(&RefreshTimer);
122 }
123
124 CullResult SpanningTreeUtilities::cull()
125 {
126         const TreeServer::ChildServers& children = TreeRoot->GetChildren();
127         while (!children.empty())
128         {
129                 TreeSocket* sock = children.front()->GetSocket();
130                 sock->Close();
131         }
132
133         for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
134         {
135                 TreeSocket* s = i->first;
136                 s->Close();
137         }
138         TreeRoot->cull();
139
140         return classbase::cull();
141 }
142
143 SpanningTreeUtilities::~SpanningTreeUtilities()
144 {
145         delete TreeRoot;
146 }
147
148 // Returns a list of DIRECT servers for a specific channel
149 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list)
150 {
151         unsigned int minrank = 0;
152         if (status)
153         {
154                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
155                 if (mh)
156                         minrank = mh->GetPrefixRank();
157         }
158
159         const Channel::MemberMap& ulist = c->GetUsers();
160         for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i)
161         {
162                 if (IS_LOCAL(i->first))
163                         continue;
164
165                 if (minrank && i->second->getRank() < minrank)
166                         continue;
167
168                 if (exempt_list.find(i->first) == exempt_list.end())
169                 {
170                         TreeServer* best = TreeServer::Get(i->first);
171                         list.insert(best->GetSocket());
172                 }
173         }
174         return;
175 }
176
177 void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute)
178 {
179         const std::string& FullLine = params.str();
180
181         const TreeServer::ChildServers& children = TreeRoot->GetChildren();
182         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
183         {
184                 TreeServer* Route = *i;
185                 // Send the line if the route isn't the path to the one to be omitted
186                 if (Route != omitroute)
187                 {
188                         Route->GetSocket()->WriteLine(FullLine);
189                 }
190         }
191 }
192
193 bool SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, const std::string& target)
194 {
195         TreeServer* Route = this->BestRouteTo(target);
196         if (!Route)
197                 return false;
198
199         DoOneToOne(params, Route);
200         return true;
201 }
202
203 void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server)
204 {
205         TreeServer* ts = static_cast<TreeServer*>(server);
206         TreeSocket* sock = ts->GetSocket();
207         if (sock)
208                 sock->WriteLine(params);
209 }
210
211 void SpanningTreeUtilities::RefreshIPCache()
212 {
213         ValidIPs.clear();
214         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
215         {
216                 Link* L = *i;
217                 if (!L->Port)
218                 {
219                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port.");
220                         /* Invalid link block */
221                         continue;
222                 }
223
224                 ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end());
225
226                 irc::sockets::sockaddrs dummy;
227                 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
228                 if ((L->IPAddr == "*") || (ipvalid))
229                         ValidIPs.push_back(L->IPAddr);
230                 else if (this->Creator->DNS)
231                 {
232                         SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA);
233                         try
234                         {
235                                 this->Creator->DNS->Process(sr);
236                         }
237                         catch (DNS::Exception &)
238                         {
239                                 delete sr;
240                         }
241                 }
242         }
243 }
244
245 void SpanningTreeUtilities::ReadConfiguration()
246 {
247         ConfigTag* security = ServerInstance->Config->ConfValue("security");
248         ConfigTag* options = ServerInstance->Config->ConfValue("options");
249         FlatLinks = security->getBool("flatlinks");
250         HideULines = security->getBool("hideulines");
251         AnnounceTSChange = options->getBool("announcets");
252         AllowOptCommon = options->getBool("allowmismatch");
253         quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts");
254         PingWarnTime = options->getInt("pingwarning");
255         PingFreq = options->getInt("serverpingfreq");
256
257         if (PingFreq == 0)
258                 PingFreq = 60;
259
260         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
261                 PingWarnTime = 0;
262
263         AutoconnectBlocks.clear();
264         LinkBlocks.clear();
265         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
266         for(ConfigIter i = tags.first; i != tags.second; ++i)
267         {
268                 ConfigTag* tag = i->second;
269                 reference<Link> L = new Link(tag);
270                 std::string linkname = tag->getString("name");
271                 L->Name = linkname.c_str();
272
273                 irc::spacesepstream sep = tag->getString("allowmask");
274                 for (std::string s; sep.GetToken(s);)
275                         L->AllowMasks.push_back(s);
276
277                 L->IPAddr = tag->getString("ipaddr");
278                 L->Port = tag->getInt("port");
279                 L->SendPass = tag->getString("sendpass", tag->getString("password"));
280                 L->RecvPass = tag->getString("recvpass", tag->getString("password"));
281                 L->Fingerprint = tag->getString("fingerprint");
282                 L->HiddenFromStats = tag->getBool("statshidden");
283                 L->Timeout = tag->getDuration("timeout", 30);
284                 L->Hook = tag->getString("ssl");
285                 L->Bind = tag->getString("bind");
286                 L->Hidden = tag->getBool("hidden");
287
288                 if (L->Name.empty())
289                         throw ModuleException("Invalid configuration, found a link tag without a name!" + (!L->IPAddr.empty() ? " IP address: "+L->IPAddr : ""));
290
291                 if (L->Name.find('.') == std::string::npos)
292                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character");
293
294                 if (L->Name.length() > ServerInstance->Config->Limits.MaxHost)
295                         throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters");
296
297                 if (L->RecvPass.empty())
298                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined");
299
300                 if (L->SendPass.empty())
301                         throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined");
302
303                 if ((L->SendPass.find(' ') != std::string::npos) || (L->RecvPass.find(' ') != std::string::npos))
304                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that contains a space character which is invalid");
305
306                 if ((L->SendPass[0] == ':') || (L->RecvPass[0] == ':'))
307                         throw ModuleException("Link block '" + assign(L->Name) + "' has a password set that begins with a colon (:) which is invalid");
308
309                 if (L->IPAddr.empty())
310                 {
311                         L->IPAddr = "*";
312                         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.");
313                 }
314
315                 if (!L->Port)
316                         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.");
317
318                 L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end());
319                 LinkBlocks.push_back(L);
320         }
321
322         tags = ServerInstance->Config->ConfTags("autoconnect");
323         for(ConfigIter i = tags.first; i != tags.second; ++i)
324         {
325                 ConfigTag* tag = i->second;
326                 reference<Autoconnect> A = new Autoconnect(tag);
327                 A->Period = tag->getDuration("period", 60, 1);
328                 A->NextConnectTime = ServerInstance->Time() + A->Period;
329                 A->position = -1;
330                 irc::spacesepstream ss(tag->getString("server"));
331                 std::string server;
332                 while (ss.GetToken(server))
333                 {
334                         A->servers.push_back(server);
335                 }
336
337                 if (A->servers.empty())
338                 {
339                         throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!");
340                 }
341
342                 AutoconnectBlocks.push_back(A);
343         }
344
345         for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i)
346                 i->second->CheckULine();
347
348         RefreshIPCache();
349 }
350
351 Link* SpanningTreeUtilities::FindLink(const std::string& name)
352 {
353         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
354         {
355                 Link* x = *i;
356                 if (InspIRCd::Match(x->Name.c_str(), name.c_str(), rfc_case_insensitive_map))
357                 {
358                         return x;
359                 }
360         }
361         return NULL;
362 }
363
364 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)
365 {
366         CmdBuilder msg(prefix, message_type);
367         msg.push_raw(' ');
368         if (status != 0)
369                 msg.push_raw(status);
370         msg.push_raw(target->name).push_last(text);
371
372         TreeSocketSet list;
373         this->GetListOfServersForChannel(target, list, status, exempt_list);
374         for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i)
375         {
376                 TreeSocket* Sock = *i;
377                 if (Sock != omit)
378                         Sock->WriteLine(msg);
379         }
380 }