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 : Away::EventListener(this)
41 , Stats::EventListener(this)
47 , eventprov(this, "event/server")
50 , tagevprov(this, "event/messagetag")
55 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
56 : svsjoin(module), svspart(module), svsnick(module), metadata(module),
57 uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
58 fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
59 away(module), addline(module), delline(module), encap(module), idle(module),
60 nick(module), ping(module), pong(module), save(module),
61 server(module), squit(module), snonotice(module),
62 endburst(module), sinfo(module), num(module)
68 void SetLocalUsersServer(Server* newserver)
70 // Does not change the server of quitting users because those are not in the list
72 ServerInstance->FakeClient->server = newserver;
73 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
74 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
75 (*i)->server = newserver;
78 void ResetMembershipIds()
80 // Set all membership ids to 0
81 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
82 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
85 for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
91 void ModuleSpanningTree::init()
93 ServerInstance->SNO->EnableSnomask('l', "LINK");
97 Utils = new SpanningTreeUtilities(this);
98 Utils->TreeRoot = new TreeServer;
100 ServerInstance->PI = &protocolinterface;
102 delete ServerInstance->FakeClient->server;
103 SetLocalUsersServer(Utils->TreeRoot);
106 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
108 std::string Parent = Utils->TreeRoot->GetName();
109 if (Current->GetParent())
111 Parent = Current->GetParent()->GetName();
114 const TreeServer::ChildServers& children = Current->GetChildren();
115 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
117 TreeServer* server = *i;
118 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
122 ShowLinks(server, user, hops+1);
127 ShowLinks(server, user, hops+1);
130 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
131 if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
133 /* Or if the server is hidden and they're not an oper */
134 else if ((Current->Hidden) && (!user->IsOper()))
137 user->WriteNumeric(RPL_LINKS, Current->GetName(),
138 (((Utils->FlatLinks) && (!user->IsOper())) ? ServerInstance->Config->ServerName : Parent),
139 InspIRCd::Format("%d %s", (((Utils->FlatLinks) && (!user->IsOper())) ? 0 : hops), Current->GetDesc().c_str()));
142 void ModuleSpanningTree::HandleLinks(const CommandBase::Params& parameters, User* user)
144 ShowLinks(Utils->TreeRoot,user,0);
145 user->WriteNumeric(RPL_ENDOFLINKS, '*', "End of /LINKS list.");
148 std::string ModuleSpanningTree::TimeToStr(time_t secs)
150 time_t mins_up = secs / 60;
151 time_t hours_up = mins_up / 60;
152 time_t days_up = hours_up / 24;
154 mins_up = mins_up % 60;
155 hours_up = hours_up % 24;
156 return ((days_up ? (ConvToStr(days_up) + "d") : "")
157 + (hours_up ? (ConvToStr(hours_up) + "h") : "")
158 + (mins_up ? (ConvToStr(mins_up) + "m") : "")
159 + ConvToStr(secs) + "s");
162 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
166 for(unsigned int j=0; j < a->servers.size(); j++)
168 if (Utils->FindServer(a->servers[j]))
170 // found something in this block. Should the server fail,
171 // we want to start at the start of the list, not in the
172 // middle where we left off
177 if (on_timer && a->position >= 0)
179 if (!on_timer && a->position < 0)
183 while (a->position < (int)a->servers.size())
185 Link* x = Utils->FindLink(a->servers[a->position]);
188 ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
194 // Autoconnect chain has been fully iterated; start at the beginning on the
195 // next AutoConnectServers run
199 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
203 if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
205 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
210 if (x->IPAddr.find('/') != std::string::npos)
213 if (stat(x->IPAddr.c_str(), &sb) == -1 || !S_ISSOCK(sb.st_mode))
217 if (x->IPAddr.find(':') != std::string::npos)
220 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
226 if (inet_pton(AF_INET, x->IPAddr.c_str(),&n) < 1)
230 /* Do we already have an IP? If so, no need to resolve it. */
233 // Create a TreeServer object that will start connecting immediately in the background
234 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
235 if (newsocket->GetFd() > -1)
237 /* Handled automatically on success */
241 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
242 x->Name.c_str(), newsocket->getError().c_str());
243 ServerInstance->GlobalCulls.AddItem(newsocket);
248 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());
252 // Guess start_type from bindip aftype
253 DNS::QueryType start_type = DNS::QUERY_AAAA;
254 irc::sockets::sockaddrs bind;
255 if ((!x->Bind.empty()) && (irc::sockets::aptosa(x->Bind, 0, bind)))
257 if (bind.family() == AF_INET)
258 start_type = DNS::QUERY_A;
261 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
266 catch (DNS::Exception& e)
269 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
270 ConnectServer(y, false);
275 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
277 for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
280 if (curtime >= x->NextConnectTime)
282 x->NextConnectTime = curtime + x->Period;
283 ConnectServer(x, true);
288 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
290 SpanningTreeUtilities::TimeoutList::iterator i = Utils->timeoutlist.begin();
291 while (i != Utils->timeoutlist.end())
293 TreeSocket* s = i->first;
294 std::pair<std::string, unsigned int> p = i->second;
295 SpanningTreeUtilities::TimeoutList::iterator me = i;
297 if (s->GetLinkState() == DYING)
299 Utils->timeoutlist.erase(me);
302 else if (curtime > s->age + p.second)
304 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %u seconds)",p.first.c_str(),p.second);
305 Utils->timeoutlist.erase(me);
311 ModResult ModuleSpanningTree::HandleVersion(const CommandBase::Params& parameters, User* user)
313 // We've already confirmed that !parameters.empty(), so this is safe
314 TreeServer* found = Utils->FindServerMask(parameters[0]);
317 if (found == Utils->TreeRoot)
319 // Pass to default VERSION handler.
320 return MOD_RES_PASSTHRU;
323 // If an oper wants to see the version then show the full version string instead of the normal,
324 // but only if it is non-empty.
325 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
326 // or the server is a 2.0 server and does not send a full version.
327 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
329 Numeric::Numeric numeric(RPL_VERSION);
330 irc::tokenstream tokens(showfull ? found->GetFullVersion() : found->GetVersion());
331 for (std::string token; tokens.GetTrailing(token); )
333 user->WriteNumeric(numeric);
337 user->WriteNumeric(ERR_NOSUCHSERVER, parameters[0], "No such server");
342 ModResult ModuleSpanningTree::HandleConnect(const CommandBase::Params& parameters, User* user)
344 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
347 if (InspIRCd::Match(x->Name, parameters[0], ascii_case_insensitive_map))
349 if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
351 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 is ME, not connecting.", x->Name.c_str()));
355 TreeServer* CheckDupe = Utils->FindServer(x->Name);
358 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));
364 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()));
369 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: No server matching \002%s\002 could be found in the config file.", parameters[0].c_str()));
373 void ModuleSpanningTree::OnUserInvite(User* source, User* dest, Channel* channel, time_t expiry, unsigned int notifyrank, CUList& notifyexcepts)
375 if (IS_LOCAL(source))
377 CmdBuilder params(source, "INVITE");
378 params.push_back(dest->uuid);
379 params.push_back(channel->name);
380 params.push_int(channel->age);
381 params.push_back(ConvToStr(expiry));
386 ModResult ModuleSpanningTree::OnPreTopicChange(User* user, Channel* chan, const std::string& topic)
388 // XXX: Deny topic changes if the current topic set time is the current time or is in the future because
389 // other servers will drop our FTOPIC. This restriction will be removed when the protocol is updated.
390 if ((chan->topicset >= ServerInstance->Time()) && (Utils->serverlist.size() > 1))
392 user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, "Retry topic change later");
395 return MOD_RES_PASSTHRU;
398 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
400 // Drop remote events on the floor.
404 CommandFTopic::Builder(user, chan).Broadcast();
407 void ModuleSpanningTree::OnUserPostMessage(User* user, const MessageTarget& target, const MessageDetails& details)
412 const char* message_type = (details.type == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
413 if (target.type == MessageTarget::TYPE_USER)
415 User* d = target.Get<User>();
418 CmdBuilder params(user, message_type);
419 params.push_tags(details.tags_out);
420 params.push_back(d->uuid);
421 params.push_last(details.text);
425 else if (target.type == MessageTarget::TYPE_CHANNEL)
427 Utils->SendChannelMessage(user->uuid, target.Get<Channel>(), details.text, target.status, details.tags_out, details.exemptions, message_type);
429 else if (target.type == MessageTarget::TYPE_SERVER)
431 const std::string* serverglob = target.Get<std::string>();
432 CmdBuilder par(user, message_type);
433 par.push_tags(details.tags_out);
434 par.push_back(*serverglob);
435 par.push_last(details.text);
440 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
442 AutoConnectServers(curtime);
443 DoConnectTimeout(curtime);
446 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
451 // Create the lazy ssl_cert metadata for this user if not already created.
453 sslapi->GetCertificate(user);
455 CommandUID::Builder(user).Broadcast();
458 CommandOpertype::Builder(user).Broadcast();
460 for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
462 ExtensionItem* item = i->first;
463 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
465 ServerInstance->PI->SendMetaData(user, item->name, value);
468 Utils->TreeRoot->UserCount++;
471 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
473 // Only do this for local users
474 if (!IS_LOCAL(memb->user))
477 // Assign the current membership id to the new Membership and increase it
478 memb->id = currmembid++;
480 if (created_by_local)
482 CommandFJoin::Builder params(memb->chan);
489 CmdBuilder params(memb->user, "IJOIN");
490 params.push_back(memb->chan->name);
491 params.push_int(memb->id);
492 if (!memb->modes.empty())
494 params.push_back(ConvToStr(memb->chan->age));
495 params.push_back(memb->modes);
501 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
503 if (user->registered != REG_ALL || !IS_LOCAL(user))
506 CmdBuilder(user, "FHOST").push(newhost).Broadcast();
509 void ModuleSpanningTree::OnChangeRealName(User* user, const std::string& real)
511 if (user->registered != REG_ALL || !IS_LOCAL(user))
514 CmdBuilder(user, "FNAME").push_last(real).Broadcast();
517 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
519 if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
522 CmdBuilder(user, "FIDENT").push(ident).Broadcast();
525 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
527 if (IS_LOCAL(memb->user))
529 CmdBuilder params(memb->user, "PART");
530 params.push_back(memb->chan->name);
531 if (!partmessage.empty())
532 params.push_last(partmessage);
537 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
541 if (oper_message != reason)
542 ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
544 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
548 // Hide the message if one of the following is true:
549 // - User is being quit due to a netsplit and quietbursts is on
550 // - Server is a silent uline
551 TreeServer* server = TreeServer::Get(user);
552 bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine()));
555 ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
556 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
560 // Regardless, update the UserCount
561 TreeServer::Get(user)->UserCount--;
564 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
568 // The nick TS is updated by the core, we don't do it
569 CmdBuilder params(user, "NICK");
570 params.push_back(user->nick);
571 params.push_back(ConvToStr(user->age));
576 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);
580 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
582 if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
585 CmdBuilder params(source, "KICK");
586 params.push_back(memb->chan->name);
587 params.push_back(memb->user->uuid);
588 // If a remote user is being kicked by us then send the membership id in the kick too
589 if (!IS_LOCAL(memb->user))
590 params.push_int(memb->id);
591 params.push_last(reason);
595 void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter)
597 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
599 // Send out to other servers
600 if (!parameter.empty() && parameter[0] != '-')
602 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
603 params.push_back(parameter);
604 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
608 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
610 // Did this rehash change the description of this server?
611 const std::string& newdesc = ServerInstance->Config->ServerDesc;
612 if (newdesc != Utils->TreeRoot->GetDesc())
614 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
615 // string that is sent in the SERVER message initially and shown for example in WHOIS.
616 // We don't need to update the field itself in the Server object - the core does that.
617 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
620 // Re-read config stuff
623 Utils->ReadConfiguration();
625 catch (ModuleException& e)
627 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
628 Utils->RefreshIPCache();
629 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
630 std::string msg = "Error in configuration: ";
631 msg.append(e.GetReason());
632 ServerInstance->SNO->WriteToSnoMask('l', msg);
633 if (status.srcuser && !IS_LOCAL(status.srcuser))
634 ServerInstance->PI->SendSNONotice('L', msg);
638 void ModuleSpanningTree::OnLoadModule(Module* mod)
642 data.append(mod->ModuleSourceFile);
643 Version v = mod->GetVersion();
644 if (!v.link_data.empty())
647 data.append(v.link_data);
649 ServerInstance->PI->SendMetaData("modules", data);
652 void ModuleSpanningTree::OnUnloadModule(Module* mod)
656 ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
660 // We are being unloaded, inform modules about all servers splitting which cannot be done later when the servers are actually disconnected
661 const server_hash& servers = Utils->serverlist;
662 for (server_hash::const_iterator i = servers.begin(); i != servers.end(); ++i)
664 TreeServer* server = i->second;
665 if (!server->IsRoot())
666 FOREACH_MOD_CUSTOM(GetEventProvider(), ServerEventListener, OnServerSplit, (server));
671 // Some other module is being unloaded. If it provides an IOHook we use, we must close that server connection now.
674 // Close all connections which use an IO hook provided by this module
675 const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
676 for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
678 TreeSocket* sock = (*i)->GetSocket();
679 if (sock->GetModHook(mod))
681 sock->SendError("SSL module unloaded");
683 // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close()
688 for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
690 TreeSocket* sock = i->first;
691 if (sock->GetModHook(mod))
696 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
698 if (user->registered != REG_ALL || !IS_LOCAL(user))
701 // Note: The protocol does not allow direct umode +o;
702 // sending OPERTYPE infers +o modechange locally.
703 CommandOpertype::Builder(user).Broadcast();
706 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
708 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
712 user = ServerInstance->FakeClient;
714 CommandAddLine::Builder(x, user).Broadcast();
717 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
719 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
723 user = ServerInstance->FakeClient;
725 CmdBuilder params(user, "DELLINE");
726 params.push_back(x->type);
727 params.push_back(x->Displayable());
731 void ModuleSpanningTree::OnUserAway(User* user)
734 CommandAway::Builder(user).Broadcast();
737 void ModuleSpanningTree::OnUserBack(User* user)
740 CommandAway::Builder(user).Broadcast();
743 void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags)
745 if (processflags & ModeParser::MODE_LOCALONLY)
750 if (u->registered != REG_ALL)
753 CmdBuilder params(source, "MODE");
754 params.push(u->uuid);
755 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
756 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
761 CmdBuilder params(source, "FMODE");
762 params.push(c->name);
763 params.push_int(c->age);
764 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
765 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
770 CullResult ModuleSpanningTree::cull()
774 return this->Module::cull();
777 ModuleSpanningTree::~ModuleSpanningTree()
779 ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
781 Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
782 SetLocalUsersServer(newsrv);
787 Version ModuleSpanningTree::GetVersion()
789 return Version("Allows servers to be linked", VF_VENDOR);
792 /* It is IMPORTANT that m_spanningtree is the last module in the chain
793 * so that any activity it sees is FINAL, e.g. we arent going to send out
794 * a NICK message before m_cloaking has finished putting the +x on the user,
796 * Therefore, we set our priority to PRIORITY_LAST to make sure we end up at the END of
797 * the module call queue.
799 void ModuleSpanningTree::Prioritize()
801 ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
802 ServerInstance->Modules.SetPriority(this, I_OnPreTopicChange, PRIORITY_FIRST);
805 MODULE_INIT(ModuleSpanningTree)