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