]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/utils.cpp
Change User::oper to an OperInfo reference
[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                 for (int j = 0; ; j++)
372                 {
373                         ConfigTag* tag = ServerInstance->Config->ConfValue("bind", j);
374                         if (!tag)
375                                 break;
376                         std::string Type = tag->getString("type");
377                         std::string IP = tag->getString("address");
378                         std::string Port = tag->getString("port");
379                         std::string ssl = tag->getString("ssl");
380                         if (Type == "servers")
381                         {
382                                 irc::portparser portrange(Port, false);
383                                 int portno = -1;
384
385                                 if (IP == "*")
386                                         IP.clear();
387
388                                 while ((portno = portrange.GetToken()))
389                                 {
390                                         ServerSocketListener *listener = new ServerSocketListener(this, portno, IP, ssl);
391                                         if (listener->GetFd() == -1)
392                                         {
393                                                 delete listener;
394                                                 continue;
395                                         }
396
397                                         ServerInstance->ports.push_back(listener);
398                                 }
399                         }
400                 }
401         }
402         FlatLinks = Conf.ReadFlag("security","flatlinks",0);
403         HideULines = Conf.ReadFlag("security","hideulines",0);
404         AnnounceTSChange = Conf.ReadFlag("options","announcets",0);
405         AllowOptCommon = Conf.ReadFlag("options", "allowmismatch", 0);
406         ChallengeResponse = !Conf.ReadFlag("security", "disablehmac", 0);
407         quiet_bursts = Conf.ReadFlag("performance", "quietbursts", 0);
408         PingWarnTime = Conf.ReadInteger("options", "pingwarning", 0, true);
409         PingFreq = Conf.ReadInteger("options", "serverpingfreq", 0, true);
410
411         if (PingFreq == 0)
412                 PingFreq = 60;
413
414         if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
415                 PingWarnTime = 0;
416
417         AutoconnectBlocks.clear();
418         LinkBlocks.clear();
419         ValidIPs.clear();
420         for (int j = 0;; ++j)
421         {
422                 ConfigTag* tag = ServerInstance->Config->ConfValue("link", j);
423                 if (!tag)
424                         break;
425                 reference<Link> L = new Link(tag);
426                 L->Name = tag->getString("name").c_str();
427                 L->AllowMask = tag->getString("allowmask");
428                 L->IPAddr = tag->getString("ipaddr");
429                 L->Port = tag->getInt("port");
430                 L->SendPass = tag->getString("sendpass");
431                 L->RecvPass = tag->getString("recvpass");
432                 L->Fingerprint = tag->getString("fingerprint");
433                 L->HiddenFromStats = tag->getBool("statshidden");
434                 L->Timeout = tag->getInt("timeout");
435                 L->Hook = tag->getString("ssl");
436                 L->Bind = tag->getString("bind");
437                 L->Hidden = tag->getBool("hidden");
438
439                 if (L->Name.find('.') == std::string::npos)
440                         throw CoreException("The link name '"+assign(L->Name)+"' is invalid and must contain at least one '.' character");
441
442                 if (L->Name.length() > 64)
443                         throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
444
445                 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
446                 {
447                         ValidIPs.push_back(L->IPAddr);
448                 }
449                 else
450                 {
451                         if (L->IPAddr.empty())
452                         {
453                                 L->IPAddr = "*";
454                                 ValidIPs.push_back("*");
455                                 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.");
456                         }
457
458                         if (L->RecvPass.empty())
459                         {
460                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
461                         }
462
463                         if (L->SendPass.empty())
464                         {
465                                 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
466                         }
467
468                         if (L->Name.empty())
469                         {
470                                 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
471                         }
472
473                         if (!L->Port)
474                         {
475                                 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.");
476                         }
477                 }
478
479                 LinkBlocks.push_back(L);
480         }
481
482         for (int j = 0;; ++j)
483         {
484                 ConfigTag* tag = ServerInstance->Config->ConfValue("autoconnect", j);
485                 if (!tag)
486                         break;
487                 reference<Autoconnect> A = new Autoconnect(tag);
488                 A->Period = tag->getInt("period");
489                 A->NextConnectTime = ServerInstance->Time() + A->Period;
490                 A->position = -1;
491                 irc::spacesepstream ss(tag->getString("server"));
492                 std::string server;
493                 while (ss.GetToken(server))
494                 {
495                         A->servers.push_back(server);
496                 }
497
498                 if (A->Period <= 0)
499                 {
500                         throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
501                 }
502
503                 if (A->servers.empty())
504                 {
505                         throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
506                 }
507
508                 AutoconnectBlocks.push_back(A);
509         }
510
511         RefreshIPCache();
512 }
513
514 Link* SpanningTreeUtilities::FindLink(const std::string& name)
515 {
516         for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
517         {
518                 Link* x = *i;
519                 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))
520                 {
521                         return x;
522                 }
523         }
524         return NULL;
525 }