]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
da3417de9735d60a8c5a85d047e507a20b8c1869
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / utils.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "socket.h"
16 #include "xline.h"
17 #include "socketengine.h"
18
19 #include "main.h"
20 #include "utils.h"
21 #include "treeserver.h"
22 #include "link.h"
23 #include "treesocket.h"
24 #include "resolvers.h"
25
26 /* Create server sockets off a listener. */
27 ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
28 {
29         if (from->bind_tag->getString("type") != "servers")
30                 return MOD_RES_PASSTHRU;
31
32         std::string incomingip = client->addr();
33
34         for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
35         {
36                 if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client))
37                 {
38                         /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
39                         new TreeSocket(Utils, newsock, from, client, server);
40                         return MOD_RES_ALLOW;
41                 }
42         }
43         ServerInstance->SNO->WriteToSnoMask('l', "Server connection from %s denied (no link blocks with that IP address)", incomingip.c_str());
44         return MOD_RES_DENY;
45 }
46
47 /** Yay for fast searches!
48  * This is hundreds of times faster than recursion
49  * or even scanning a linked list, especially when
50  * there are more than a few servers to deal with.
51  * (read as: lots).
52  */
53 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
54 {
55         if (ServerInstance->IsSID(ServerName))
56                 return this->FindServerID(ServerName);
57
58         server_hash::iterator iter = serverlist.find(ServerName.c_str());
59         if (iter != serverlist.end())
60         {
61                 return iter->second;
62         }
63         else
64         {
65                 return NULL;
66         }
67 }
68
69 /** Returns the locally connected server we must route a
70  * message through to reach server 'ServerName'. This
71  * only applies to one-to-one and not one-to-many routing.
72  * See the comments for the constructor of TreeServer
73  * for more details.
74  */
75 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
76 {
77         if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
78                 return NULL;
79         TreeServer* Found = FindServer(ServerName);
80         if (Found)
81         {
82                 return Found->GetRoute();
83         }
84         else
85         {
86                 // Cheat a bit. This allows for (better) working versions of routing commands with nick based prefixes, without hassle
87                 User *u = ServerInstance->FindNick(ServerName);
88                 if (u)
89                 {
90                         Found = FindServer(u->server);
91                         if (Found)
92                                 return Found->GetRoute();
93                 }
94
95                 return NULL;
96         }
97 }
98
99 /** Find the first server matching a given glob mask.
100  * Theres no find-using-glob method of hash_map [awwww :-(]
101  * so instead, we iterate over the list using an iterator
102  * and match each one until we get a hit. Yes its slow,
103  * deal with it.
104  */
105 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
106 {
107         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
108         {
109                 if (InspIRCd::Match(i->first,ServerName))
110                         return i->second;
111         }
112         return NULL;
113 }
114
115 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
116 {
117         server_hash::iterator iter = sidlist.find(id);
118         if (iter != sidlist.end())
119                 return iter->second;
120         else
121                 return NULL;
122 }
123
124 /* A convenient wrapper that returns true if a server exists */
125 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
126 {
127         return (FindServer(ServerName) != NULL);
128 }
129
130 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
131 {
132         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
133
134         this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
135         this->ReadConfiguration();
136 }
137
138 CullResult SpanningTreeUtilities::cull()
139 {
140         while (TreeRoot->ChildCount())
141         {
142                 TreeServer* child_server = TreeRoot->GetChild(0);
143                 if (child_server)
144                 {
145                         TreeSocket* sock = child_server->GetSocket();
146                         sock->Close();
147                         ServerInstance->GlobalCulls.AddItem(sock);
148                 }
149         }
150
151         for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i)
152         {
153                 TreeSocket* s = i->first;
154                 ServerInstance->GlobalCulls.AddItem(s);
155         }
156         TreeRoot->cull();
157
158         return classbase::cull();
159 }
160
161 SpanningTreeUtilities::~SpanningTreeUtilities()
162 {
163         delete TreeRoot;
164 }
165
166 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
167 {
168         if (list.find(server) == list.end())
169                 list[server] = server;
170 }
171
172 /* returns a list of DIRECT servernames for a specific channel */
173 void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list)
174 {
175         const UserMembList *ulist = c->GetUsers();
176
177         for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
178         {
179                 if (IS_LOCAL(i->first))
180                         continue;
181
182                 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
183                         continue;
184
185                 if (exempt_list.find(i->first) == exempt_list.end())
186                 {
187                         TreeServer* best = this->BestRouteTo(i->first->server);
188                         if (best)
189                                 AddThisServer(best,list);
190                 }
191         }
192         return;
193 }
194
195 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist &params)
196 {
197         TreeServer* omitroute = this->BestRouteTo(omit);
198         unsigned int items =this->TreeRoot->ChildCount();
199         for (unsigned int x = 0; x < items; x++)
200         {
201                 TreeServer* Route = this->TreeRoot->GetChild(x);
202                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
203                 {
204                         TreeSocket* Sock = Route->GetSocket();
205                         if (Sock)
206                                 Sock->WriteLine(data);
207                 }
208         }
209         return true;
210 }
211
212 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist &params, std::string omit)
213 {
214         TreeServer* omitroute = this->BestRouteTo(omit);
215         std::string FullLine = ":" + prefix + " " + command;
216         unsigned int words = params.size();
217         for (unsigned int x = 0; x < words; x++)
218         {
219                 FullLine = FullLine + " " + params[x];
220         }
221         unsigned int items = this->TreeRoot->ChildCount();
222         for (unsigned int x = 0; x < items; x++)
223         {
224                 TreeServer* Route = this->TreeRoot->GetChild(x);
225                 // Send the line IF:
226                 // The route has a socket (its a direct connection)
227                 // The route isnt the one to be omitted
228                 // The route isnt the path to the one to be omitted
229                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
230                 {
231                         TreeSocket* Sock = Route->GetSocket();
232                         if (Sock)
233                                 Sock->WriteLine(FullLine);
234                 }
235         }
236         return true;
237 }
238
239 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist &params)
240 {
241         std::string FullLine = ":" + prefix + " " + command;
242         unsigned int words = params.size();
243         for (unsigned int x = 0; x < words; x++)
244         {
245                 FullLine = FullLine + " " + params[x];
246         }
247         unsigned int items = this->TreeRoot->ChildCount();
248         for (unsigned int x = 0; x < items; x++)
249         {
250                 TreeServer* Route = this->TreeRoot->GetChild(x);
251                 if (Route && Route->GetSocket())
252                 {
253                         TreeSocket* Sock = Route->GetSocket();
254                         if (Sock)
255                                 Sock->WriteLine(FullLine);
256                 }
257         }
258         return true;
259 }
260
261 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist &params)
262 {
263         std::string spfx = prefix;
264         std::string scmd = command;
265         return this->DoOneToMany(spfx, scmd, params);
266 }
267
268 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist &params, std::string omit)
269 {
270         std::string spfx = prefix;
271         std::string scmd = command;
272         return this->DoOneToAllButSender(spfx, scmd, params, omit);
273 }
274
275 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist &params, std::string target)
276 {
277         TreeServer* Route = this->BestRouteTo(target);
278         if (Route)
279         {
280                 std::string FullLine = ":" + prefix + " " + command;
281                 unsigned int words = params.size();
282                 for (unsigned int x = 0; x < words; x++)
283                 {
284                         FullLine = FullLine + " " + params[x];
285                 }
286                 if (Route && Route->GetSocket())
287                 {
288                         TreeSocket* Sock = Route->GetSocket();
289                         if (Sock)
290                                 Sock->WriteLine(FullLine);
291                 }
292                 return true;
293         }
294         else
295         {
296                 return false;
297         }
298 }
299
300 void SpanningTreeUtilities::RefreshIPCache()
301 {
302         ValidIPs.clear();
303         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
304         {
305                 Link* L = *i;
306                 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
307                 {
308                         if (L->Name.empty())
309                         {
310                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
311                         }
312                         else
313                         {
314                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
315                         }
316
317                         /* Invalid link block */
318                         continue;
319                 }
320
321                 if (L->AllowMask.length())
322                         ValidIPs.push_back(L->AllowMask);
323
324                 irc::sockets::sockaddrs dummy;
325                 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy);
326                 if (ipvalid)
327                         ValidIPs.push_back(L->IPAddr);
328                 else
329                 {
330                         try
331                         {
332                                 bool cached;
333                                 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
334                                 ServerInstance->AddResolver(sr, cached);
335                         }
336                         catch (...)
337                         {
338                         }
339                 }
340         }
341 }
342
343 void SpanningTreeUtilities::ReadConfiguration()
344 {
345         ConfigReader Conf;
346
347         FlatLinks = Conf.ReadFlag("security","flatlinks",0);
348         HideULines = Conf.ReadFlag("security","hideulines",0);
349         AnnounceTSChange = Conf.ReadFlag("options","announcets",0);
350         AllowOptCommon = Conf.ReadFlag("options", "allowmismatch", 0);
351         ChallengeResponse = !Conf.ReadFlag("security", "disablehmac", 0);
352         quiet_bursts = Conf.ReadFlag("performance", "quietbursts", 0);
353         PingWarnTime = Conf.ReadInteger("options", "pingwarning", 0, true);
354         PingFreq = Conf.ReadInteger("options", "serverpingfreq", 0, true);
355
356         if (PingFreq == 0)
357                 PingFreq = 60;
358
359         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
360                 PingWarnTime = 0;
361
362         AutoconnectBlocks.clear();
363         LinkBlocks.clear();
364         ValidIPs.clear();
365         ConfigTagList tags = ServerInstance->Config->ConfTags("link");
366         for(ConfigIter i = tags.first; i != tags.second; ++i)
367         {
368                 ConfigTag* tag = i->second;
369                 reference<Link> L = new Link(tag);
370                 L->Name = tag->getString("name").c_str();
371                 L->AllowMask = tag->getString("allowmask");
372                 L->IPAddr = tag->getString("ipaddr");
373                 L->Port = tag->getInt("port");
374                 L->SendPass = tag->getString("sendpass");
375                 L->RecvPass = tag->getString("recvpass");
376                 L->Fingerprint = tag->getString("fingerprint");
377                 L->HiddenFromStats = tag->getBool("statshidden");
378                 L->Timeout = tag->getInt("timeout");
379                 L->Hook = tag->getString("ssl");
380                 L->Bind = tag->getString("bind");
381                 L->Hidden = tag->getBool("hidden");
382
383                 if (L->Name.find('.') == std::string::npos)
384                         throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
385
386                 if (L->Name.length() > 64)
387                         throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
388
389                 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
390                 {
391                         ValidIPs.push_back(L->IPAddr);
392                 }
393                 else
394                 {
395                         if (L->IPAddr.empty())
396                         {
397                                 L->IPAddr = "*";
398                                 ValidIPs.push_back("*");
399                                 ServerInstance->Logs->Log("m_spanningtree",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.");
400                         }
401
402                         if (L->RecvPass.empty())
403                         {
404                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
405                         }
406
407                         if (L->SendPass.empty())
408                         {
409                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
410                         }
411
412                         if (L->Name.empty())
413                         {
414                                 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
415                         }
416
417                         if (!L->Port)
418                         {
419                                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block " + assign(L->Name) + " has no port defined, you will not be able to /connect it.");
420                         }
421                 }
422
423                 LinkBlocks.push_back(L);
424         }
425
426         tags = ServerInstance->Config->ConfTags("autoconnect");
427         for(ConfigIter i = tags.first; i != tags.second; ++i)
428         {
429                 ConfigTag* tag = i->second;
430                 reference<Autoconnect> A = new Autoconnect(tag);
431                 A->Period = tag->getInt("period");
432                 A->NextConnectTime = ServerInstance->Time() + A->Period;
433                 A->position = -1;
434                 irc::spacesepstream ss(tag->getString("server"));
435                 std::string server;
436                 while (ss.GetToken(server))
437                 {
438                         A->servers.push_back(server);
439                 }
440
441                 if (A->Period <= 0)
442                 {
443                         throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
444                 }
445
446                 if (A->servers.empty())
447                 {
448                         throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
449                 }
450
451                 AutoconnectBlocks.push_back(A);
452         }
453
454         RefreshIPCache();
455 }
456
457 Link* SpanningTreeUtilities::FindLink(const std::string& name)
458 {
459         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
460         {
461                 Link* x = *i;
462                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
463                 {
464                         return x;
465                 }
466         }
467         return NULL;
468 }