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 "translate.h"
38 ModuleSpanningTree::ModuleSpanningTree()
39 : rconnect(this), rsquit(this), map(this)
42 , eventprov(this, "event/spanningtree")
48 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
49 : svsjoin(module), svspart(module), svsnick(module), metadata(module),
50 uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
51 fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
52 away(module), addline(module), delline(module), encap(module), idle(module),
53 nick(module), ping(module), pong(module), push(module), save(module),
54 server(module), squit(module), snonotice(module),
55 endburst(module), sinfo(module), num(module)
61 void SetLocalUsersServer(Server* newserver)
63 // Does not change the server of quitting users because those are not in the list
65 ServerInstance->FakeClient->server = newserver;
66 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
67 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
68 (*i)->server = newserver;
71 void ResetMembershipIds()
73 // Set all membership ids to 0
74 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
75 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
78 for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
84 void ModuleSpanningTree::init()
86 ServerInstance->SNO->EnableSnomask('l', "LINK");
90 Utils = new SpanningTreeUtilities(this);
91 Utils->TreeRoot = new TreeServer;
93 ServerInstance->PI = &protocolinterface;
95 delete ServerInstance->FakeClient->server;
96 SetLocalUsersServer(Utils->TreeRoot);
99 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
101 std::string Parent = Utils->TreeRoot->GetName();
102 if (Current->GetParent())
104 Parent = Current->GetParent()->GetName();
107 const TreeServer::ChildServers& children = Current->GetChildren();
108 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
110 TreeServer* server = *i;
111 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
115 ShowLinks(server, user, hops+1);
120 ShowLinks(server, user, hops+1);
123 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
124 if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
126 /* Or if the server is hidden and they're not an oper */
127 else if ((Current->Hidden) && (!user->IsOper()))
130 user->WriteNumeric(RPL_LINKS, Current->GetName(),
131 (((Utils->FlatLinks) && (!user->IsOper())) ? ServerInstance->Config->ServerName : Parent),
132 InspIRCd::Format("%d %s", (((Utils->FlatLinks) && (!user->IsOper())) ? 0 : hops), Current->GetDesc().c_str()));
135 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
137 ShowLinks(Utils->TreeRoot,user,0);
138 user->WriteNumeric(RPL_ENDOFLINKS, '*', "End of /LINKS list.");
141 std::string ModuleSpanningTree::TimeToStr(time_t secs)
143 time_t mins_up = secs / 60;
144 time_t hours_up = mins_up / 60;
145 time_t days_up = hours_up / 24;
147 mins_up = mins_up % 60;
148 hours_up = hours_up % 24;
149 return ((days_up ? (ConvToStr(days_up) + "d") : "")
150 + (hours_up ? (ConvToStr(hours_up) + "h") : "")
151 + (mins_up ? (ConvToStr(mins_up) + "m") : "")
152 + ConvToStr(secs) + "s");
155 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
159 for(unsigned int j=0; j < a->servers.size(); j++)
161 if (Utils->FindServer(a->servers[j]))
163 // found something in this block. Should the server fail,
164 // we want to start at the start of the list, not in the
165 // middle where we left off
170 if (on_timer && a->position >= 0)
172 if (!on_timer && a->position < 0)
176 while (a->position < (int)a->servers.size())
178 Link* x = Utils->FindLink(a->servers[a->position]);
181 ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
187 // Autoconnect chain has been fully iterated; start at the beginning on the
188 // next AutoConnectServers run
192 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
196 if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
198 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
202 DNS::QueryType start_type = DNS::QUERY_AAAA;
203 if (strchr(x->IPAddr.c_str(),':'))
206 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
212 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
216 /* Do we already have an IP? If so, no need to resolve it. */
219 // Create a TreeServer object that will start connecting immediately in the background
220 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
221 if (newsocket->GetFd() > -1)
223 /* Handled automatically on success */
227 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
228 x->Name.c_str(), newsocket->getError().c_str());
229 ServerInstance->GlobalCulls.AddItem(newsocket);
234 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());
238 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
243 catch (DNS::Exception& e)
246 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
247 ConnectServer(y, false);
252 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
254 for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
257 if (curtime >= x->NextConnectTime)
259 x->NextConnectTime = curtime + x->Period;
260 ConnectServer(x, true);
265 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
267 std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
268 while (i != Utils->timeoutlist.end())
270 TreeSocket* s = i->first;
271 std::pair<std::string, int> p = i->second;
272 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
274 if (s->GetLinkState() == DYING)
276 Utils->timeoutlist.erase(me);
279 else if (curtime > s->age + p.second)
281 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
282 Utils->timeoutlist.erase(me);
288 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
290 // We've already confirmed that !parameters.empty(), so this is safe
291 TreeServer* found = Utils->FindServerMask(parameters[0]);
294 if (found == Utils->TreeRoot)
296 // Pass to default VERSION handler.
297 return MOD_RES_PASSTHRU;
300 // If an oper wants to see the version then show the full version string instead of the normal,
301 // but only if it is non-empty.
302 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
303 // or the server is a 2.0 server and does not send a full version.
304 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
305 const std::string& Version = (showfull ? found->GetFullVersion() : found->GetVersion());
306 user->WriteNumeric(RPL_VERSION, Version);
310 user->WriteNumeric(ERR_NOSUCHSERVER, parameters[0], "No such server");
315 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
317 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
320 if (InspIRCd::Match(x->Name.c_str(),parameters[0], rfc_case_insensitive_map))
322 if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
324 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 is ME, not connecting.", x->Name.c_str()));
328 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
331 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Connecting to server: \002%s\002 (%s:%d)", x->Name.c_str(), (x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()), x->Port));
337 user->WriteRemoteNotice(InspIRCd::Format("*** 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()));
342 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: No server matching \002%s\002 could be found in the config file.", parameters[0].c_str()));
346 void ModuleSpanningTree::OnUserInvite(User* source, User* dest, Channel* channel, time_t expiry, unsigned int notifyrank, CUList& notifyexcepts)
348 if (IS_LOCAL(source))
350 CmdBuilder params(source, "INVITE");
351 params.push_back(dest->uuid);
352 params.push_back(channel->name);
353 params.push_int(channel->age);
354 params.push_back(ConvToStr(expiry));
359 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
361 // Drop remote events on the floor.
365 CommandFTopic::Builder(user, chan).Broadcast();
368 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
373 const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
374 if (target_type == TYPE_USER)
376 User* d = (User*) dest;
379 CmdBuilder params(user, message_type);
380 params.push_back(d->uuid);
381 params.push_last(text);
385 else if (target_type == TYPE_CHANNEL)
387 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
389 else if (target_type == TYPE_SERVER)
391 char* target = (char*) dest;
392 CmdBuilder par(user, message_type);
393 par.push_back(target);
399 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
401 AutoConnectServers(curtime);
402 DoConnectTimeout(curtime);
405 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
410 CommandUID::Builder(user).Broadcast();
413 CommandOpertype::Builder(user).Broadcast();
415 for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
417 ExtensionItem* item = i->first;
418 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
420 ServerInstance->PI->SendMetaData(user, item->name, value);
423 Utils->TreeRoot->UserCount++;
426 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
428 // Only do this for local users
429 if (!IS_LOCAL(memb->user))
432 // Assign the current membership id to the new Membership and increase it
433 memb->id = currmembid++;
435 if (created_by_local)
437 CommandFJoin::Builder params(memb->chan);
444 CmdBuilder params(memb->user, "IJOIN");
445 params.push_back(memb->chan->name);
446 params.push_int(memb->id);
447 if (!memb->modes.empty())
449 params.push_back(ConvToStr(memb->chan->age));
450 params.push_back(memb->modes);
456 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
458 if (user->registered != REG_ALL || !IS_LOCAL(user))
461 CmdBuilder(user, "FHOST").push(newhost).Broadcast();
464 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
466 if (user->registered != REG_ALL || !IS_LOCAL(user))
469 CmdBuilder(user, "FNAME").push_last(gecos).Broadcast();
472 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
474 if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
477 CmdBuilder(user, "FIDENT").push(ident).Broadcast();
480 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
482 if (IS_LOCAL(memb->user))
484 CmdBuilder params(memb->user, "PART");
485 params.push_back(memb->chan->name);
486 if (!partmessage.empty())
487 params.push_last(partmessage);
492 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
496 if (oper_message != reason)
497 ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
499 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
503 // Hide the message if one of the following is true:
504 // - User is being quit due to a netsplit and quietbursts is on
505 // - Server is a silent uline
506 TreeServer* server = TreeServer::Get(user);
507 bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine()));
510 ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
511 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
515 // Regardless, update the UserCount
516 TreeServer::Get(user)->UserCount--;
519 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
523 // The nick TS is updated by the core, we don't do it
524 CmdBuilder params(user, "NICK");
525 params.push_back(user->nick);
526 params.push_back(ConvToStr(user->age));
531 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Changed nick of remote user %s from %s to %s TS %lu by ourselves!", user->uuid.c_str(), oldnick.c_str(), user->nick.c_str(), (unsigned long) user->age);
535 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
537 if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
540 CmdBuilder params(source, "KICK");
541 params.push_back(memb->chan->name);
542 params.push_back(memb->user->uuid);
543 // If a remote user is being kicked by us then send the membership id in the kick too
544 if (!IS_LOCAL(memb->user))
545 params.push_int(memb->id);
546 params.push_last(reason);
550 void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter)
553 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
555 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
557 // Send out to other servers
558 if (!parameter.empty() && parameter[0] != '-')
560 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
561 params.push_back(parameter);
562 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
566 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
568 // Did this rehash change the description of this server?
569 const std::string& newdesc = ServerInstance->Config->ServerDesc;
570 if (newdesc != Utils->TreeRoot->GetDesc())
572 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
573 // string that is sent in the SERVER message initially and shown for example in WHOIS.
574 // We don't need to update the field itself in the Server object - the core does that.
575 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
578 // Re-read config stuff
581 Utils->ReadConfiguration();
583 catch (ModuleException& e)
585 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
586 Utils->RefreshIPCache();
587 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
588 std::string msg = "Error in configuration: ";
589 msg.append(e.GetReason());
590 ServerInstance->SNO->WriteToSnoMask('l', msg);
591 if (status.srcuser && !IS_LOCAL(status.srcuser))
592 ServerInstance->PI->SendSNONotice('L', msg);
596 void ModuleSpanningTree::OnLoadModule(Module* mod)
600 data.append(mod->ModuleSourceFile);
601 Version v = mod->GetVersion();
602 if (!v.link_data.empty())
605 data.append(v.link_data);
607 ServerInstance->PI->SendMetaData("modules", data);
610 void ModuleSpanningTree::OnUnloadModule(Module* mod)
614 ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
617 // Close all connections which use an IO hook provided by this module
618 const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
619 for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
621 TreeSocket* sock = (*i)->GetSocket();
622 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
624 sock->SendError("SSL module unloaded");
626 // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close()
631 for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
633 TreeSocket* sock = i->first;
634 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
639 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
641 if (user->registered != REG_ALL || !IS_LOCAL(user))
644 // Note: The protocol does not allow direct umode +o;
645 // sending OPERTYPE infers +o modechange locally.
646 CommandOpertype::Builder(user).Broadcast();
649 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
651 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
655 user = ServerInstance->FakeClient;
657 CommandAddLine::Builder(x, user).Broadcast();
660 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
662 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
666 user = ServerInstance->FakeClient;
668 CmdBuilder params(user, "DELLINE");
669 params.push_back(x->type);
670 params.push_back(x->Displayable());
674 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
677 CommandAway::Builder(user, awaymsg).Broadcast();
679 return MOD_RES_PASSTHRU;
682 void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags, const std::string& output_mode)
684 if (processflags & ModeParser::MODE_LOCALONLY)
689 if (u->registered != REG_ALL)
692 CmdBuilder params(source, "MODE");
693 params.push(u->uuid);
694 params.push(output_mode);
695 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
700 CmdBuilder params(source, "FMODE");
701 params.push(c->name);
702 params.push_int(c->age);
703 params.push(output_mode);
704 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
709 CullResult ModuleSpanningTree::cull()
713 return this->Module::cull();
716 ModuleSpanningTree::~ModuleSpanningTree()
718 ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
720 Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
721 SetLocalUsersServer(newsrv);
726 Version ModuleSpanningTree::GetVersion()
728 return Version("Allows servers to be linked", VF_VENDOR);
731 /* It is IMPORTANT that m_spanningtree is the last module in the chain
732 * so that any activity it sees is FINAL, e.g. we arent going to send out
733 * a NICK message before m_cloaking has finished putting the +x on the user,
735 * Therefore, we set our priority to PRIORITY_LAST to make sure we end up at the END of
736 * the module call queue.
738 void ModuleSpanningTree::Prioritize()
740 ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
743 MODULE_INIT(ModuleSpanningTree)