1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
17 #include "socketengine.h"
21 #include "treeserver.h"
23 #include "treesocket.h"
24 #include "resolvers.h"
26 /* Create server sockets off a listener. */
27 void ServerSocketListener::OnAcceptReady(int newsock)
31 std::string incomingip;
32 irc::sockets::satoap(&client, incomingip, port);
34 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), incomingip) != Utils->ValidIPs.end());
37 for (std::vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
39 if (*i == "*" || irc::sockets::MatchCIDR(incomingip, *i))
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);
54 /* we don't need to do anything with the pointer, creating it stores it in the necessary places */
56 new TreeSocket(Utils, newsock, this, &client, &server);
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.
65 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
67 if (ServerInstance->IsSID(ServerName))
68 return this->FindServerID(ServerName);
70 server_hash::iterator iter = serverlist.find(ServerName.c_str());
71 if (iter != serverlist.end())
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
87 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
89 if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID())
91 TreeServer* Found = FindServer(ServerName);
94 return Found->GetRoute();
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);
102 Found = FindServer(u->server);
104 return Found->GetRoute();
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,
117 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
119 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
121 if (InspIRCd::Match(i->first,ServerName))
127 TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id)
129 server_hash::iterator iter = sidlist.find(id);
130 if (iter != sidlist.end())
136 /* A convenient wrapper that returns true if a server exists */
137 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
139 return (FindServer(ServerName) != NULL);
142 SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C)
144 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str());
146 this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID());
147 ServerUser = new FakeUser(TreeRoot->GetID());
149 this->ReadConfiguration(true);
152 CullResult SpanningTreeUtilities::cull()
154 for (unsigned int i = 0; i < ServerInstance->ports.size(); i++)
156 if (ServerInstance->ports[i]->type == "servers")
157 ServerInstance->ports[i]->cull();
160 while (TreeRoot->ChildCount())
162 TreeServer* child_server = TreeRoot->GetChild(0);
165 TreeSocket* sock = child_server->GetSocket();
167 ServerInstance->GlobalCulls.AddItem(sock);
171 ServerUser->uuid = TreeRoot->GetID();
174 return classbase::cull();
177 SpanningTreeUtilities::~SpanningTreeUtilities()
179 for (unsigned int i = 0; i < ServerInstance->ports.size(); i++)
181 if (ServerInstance->ports[i]->type == "servers")
182 delete ServerInstance->ports[i];
188 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
190 if (list.find(server) == list.end())
191 list[server] = server;
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)
197 const UserMembList *ulist = c->GetUsers();
199 for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++)
201 if (IS_LOCAL(i->first))
204 if (status && !strchr(c->GetAllPrefixChars(i->first), status))
207 if (exempt_list.find(i->first) == exempt_list.end())
209 TreeServer* best = this->BestRouteTo(i->first->server);
211 AddThisServer(best,list);
217 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, parameterlist ¶ms)
219 TreeServer* omitroute = this->BestRouteTo(omit);
220 unsigned int items =this->TreeRoot->ChildCount();
221 for (unsigned int x = 0; x < items; x++)
223 TreeServer* Route = this->TreeRoot->GetChild(x);
224 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
226 TreeSocket* Sock = Route->GetSocket();
228 Sock->WriteLine(data);
234 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string omit)
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++)
241 FullLine = FullLine + " " + params[x];
243 unsigned int items = this->TreeRoot->ChildCount();
244 for (unsigned int x = 0; x < items; x++)
246 TreeServer* Route = this->TreeRoot->GetChild(x);
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))
253 TreeSocket* Sock = Route->GetSocket();
255 Sock->WriteLine(FullLine);
261 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, parameterlist ¶ms)
263 std::string FullLine = ":" + prefix + " " + command;
264 unsigned int words = params.size();
265 for (unsigned int x = 0; x < words; x++)
267 FullLine = FullLine + " " + params[x];
269 unsigned int items = this->TreeRoot->ChildCount();
270 for (unsigned int x = 0; x < items; x++)
272 TreeServer* Route = this->TreeRoot->GetChild(x);
273 if (Route && Route->GetSocket())
275 TreeSocket* Sock = Route->GetSocket();
277 Sock->WriteLine(FullLine);
283 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, parameterlist ¶ms)
285 std::string spfx = prefix;
286 std::string scmd = command;
287 return this->DoOneToMany(spfx, scmd, params);
290 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, parameterlist ¶ms, std::string omit)
292 std::string spfx = prefix;
293 std::string scmd = command;
294 return this->DoOneToAllButSender(spfx, scmd, params, omit);
297 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, parameterlist ¶ms, std::string target)
299 TreeServer* Route = this->BestRouteTo(target);
302 std::string FullLine = ":" + prefix + " " + command;
303 unsigned int words = params.size();
304 for (unsigned int x = 0; x < words; x++)
306 FullLine = FullLine + " " + params[x];
308 if (Route && Route->GetSocket())
310 TreeSocket* Sock = Route->GetSocket();
312 Sock->WriteLine(FullLine);
322 void SpanningTreeUtilities::RefreshIPCache()
325 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
328 if (L->IPAddr.empty() || L->RecvPass.empty() || L->SendPass.empty() || L->Name.empty() || !L->Port)
332 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a malformed link block (all link blocks require a name!)");
336 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block missing recvpass, sendpass, port or ipaddr.");
339 /* Invalid link block */
343 if (L->AllowMask.length())
344 ValidIPs.push_back(L->AllowMask);
346 irc::sockets::sockaddrs dummy;
347 bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, &dummy);
349 ValidIPs.push_back(L->IPAddr);
355 SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
356 ServerInstance->AddResolver(sr, cached);
365 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
371 ConfigTagList tags = ServerInstance->Config->ConfTags("bind");
372 for(ConfigIter i = tags.first; i != tags.second; ++i)
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")
381 irc::portparser portrange(Port, false);
387 while ((portno = portrange.GetToken()))
389 ServerSocketListener *listener = new ServerSocketListener(this, portno, IP, ssl);
390 if (listener->GetFd() == -1)
396 ServerInstance->ports.push_back(listener);
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);
413 if (PingWarnTime < 0 || PingWarnTime > PingFreq - 1)
416 AutoconnectBlocks.clear();
419 ConfigTagList tags = ServerInstance->Config->ConfTags("link");
420 for(ConfigIter i = tags.first; i != tags.second; ++i)
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");
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");
440 if (L->Name.length() > 64)
441 throw CoreException("The link name '"+assign(L->Name)+"' is longer than 64 characters!");
443 if ((!L->IPAddr.empty()) && (!L->RecvPass.empty()) && (!L->SendPass.empty()) && (!L->Name.empty()) && (L->Port))
445 ValidIPs.push_back(L->IPAddr);
449 if (L->IPAddr.empty())
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.");
456 if (L->RecvPass.empty())
458 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined!");
461 if (L->SendPass.empty())
463 throw CoreException("Invalid configuration for server '"+assign(L->Name)+"', sendpass not defined!");
468 throw CoreException("Invalid configuration, link tag without a name! IP address: "+L->IPAddr);
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.");
477 LinkBlocks.push_back(L);
480 tags = ServerInstance->Config->ConfTags("autoconnect");
481 for(ConfigIter i = tags.first; i != tags.second; ++i)
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;
488 irc::spacesepstream ss(tag->getString("server"));
490 while (ss.GetToken(server))
492 A->servers.push_back(server);
497 throw CoreException("Invalid configuration for autoconnect, period not a positive integer!");
500 if (A->servers.empty())
502 throw CoreException("Invalid configuration for autoconnect, server cannot be empty!");
505 AutoconnectBlocks.push_back(A);
511 Link* SpanningTreeUtilities::FindLink(const std::string& name)
513 for (std::vector<reference<Link> >::iterator i = LinkBlocks.begin(); i != LinkBlocks.end(); ++i)
516 if (InspIRCd::Match(x->Name.c_str(), name.c_str()))