1 #include "configreader.h"
5 #include "commands/cmd_whois.h"
6 #include "commands/cmd_stats.h"
11 #include "transport.h"
12 #include "socketengine.h"
14 #include "m_spanningtree/main.h"
15 #include "m_spanningtree/utils.h"
16 #include "m_spanningtree/treeserver.h"
17 #include "m_spanningtree/link.h"
18 #include "m_spanningtree/treesocket.h"
19 #include "m_spanningtree/resolvers.h"
21 /** Yay for fast searches!
22 * This is hundreds of times faster than recursion
23 * or even scanning a linked list, especially when
24 * there are more than a few servers to deal with.
27 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
29 server_hash::iterator iter;
30 iter = serverlist.find(ServerName.c_str());
31 if (iter != serverlist.end())
41 /** Returns the locally connected server we must route a
42 * message through to reach server 'ServerName'. This
43 * only applies to one-to-one and not one-to-many routing.
44 * See the comments for the constructor of TreeServer
47 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
49 if (ServerName.c_str() == TreeRoot->GetName())
51 TreeServer* Found = FindServer(ServerName);
54 return Found->GetRoute();
62 /** Find the first server matching a given glob mask.
63 * Theres no find-using-glob method of hash_map [awwww :-(]
64 * so instead, we iterate over the list using an iterator
65 * and match each one until we get a hit. Yes its slow,
68 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
70 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
72 if (match(i->first.c_str(),ServerName.c_str()))
78 /* A convenient wrapper that returns true if a server exists */
79 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
81 return (FindServer(ServerName) != NULL);
84 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
90 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
92 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
94 /* Did we find any modules? */
97 /* Yes, enumerate them all to find out the hook name */
98 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
100 /* Make a request to it for its name, its implementing
101 * InspSocketHook so we know its safe to do this
103 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
104 /* Build a map of them */
105 hooks[name.c_str()] = *m;
106 hooknames.push_back(name);
110 this->ReadConfiguration(true);
113 SpanningTreeUtilities::~SpanningTreeUtilities()
115 for (unsigned int i = 0; i < Bindings.size(); i++)
117 ServerInstance->SE->DelFd(Bindings[i]);
118 Bindings[i]->Close();
121 while (TreeRoot->ChildCount())
123 TreeServer* child_server = TreeRoot->GetChild(0);
126 TreeSocket* sock = child_server->GetSocket();
127 ServerInstance->SE->DelFd(sock);
135 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
137 if (list.find(server) == list.end())
138 list[server] = server;
141 /* returns a list of DIRECT servernames for a specific channel */
142 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
148 ulist = c->GetOppedUsers();
151 ulist = c->GetHalfoppedUsers();
154 ulist = c->GetVoicedUsers();
157 ulist = c->GetUsers();
160 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
162 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
164 TreeServer* best = this->BestRouteTo(i->second->server);
166 AddThisServer(best,list);
172 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
175 TreeServer* omitroute = this->BestRouteTo(omit);
176 if ((command == "NOTICE") || (command == "PRIVMSG"))
178 if (params.size() >= 2)
181 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
184 params[0] = params[0].substr(1, params[0].length()-1);
186 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
188 // special routing for private messages/notices
189 userrec* d = ServerInstance->FindNick(params[0]);
192 std::deque<std::string> par;
193 par.push_back(params[0]);
194 par.push_back(":"+params[1]);
195 this->DoOneToOne(prefix,command.c_str(),par,d->server);
199 else if (*(params[0].c_str()) == '$')
201 std::deque<std::string> par;
202 par.push_back(params[0]);
203 par.push_back(":"+params[1]);
204 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
209 chanrec* c = ServerInstance->FindChan(params[0]);
210 userrec* u = ServerInstance->FindNick(prefix);
215 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
216 GetListOfServersForChannel(c,list,pfx,elist);
218 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
220 TreeSocket* Sock = i->second->GetSocket();
221 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
223 Sock->WriteLine(data);
231 unsigned int items =this->TreeRoot->ChildCount();
232 for (unsigned int x = 0; x < items; x++)
234 TreeServer* Route = this->TreeRoot->GetChild(x);
235 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
237 TreeSocket* Sock = Route->GetSocket();
239 Sock->WriteLine(data);
245 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
247 TreeServer* omitroute = this->BestRouteTo(omit);
248 std::string FullLine = ":" + prefix + " " + command;
249 unsigned int words = params.size();
250 for (unsigned int x = 0; x < words; x++)
252 FullLine = FullLine + " " + params[x];
254 unsigned int items = this->TreeRoot->ChildCount();
255 for (unsigned int x = 0; x < items; x++)
257 TreeServer* Route = this->TreeRoot->GetChild(x);
259 // The route has a socket (its a direct connection)
260 // The route isnt the one to be omitted
261 // The route isnt the path to the one to be omitted
262 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
264 TreeSocket* Sock = Route->GetSocket();
266 Sock->WriteLine(FullLine);
272 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
274 std::string FullLine = ":" + prefix + " " + command;
275 unsigned int words = params.size();
276 for (unsigned int x = 0; x < words; x++)
278 FullLine = FullLine + " " + params[x];
280 unsigned int items = this->TreeRoot->ChildCount();
281 for (unsigned int x = 0; x < items; x++)
283 TreeServer* Route = this->TreeRoot->GetChild(x);
284 if (Route && Route->GetSocket())
286 TreeSocket* Sock = Route->GetSocket();
288 Sock->WriteLine(FullLine);
294 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
296 std::string spfx = prefix;
297 std::string scmd = command;
298 return this->DoOneToMany(spfx, scmd, params);
301 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
303 std::string spfx = prefix;
304 std::string scmd = command;
305 return this->DoOneToAllButSender(spfx, scmd, params, omit);
308 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
310 TreeServer* Route = this->BestRouteTo(target);
313 std::string FullLine = ":" + prefix + " " + command;
314 unsigned int words = params.size();
315 for (unsigned int x = 0; x < words; x++)
317 FullLine = FullLine + " " + params[x];
319 if (Route && Route->GetSocket())
321 TreeSocket* Sock = Route->GetSocket();
323 Sock->WriteLine(FullLine);
333 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
335 ConfigReader* Conf = new ConfigReader(ServerInstance);
338 for (int j =0; j < Conf->Enumerate("bind"); j++)
340 std::string Type = Conf->ReadValue("bind","type",j);
341 std::string IP = Conf->ReadValue("bind","address",j);
342 std::string Port = Conf->ReadValue("bind","port",j);
343 std::string transport = Conf->ReadValue("bind","transport",j);
344 if (Type == "servers")
346 irc::portparser portrange(Port, false);
348 while ((portno = portrange.GetToken()))
353 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
355 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for port %s:%s - maybe you forgot to load it BEFORE m_spanningtree in your config file? - Skipping this port binding", transport.c_str(), IP.c_str(), Port.c_str());
359 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
360 if (listener->GetState() == I_LISTENING)
362 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
363 Bindings.push_back(listener);
367 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
375 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
376 HideULines = Conf->ReadFlag("options","hideulines",0);
377 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
378 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
381 for (int j =0; j < Conf->Enumerate("link"); j++)
384 std::string Allow = Conf->ReadValue("link","allowmask",j);
385 L.Name = (Conf->ReadValue("link","name",j)).c_str();
386 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
387 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
388 L.Port = Conf->ReadInteger("link","port",j,true);
389 L.SendPass = Conf->ReadValue("link","sendpass",j);
390 L.RecvPass = Conf->ReadValue("link","recvpass",j);
391 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
392 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
393 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
394 L.Hook = Conf->ReadValue("link", "transport", j);
396 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
398 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for link '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping <link> tag completely.",
399 L.Hook.c_str(), L.Name.c_str());
404 L.NextConnectTime = time(NULL) + L.AutoConnect;
405 /* Bugfix by brain, do not allow people to enter bad configurations */
406 if (L.Name != ServerInstance->Config->ServerName)
408 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
410 ValidIPs.push_back(L.IPAddr);
413 ValidIPs.push_back(Allow);
415 /* Needs resolving */
417 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
422 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached);
423 ServerInstance->AddResolver(sr, cached);
425 catch (ModuleException& e)
430 LinkBlocks.push_back(L);
436 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
438 else if (L.RecvPass == "")
440 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
442 else if (L.SendPass == "")
444 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
446 else if (L.Name == "")
448 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
452 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
458 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
464 void SpanningTreeUtilities::DoFailOver(Link* x)
466 if (x->FailOver.length())
468 if (x->FailOver == x->Name)
470 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
473 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
476 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
477 Creator->ConnectServer(TryThisOne);
481 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
486 Link* SpanningTreeUtilities::FindLink(const std::string& name)
488 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
490 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))