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/>.
28 #include "modules/server.h"
30 #include "resolvers.h"
33 #include "treeserver.h"
35 #include "treesocket.h"
37 #include "translate.h"
39 ModuleSpanningTree::ModuleSpanningTree()
40 : Stats::EventListener(this)
46 , eventprov(this, "event/server")
52 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
53 : svsjoin(module), svspart(module), svsnick(module), metadata(module),
54 uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
55 fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
56 away(module), addline(module), delline(module), encap(module), idle(module),
57 nick(module), ping(module), pong(module), save(module),
58 server(module), squit(module), snonotice(module),
59 endburst(module), sinfo(module), num(module)
65 void SetLocalUsersServer(Server* newserver)
67 // Does not change the server of quitting users because those are not in the list
69 ServerInstance->FakeClient->server = newserver;
70 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
71 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
72 (*i)->server = newserver;
75 void ResetMembershipIds()
77 // Set all membership ids to 0
78 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
79 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
82 for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
88 void ModuleSpanningTree::init()
90 ServerInstance->SNO->EnableSnomask('l', "LINK");
94 Utils = new SpanningTreeUtilities(this);
95 Utils->TreeRoot = new TreeServer;
97 ServerInstance->PI = &protocolinterface;
99 delete ServerInstance->FakeClient->server;
100 SetLocalUsersServer(Utils->TreeRoot);
103 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
105 std::string Parent = Utils->TreeRoot->GetName();
106 if (Current->GetParent())
108 Parent = Current->GetParent()->GetName();
111 const TreeServer::ChildServers& children = Current->GetChildren();
112 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
114 TreeServer* server = *i;
115 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
119 ShowLinks(server, user, hops+1);
124 ShowLinks(server, user, hops+1);
127 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
128 if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
130 /* Or if the server is hidden and they're not an oper */
131 else if ((Current->Hidden) && (!user->IsOper()))
134 user->WriteNumeric(RPL_LINKS, Current->GetName(),
135 (((Utils->FlatLinks) && (!user->IsOper())) ? ServerInstance->Config->ServerName : Parent),
136 InspIRCd::Format("%d %s", (((Utils->FlatLinks) && (!user->IsOper())) ? 0 : hops), Current->GetDesc().c_str()));
139 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
141 ShowLinks(Utils->TreeRoot,user,0);
142 user->WriteNumeric(RPL_ENDOFLINKS, '*', "End of /LINKS list.");
145 std::string ModuleSpanningTree::TimeToStr(time_t secs)
147 time_t mins_up = secs / 60;
148 time_t hours_up = mins_up / 60;
149 time_t days_up = hours_up / 24;
151 mins_up = mins_up % 60;
152 hours_up = hours_up % 24;
153 return ((days_up ? (ConvToStr(days_up) + "d") : "")
154 + (hours_up ? (ConvToStr(hours_up) + "h") : "")
155 + (mins_up ? (ConvToStr(mins_up) + "m") : "")
156 + ConvToStr(secs) + "s");
159 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
163 for(unsigned int j=0; j < a->servers.size(); j++)
165 if (Utils->FindServer(a->servers[j]))
167 // found something in this block. Should the server fail,
168 // we want to start at the start of the list, not in the
169 // middle where we left off
174 if (on_timer && a->position >= 0)
176 if (!on_timer && a->position < 0)
180 while (a->position < (int)a->servers.size())
182 Link* x = Utils->FindLink(a->servers[a->position]);
185 ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
191 // Autoconnect chain has been fully iterated; start at the beginning on the
192 // next AutoConnectServers run
196 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
200 if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
202 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
207 if (x->IPAddr.find('/') != std::string::npos)
210 if (stat(x->IPAddr.c_str(), &sb) == -1 || !S_ISSOCK(sb.st_mode))
214 if (x->IPAddr.find(':') != std::string::npos)
217 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
223 if (inet_pton(AF_INET, x->IPAddr.c_str(),&n) < 1)
227 /* Do we already have an IP? If so, no need to resolve it. */
230 // Create a TreeServer object that will start connecting immediately in the background
231 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
232 if (newsocket->GetFd() > -1)
234 /* Handled automatically on success */
238 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
239 x->Name.c_str(), newsocket->getError().c_str());
240 ServerInstance->GlobalCulls.AddItem(newsocket);
245 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Hostname given and core_dns is not loaded, unable to resolve.", x->Name.c_str());
249 // Guess start_type from bindip aftype
250 DNS::QueryType start_type = DNS::QUERY_AAAA;
251 irc::sockets::sockaddrs bind;
252 if ((!x->Bind.empty()) && (irc::sockets::aptosa(x->Bind, 0, bind)))
254 if (bind.family() == AF_INET)
255 start_type = DNS::QUERY_A;
258 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
263 catch (DNS::Exception& e)
266 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
267 ConnectServer(y, false);
272 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
274 for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
277 if (curtime >= x->NextConnectTime)
279 x->NextConnectTime = curtime + x->Period;
280 ConnectServer(x, true);
285 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
287 SpanningTreeUtilities::TimeoutList::iterator i = Utils->timeoutlist.begin();
288 while (i != Utils->timeoutlist.end())
290 TreeSocket* s = i->first;
291 std::pair<std::string, unsigned int> p = i->second;
292 SpanningTreeUtilities::TimeoutList::iterator me = i;
294 if (s->GetLinkState() == DYING)
296 Utils->timeoutlist.erase(me);
299 else if (curtime > s->age + p.second)
301 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %u seconds)",p.first.c_str(),p.second);
302 Utils->timeoutlist.erase(me);
308 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
310 // We've already confirmed that !parameters.empty(), so this is safe
311 TreeServer* found = Utils->FindServerMask(parameters[0]);
314 if (found == Utils->TreeRoot)
316 // Pass to default VERSION handler.
317 return MOD_RES_PASSTHRU;
320 // If an oper wants to see the version then show the full version string instead of the normal,
321 // but only if it is non-empty.
322 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
323 // or the server is a 2.0 server and does not send a full version.
324 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
325 const std::string& Version = (showfull ? found->GetFullVersion() : found->GetVersion());
326 user->WriteNumeric(RPL_VERSION, Version);
330 user->WriteNumeric(ERR_NOSUCHSERVER, parameters[0], "No such server");
335 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
337 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
340 if (InspIRCd::Match(x->Name, parameters[0], ascii_case_insensitive_map))
342 if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
344 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 is ME, not connecting.", x->Name.c_str()));
348 TreeServer* CheckDupe = Utils->FindServer(x->Name);
351 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));
357 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()));
362 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: No server matching \002%s\002 could be found in the config file.", parameters[0].c_str()));
366 void ModuleSpanningTree::OnUserInvite(User* source, User* dest, Channel* channel, time_t expiry, unsigned int notifyrank, CUList& notifyexcepts)
368 if (IS_LOCAL(source))
370 CmdBuilder params(source, "INVITE");
371 params.push_back(dest->uuid);
372 params.push_back(channel->name);
373 params.push_int(channel->age);
374 params.push_back(ConvToStr(expiry));
379 ModResult ModuleSpanningTree::OnPreTopicChange(User* user, Channel* chan, const std::string& topic)
381 // XXX: Deny topic changes if the current topic set time is the current time or is in the future because
382 // other servers will drop our FTOPIC. This restriction will be removed when the protocol is updated.
383 if ((chan->topicset >= ServerInstance->Time()) && (Utils->serverlist.size() > 1))
385 user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, "Retry topic change later");
388 return MOD_RES_PASSTHRU;
391 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
393 // Drop remote events on the floor.
397 CommandFTopic::Builder(user, chan).Broadcast();
400 void ModuleSpanningTree::OnUserPostMessage(User* user, const MessageTarget& target, const MessageDetails& details)
405 const char* message_type = (details.type == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
406 if (target.type == MessageTarget::TYPE_USER)
408 User* d = target.Get<User>();
411 CmdBuilder params(user, message_type);
412 params.push_back(d->uuid);
413 params.push_last(details.text);
417 else if (target.type == MessageTarget::TYPE_CHANNEL)
419 Utils->SendChannelMessage(user->uuid, target.Get<Channel>(), details.text, target.status, details.exemptions, message_type);
421 else if (target.type == MessageTarget::TYPE_SERVER)
423 const std::string* serverglob = target.Get<std::string>();
424 CmdBuilder par(user, message_type);
425 par.push_back(*serverglob);
426 par.push_last(details.text);
431 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
433 AutoConnectServers(curtime);
434 DoConnectTimeout(curtime);
437 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
442 CommandUID::Builder(user).Broadcast();
445 CommandOpertype::Builder(user).Broadcast();
447 for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
449 ExtensionItem* item = i->first;
450 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
452 ServerInstance->PI->SendMetaData(user, item->name, value);
455 Utils->TreeRoot->UserCount++;
458 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
460 // Only do this for local users
461 if (!IS_LOCAL(memb->user))
464 // Assign the current membership id to the new Membership and increase it
465 memb->id = currmembid++;
467 if (created_by_local)
469 CommandFJoin::Builder params(memb->chan);
476 CmdBuilder params(memb->user, "IJOIN");
477 params.push_back(memb->chan->name);
478 params.push_int(memb->id);
479 if (!memb->modes.empty())
481 params.push_back(ConvToStr(memb->chan->age));
482 params.push_back(memb->modes);
488 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
490 if (user->registered != REG_ALL || !IS_LOCAL(user))
493 CmdBuilder(user, "FHOST").push(newhost).Broadcast();
496 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
498 if (user->registered != REG_ALL || !IS_LOCAL(user))
501 CmdBuilder(user, "FNAME").push_last(gecos).Broadcast();
504 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
506 if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
509 CmdBuilder(user, "FIDENT").push(ident).Broadcast();
512 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
514 if (IS_LOCAL(memb->user))
516 CmdBuilder params(memb->user, "PART");
517 params.push_back(memb->chan->name);
518 if (!partmessage.empty())
519 params.push_last(partmessage);
524 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
528 if (oper_message != reason)
529 ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
531 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
535 // Hide the message if one of the following is true:
536 // - User is being quit due to a netsplit and quietbursts is on
537 // - Server is a silent uline
538 TreeServer* server = TreeServer::Get(user);
539 bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine()));
542 ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
543 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
547 // Regardless, update the UserCount
548 TreeServer::Get(user)->UserCount--;
551 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
555 // The nick TS is updated by the core, we don't do it
556 CmdBuilder params(user, "NICK");
557 params.push_back(user->nick);
558 params.push_back(ConvToStr(user->age));
563 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);
567 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
569 if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
572 CmdBuilder params(source, "KICK");
573 params.push_back(memb->chan->name);
574 params.push_back(memb->user->uuid);
575 // If a remote user is being kicked by us then send the membership id in the kick too
576 if (!IS_LOCAL(memb->user))
577 params.push_int(memb->id);
578 params.push_last(reason);
582 void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter)
585 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
587 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
589 // Send out to other servers
590 if (!parameter.empty() && parameter[0] != '-')
592 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
593 params.push_back(parameter);
594 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
598 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
600 // Did this rehash change the description of this server?
601 const std::string& newdesc = ServerInstance->Config->ServerDesc;
602 if (newdesc != Utils->TreeRoot->GetDesc())
604 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
605 // string that is sent in the SERVER message initially and shown for example in WHOIS.
606 // We don't need to update the field itself in the Server object - the core does that.
607 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
610 // Re-read config stuff
613 Utils->ReadConfiguration();
615 catch (ModuleException& e)
617 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
618 Utils->RefreshIPCache();
619 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
620 std::string msg = "Error in configuration: ";
621 msg.append(e.GetReason());
622 ServerInstance->SNO->WriteToSnoMask('l', msg);
623 if (status.srcuser && !IS_LOCAL(status.srcuser))
624 ServerInstance->PI->SendSNONotice('L', msg);
628 void ModuleSpanningTree::OnLoadModule(Module* mod)
632 data.append(mod->ModuleSourceFile);
633 Version v = mod->GetVersion();
634 if (!v.link_data.empty())
637 data.append(v.link_data);
639 ServerInstance->PI->SendMetaData("modules", data);
642 void ModuleSpanningTree::OnUnloadModule(Module* mod)
646 ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
650 // We are being unloaded, inform modules about all servers splitting which cannot be done later when the servers are actually disconnected
651 const server_hash& servers = Utils->serverlist;
652 for (server_hash::const_iterator i = servers.begin(); i != servers.end(); ++i)
654 TreeServer* server = i->second;
655 if (!server->IsRoot())
656 FOREACH_MOD_CUSTOM(GetEventProvider(), ServerEventListener, OnServerSplit, (server));
661 // Some other module is being unloaded. If it provides an IOHook we use, we must close that server connection now.
664 // Close all connections which use an IO hook provided by this module
665 const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
666 for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
668 TreeSocket* sock = (*i)->GetSocket();
669 if (sock->GetModHook(mod))
671 sock->SendError("SSL module unloaded");
673 // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close()
678 for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
680 TreeSocket* sock = i->first;
681 if (sock->GetModHook(mod))
686 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
688 if (user->registered != REG_ALL || !IS_LOCAL(user))
691 // Note: The protocol does not allow direct umode +o;
692 // sending OPERTYPE infers +o modechange locally.
693 CommandOpertype::Builder(user).Broadcast();
696 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
698 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
702 user = ServerInstance->FakeClient;
704 CommandAddLine::Builder(x, user).Broadcast();
707 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
709 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
713 user = ServerInstance->FakeClient;
715 CmdBuilder params(user, "DELLINE");
716 params.push_back(x->type);
717 params.push_back(x->Displayable());
721 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
724 CommandAway::Builder(user, awaymsg).Broadcast();
726 return MOD_RES_PASSTHRU;
729 void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags, const std::string& output_mode)
731 if (processflags & ModeParser::MODE_LOCALONLY)
736 if (u->registered != REG_ALL)
739 CmdBuilder params(source, "MODE");
740 params.push(u->uuid);
741 params.push(output_mode);
742 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
747 CmdBuilder params(source, "FMODE");
748 params.push(c->name);
749 params.push_int(c->age);
750 params.push(output_mode);
751 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
756 CullResult ModuleSpanningTree::cull()
760 return this->Module::cull();
763 ModuleSpanningTree::~ModuleSpanningTree()
765 ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
767 Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
768 SetLocalUsersServer(newsrv);
773 Version ModuleSpanningTree::GetVersion()
775 return Version("Allows servers to be linked", VF_VENDOR);
778 /* It is IMPORTANT that m_spanningtree is the last module in the chain
779 * so that any activity it sees is FINAL, e.g. we arent going to send out
780 * a NICK message before m_cloaking has finished putting the +x on the user,
782 * Therefore, we set our priority to PRIORITY_LAST to make sure we end up at the END of
783 * the module call queue.
785 void ModuleSpanningTree::Prioritize()
787 ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
788 ServerInstance->Modules.SetPriority(this, I_OnPreTopicChange, PRIORITY_FIRST);
791 MODULE_INIT(ModuleSpanningTree)