2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2009 Craig Edwards <craigedwards@brainbox.cc>
6 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
7 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 #include "resolvers.h"
32 #include "treeserver.h"
34 #include "treesocket.h"
36 #include "protocolinterface.h"
38 ModuleSpanningTree::ModuleSpanningTree()
39 : rconnect(this), rsquit(this), map(this)
40 , commands(NULL), DNS(this, "DNS")
44 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
45 : svsjoin(module), svspart(module), svsnick(module), metadata(module),
46 uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
47 fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
48 away(module), addline(module), delline(module), encap(module), idle(module),
49 nick(module), ping(module), pong(module), push(module), save(module),
50 server(module), squit(module), snonotice(module), version(module),
51 burst(module), endburst(module)
57 void SetLocalUsersServer(Server* newserver)
59 ServerInstance->FakeClient->server = newserver;
60 const LocalUserList& list = ServerInstance->Users->local_users;
61 for (LocalUserList::const_iterator i = list.begin(); i != list.end(); ++i)
62 (*i)->server = newserver;
66 void ModuleSpanningTree::init()
68 ServerInstance->SNO->EnableSnomask('l', "LINK");
70 Utils = new SpanningTreeUtilities(this);
71 Utils->TreeRoot = new TreeServer;
72 commands = new SpanningTreeCommands(this);
74 delete ServerInstance->PI;
75 ServerInstance->PI = new SpanningTreeProtocolInterface;
77 delete ServerInstance->FakeClient->server;
78 SetLocalUsersServer(Utils->TreeRoot);
81 SplitInProgress = false;
83 // update our local user count
84 Utils->TreeRoot->UserCount = ServerInstance->Users->local_users.size();
87 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
89 std::string Parent = Utils->TreeRoot->GetName();
90 if (Current->GetParent())
92 Parent = Current->GetParent()->GetName();
95 const TreeServer::ChildServers& children = Current->GetChildren();
96 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
98 TreeServer* server = *i;
99 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
103 ShowLinks(server, user, hops+1);
108 ShowLinks(server, user, hops+1);
111 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
112 if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
114 /* Or if the server is hidden and they're not an oper */
115 else if ((Current->Hidden) && (!user->IsOper()))
118 user->WriteNumeric(RPL_LINKS, "%s %s :%d %s", Current->GetName().c_str(),
119 (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(),
120 (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops,
121 Current->GetDesc().c_str());
124 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
126 ShowLinks(Utils->TreeRoot,user,0);
127 user->WriteNumeric(RPL_ENDOFLINKS, "* :End of /LINKS list.");
130 std::string ModuleSpanningTree::TimeToStr(time_t secs)
132 time_t mins_up = secs / 60;
133 time_t hours_up = mins_up / 60;
134 time_t days_up = hours_up / 24;
136 mins_up = mins_up % 60;
137 hours_up = hours_up % 24;
138 return ((days_up ? (ConvToStr(days_up) + "d") : "")
139 + (hours_up ? (ConvToStr(hours_up) + "h") : "")
140 + (mins_up ? (ConvToStr(mins_up) + "m") : "")
141 + ConvToStr(secs) + "s");
144 void ModuleSpanningTree::DoPingChecks(time_t curtime)
147 * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
148 * This prevents lost REMOTECONNECT notices
150 long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
153 for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
155 TreeServer *s = i->second;
161 if (s->GetSocket()->GetLinkState() == DYING)
163 s->GetSocket()->Close();
167 // Do not ping servers that are not fully connected yet!
168 // Servers which are connected to us have IsLocal() == true and if they're fully connected
169 // then Socket->LinkState == CONNECTED. Servers that are linked to another server are always fully connected.
170 if (s->IsLocal() && s->GetSocket()->GetLinkState() != CONNECTED)
173 // Now do PING checks on all servers
174 // Only ping if this server needs one
175 if (curtime >= s->NextPingTime())
177 // And if they answered the last
178 if (s->AnsweredLastPing())
180 // They did, send a ping to them
181 s->SetNextPingTime(curtime + Utils->PingFreq);
182 s->GetSocket()->WriteLine(":" + ServerInstance->Config->GetSID() + " PING " + s->GetID());
183 s->LastPingMsec = ts;
187 // They didn't answer the last ping, if they are locally connected, get rid of them.
190 TreeSocket* sock = s->GetSocket();
191 sock->SendError("Ping timeout");
198 // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
199 if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
201 /* The server hasnt responded, send a warning to opers */
202 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
208 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
212 for(unsigned int j=0; j < a->servers.size(); j++)
214 if (Utils->FindServer(a->servers[j]))
216 // found something in this block. Should the server fail,
217 // we want to start at the start of the list, not in the
218 // middle where we left off
223 if (on_timer && a->position >= 0)
225 if (!on_timer && a->position < 0)
229 while (a->position < (int)a->servers.size())
231 Link* x = Utils->FindLink(a->servers[a->position]);
234 ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
240 // Autoconnect chain has been fully iterated; start at the beginning on the
241 // next AutoConnectServers run
245 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
249 if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
251 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
255 DNS::QueryType start_type = DNS::QUERY_AAAA;
256 if (strchr(x->IPAddr.c_str(),':'))
259 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
265 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
269 /* Do we already have an IP? If so, no need to resolve it. */
272 /* Gave a hook, but it wasnt one we know */
273 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
274 if (newsocket->GetFd() > -1)
276 /* Handled automatically on success */
280 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
281 x->Name.c_str(), newsocket->getError().c_str());
282 ServerInstance->GlobalCulls.AddItem(newsocket);
287 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Hostname given and m_dns.so is not loaded, unable to resolve.", x->Name.c_str());
291 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
296 catch (DNS::Exception& e)
299 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
300 ConnectServer(y, false);
305 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
307 for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
310 if (curtime >= x->NextConnectTime)
312 x->NextConnectTime = curtime + x->Period;
313 ConnectServer(x, true);
318 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
320 std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
321 while (i != Utils->timeoutlist.end())
323 TreeSocket* s = i->first;
324 std::pair<std::string, int> p = i->second;
325 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
327 if (s->GetLinkState() == DYING)
329 Utils->timeoutlist.erase(me);
332 else if (curtime > s->age + p.second)
334 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
335 Utils->timeoutlist.erase(me);
341 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
343 // we've already checked if pcnt > 0, so this is safe
344 TreeServer* found = Utils->FindServerMask(parameters[0]);
347 if (found == Utils->TreeRoot)
349 // Pass to default VERSION handler.
350 return MOD_RES_PASSTHRU;
352 std::string Version = found->GetVersion();
353 user->WriteNumeric(RPL_VERSION, ":%s", Version.c_str());
357 user->WriteNumeric(ERR_NOSUCHSERVER, "%s :No such server", parameters[0].c_str());
362 /* This method will attempt to get a message to a remote user.
364 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
367 VAFORMAT(text, format, format);
370 user->WriteNotice(text);
372 ServerInstance->PI->SendUserNotice(user, text);
375 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
377 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
380 if (InspIRCd::Match(x->Name.c_str(),parameters[0], rfc_case_insensitive_map))
382 if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
384 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
388 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
391 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
397 RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002", x->Name.c_str(), CheckDupe->GetParent()->GetName().c_str());
402 RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
406 void ModuleSpanningTree::On005Numeric(std::map<std::string, std::string>& tokens)
411 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
413 if (IS_LOCAL(source))
415 CmdBuilder params(source, "INVITE");
416 params.push_back(dest->uuid);
417 params.push_back(channel->name);
418 params.push_back(ConvToStr(expiry));
423 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
425 // Drop remote events on the floor.
429 CommandFTopic::Builder(user, chan).Broadcast();
432 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
437 const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
438 if (target_type == TYPE_USER)
440 User* d = (User*) dest;
443 CmdBuilder params(user, message_type);
444 params.push_back(d->uuid);
445 params.push_last(text);
449 else if (target_type == TYPE_CHANNEL)
451 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
453 else if (target_type == TYPE_SERVER)
455 char* target = (char*) dest;
456 CmdBuilder par(user, message_type);
457 par.push_back(target);
463 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
465 AutoConnectServers(curtime);
466 DoPingChecks(curtime);
467 DoConnectTimeout(curtime);
470 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
475 CommandUID::Builder(user).Broadcast();
478 CommandOpertype::Builder(user).Broadcast();
480 for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
482 ExtensionItem* item = i->first;
483 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
485 ServerInstance->PI->SendMetaData(user, item->name, value);
488 Utils->TreeRoot->UserCount++;
491 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
493 // Only do this for local users
494 if (!IS_LOCAL(memb->user))
497 if (created_by_local)
499 CmdBuilder params("FJOIN");
500 params.push_back(memb->chan->name);
501 params.push_back(ConvToStr(memb->chan->age));
502 params.push_raw(" +").push_raw(memb->chan->ChanModes(true));
503 params.push(memb->modes).push_raw(',').push_raw(memb->user->uuid);
508 CmdBuilder params(memb->user, "IJOIN");
509 params.push_back(memb->chan->name);
510 if (!memb->modes.empty())
512 params.push_back(ConvToStr(memb->chan->age));
513 params.push_back(memb->modes);
519 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
521 if (user->registered != REG_ALL || !IS_LOCAL(user))
524 CmdBuilder(user, "FHOST").push(newhost).Broadcast();
527 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
529 if (user->registered != REG_ALL || !IS_LOCAL(user))
532 CmdBuilder(user, "FNAME").push_last(gecos).Broadcast();
535 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
537 if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
540 CmdBuilder(user, "FIDENT").push(ident).Broadcast();
543 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
545 if (IS_LOCAL(memb->user))
547 CmdBuilder params(memb->user, "PART");
548 params.push_back(memb->chan->name);
549 if (!partmessage.empty())
550 params.push_last(partmessage);
555 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
559 if (oper_message != reason)
560 ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
562 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
566 // Hide the message if one of the following is true:
567 // - User is being quit due to a netsplit and quietbursts is on
568 // - Server is a silent uline
569 bool hide = (((this->SplitInProgress) && (Utils->quiet_bursts)) || (user->server->IsSilentULine()));
572 ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
573 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
577 // Regardless, We need to modify the user Counts..
578 TreeServer::Get(user)->UserCount--;
581 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
585 // The nick TS is updated by the core, we don't do it
586 CmdBuilder params(user, "NICK");
587 params.push_back(user->nick);
588 params.push_back(ConvToStr(user->age));
591 else if (!loopCall && user->nick == user->uuid)
593 CmdBuilder params("SAVE");
594 params.push_back(user->uuid);
595 params.push_back(ConvToStr(user->age));
600 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
602 if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
605 CmdBuilder params(source, "KICK");
606 params.push_back(memb->chan->name);
607 params.push_back(memb->user->uuid);
608 params.push_last(reason);
612 void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter)
615 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
617 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
619 // Send out to other servers
620 if (!parameter.empty() && parameter[0] != '-')
622 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
623 params.push_back(parameter);
624 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
628 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
630 // Re-read config stuff
633 Utils->ReadConfiguration();
635 catch (ModuleException& e)
637 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
638 Utils->RefreshIPCache();
639 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
640 std::string msg = "Error in configuration: ";
641 msg.append(e.GetReason());
642 ServerInstance->SNO->WriteToSnoMask('l', msg);
643 if (status.srcuser && !IS_LOCAL(status.srcuser))
644 ServerInstance->PI->SendSNONotice('L', msg);
648 void ModuleSpanningTree::OnLoadModule(Module* mod)
652 data.append(mod->ModuleSourceFile);
653 Version v = mod->GetVersion();
654 if (!v.link_data.empty())
657 data.append(v.link_data);
659 ServerInstance->PI->SendMetaData("modules", data);
662 void ModuleSpanningTree::OnUnloadModule(Module* mod)
666 ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
668 // Close all connections which use an IO hook provided by this module
669 const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
670 for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
672 TreeSocket* sock = (*i)->GetSocket();
673 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
675 sock->SendError("SSL module unloaded");
680 for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
682 TreeSocket* sock = i->first;
683 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
688 // note: the protocol does not allow direct umode +o except
689 // via NICK with 8 params. sending OPERTYPE infers +o modechange
691 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
693 if (user->registered != REG_ALL || !IS_LOCAL(user))
695 CommandOpertype::Builder(user).Broadcast();
698 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
700 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
704 user = ServerInstance->FakeClient;
706 CommandAddLine::Builder(x, user).Broadcast();
709 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
711 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
715 user = ServerInstance->FakeClient;
717 CmdBuilder params(user, "DELLINE");
718 params.push_back(x->type);
719 params.push_back(x->Displayable());
723 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
726 CommandAway::Builder(user, awaymsg).Broadcast();
728 return MOD_RES_PASSTHRU;
731 CullResult ModuleSpanningTree::cull()
735 return this->Module::cull();
738 ModuleSpanningTree::~ModuleSpanningTree()
740 delete ServerInstance->PI;
741 ServerInstance->PI = new ProtocolInterface;
743 Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
744 SetLocalUsersServer(newsrv);
746 /* This will also free the listeners */
752 Version ModuleSpanningTree::GetVersion()
754 return Version("Allows servers to be linked", VF_VENDOR);
757 /* It is IMPORTANT that m_spanningtree is the last module in the chain
758 * so that any activity it sees is FINAL, e.g. we arent going to send out
759 * a NICK message before m_cloaking has finished putting the +x on the user,
761 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
762 * the module call queue.
764 void ModuleSpanningTree::Prioritize()
766 ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
769 MODULE_INIT(ModuleSpanningTree)