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")
45 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
46 : svsjoin(module), svspart(module), svsnick(module), metadata(module),
47 uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
48 fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
49 away(module), addline(module), delline(module), encap(module), idle(module),
50 nick(module), ping(module), pong(module), push(module), save(module),
51 server(module), squit(module), snonotice(module), version(module),
52 burst(module), endburst(module)
58 void SetLocalUsersServer(Server* newserver)
60 ServerInstance->FakeClient->server = newserver;
61 const LocalUserList& list = ServerInstance->Users->local_users;
62 for (LocalUserList::const_iterator i = list.begin(); i != list.end(); ++i)
63 (*i)->server = newserver;
67 void ModuleSpanningTree::init()
69 ServerInstance->SNO->EnableSnomask('l', "LINK");
71 Utils = new SpanningTreeUtilities(this);
72 Utils->TreeRoot = new TreeServer;
73 commands = new SpanningTreeCommands(this);
75 delete ServerInstance->PI;
76 ServerInstance->PI = new SpanningTreeProtocolInterface;
78 delete ServerInstance->FakeClient->server;
79 SetLocalUsersServer(Utils->TreeRoot);
82 SplitInProgress = false;
84 // update our local user count
85 Utils->TreeRoot->UserCount = ServerInstance->Users->local_users.size();
88 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
90 std::string Parent = Utils->TreeRoot->GetName();
91 if (Current->GetParent())
93 Parent = Current->GetParent()->GetName();
96 const TreeServer::ChildServers& children = Current->GetChildren();
97 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
99 TreeServer* server = *i;
100 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
104 ShowLinks(server, user, hops+1);
109 ShowLinks(server, user, hops+1);
112 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
113 if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
115 /* Or if the server is hidden and they're not an oper */
116 else if ((Current->Hidden) && (!user->IsOper()))
119 user->WriteNumeric(RPL_LINKS, "%s %s :%d %s", Current->GetName().c_str(),
120 (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(),
121 (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops,
122 Current->GetDesc().c_str());
125 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
127 ShowLinks(Utils->TreeRoot,user,0);
128 user->WriteNumeric(RPL_ENDOFLINKS, "* :End of /LINKS list.");
131 std::string ModuleSpanningTree::TimeToStr(time_t secs)
133 time_t mins_up = secs / 60;
134 time_t hours_up = mins_up / 60;
135 time_t days_up = hours_up / 24;
137 mins_up = mins_up % 60;
138 hours_up = hours_up % 24;
139 return ((days_up ? (ConvToStr(days_up) + "d") : "")
140 + (hours_up ? (ConvToStr(hours_up) + "h") : "")
141 + (mins_up ? (ConvToStr(mins_up) + "m") : "")
142 + ConvToStr(secs) + "s");
145 void ModuleSpanningTree::DoPingChecks(time_t curtime)
148 * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
149 * This prevents lost REMOTECONNECT notices
151 long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
154 for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
156 TreeServer *s = i->second;
162 if (s->GetSocket()->GetLinkState() == DYING)
164 s->GetSocket()->Close();
168 // Do not ping servers that are not fully connected yet!
169 // Servers which are connected to us have IsLocal() == true and if they're fully connected
170 // then Socket->LinkState == CONNECTED. Servers that are linked to another server are always fully connected.
171 if (s->IsLocal() && s->GetSocket()->GetLinkState() != CONNECTED)
174 // Now do PING checks on all servers
175 // Only ping if this server needs one
176 if (curtime >= s->NextPingTime())
178 // And if they answered the last
179 if (s->AnsweredLastPing())
181 // They did, send a ping to them
182 s->SetNextPingTime(curtime + Utils->PingFreq);
183 s->GetSocket()->WriteLine(":" + ServerInstance->Config->GetSID() + " PING " + s->GetID());
184 s->LastPingMsec = ts;
188 // They didn't answer the last ping, if they are locally connected, get rid of them.
191 TreeSocket* sock = s->GetSocket();
192 sock->SendError("Ping timeout");
199 // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
200 if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
202 /* The server hasnt responded, send a warning to opers */
203 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
209 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
213 for(unsigned int j=0; j < a->servers.size(); j++)
215 if (Utils->FindServer(a->servers[j]))
217 // found something in this block. Should the server fail,
218 // we want to start at the start of the list, not in the
219 // middle where we left off
224 if (on_timer && a->position >= 0)
226 if (!on_timer && a->position < 0)
230 while (a->position < (int)a->servers.size())
232 Link* x = Utils->FindLink(a->servers[a->position]);
235 ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
241 // Autoconnect chain has been fully iterated; start at the beginning on the
242 // next AutoConnectServers run
246 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
250 if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
252 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
256 DNS::QueryType start_type = DNS::QUERY_AAAA;
257 if (strchr(x->IPAddr.c_str(),':'))
260 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
266 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
270 /* Do we already have an IP? If so, no need to resolve it. */
273 /* Gave a hook, but it wasnt one we know */
274 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
275 if (newsocket->GetFd() > -1)
277 /* Handled automatically on success */
281 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
282 x->Name.c_str(), newsocket->getError().c_str());
283 ServerInstance->GlobalCulls.AddItem(newsocket);
288 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());
292 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
297 catch (DNS::Exception& e)
300 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
301 ConnectServer(y, false);
306 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
308 for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
311 if (curtime >= x->NextConnectTime)
313 x->NextConnectTime = curtime + x->Period;
314 ConnectServer(x, true);
319 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
321 std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
322 while (i != Utils->timeoutlist.end())
324 TreeSocket* s = i->first;
325 std::pair<std::string, int> p = i->second;
326 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
328 if (s->GetLinkState() == DYING)
330 Utils->timeoutlist.erase(me);
333 else if (curtime > s->age + p.second)
335 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
336 Utils->timeoutlist.erase(me);
342 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
344 // we've already checked if pcnt > 0, so this is safe
345 TreeServer* found = Utils->FindServerMask(parameters[0]);
348 if (found == Utils->TreeRoot)
350 // Pass to default VERSION handler.
351 return MOD_RES_PASSTHRU;
353 std::string Version = found->GetVersion();
354 user->WriteNumeric(RPL_VERSION, ":%s", Version.c_str());
358 user->WriteNumeric(ERR_NOSUCHSERVER, "%s :No such server", parameters[0].c_str());
363 /* This method will attempt to get a message to a remote user.
365 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
368 VAFORMAT(text, format, format);
371 user->WriteNotice(text);
373 ServerInstance->PI->SendUserNotice(user, text);
376 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
378 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
381 if (InspIRCd::Match(x->Name.c_str(),parameters[0], rfc_case_insensitive_map))
383 if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
385 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
389 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
392 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
398 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());
403 RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
407 void ModuleSpanningTree::On005Numeric(std::map<std::string, std::string>& tokens)
412 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
414 if (IS_LOCAL(source))
416 CmdBuilder params(source, "INVITE");
417 params.push_back(dest->uuid);
418 params.push_back(channel->name);
419 params.push_back(ConvToStr(expiry));
424 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
426 // Drop remote events on the floor.
430 CommandFTopic::Builder(user, chan).Broadcast();
433 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
438 const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
439 if (target_type == TYPE_USER)
441 User* d = (User*) dest;
444 CmdBuilder params(user, message_type);
445 params.push_back(d->uuid);
446 params.push_last(text);
450 else if (target_type == TYPE_CHANNEL)
452 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
454 else if (target_type == TYPE_SERVER)
456 char* target = (char*) dest;
457 CmdBuilder par(user, message_type);
458 par.push_back(target);
464 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
466 AutoConnectServers(curtime);
467 DoPingChecks(curtime);
468 DoConnectTimeout(curtime);
471 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
476 CommandUID::Builder(user).Broadcast();
479 CommandOpertype::Builder(user).Broadcast();
481 for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
483 ExtensionItem* item = i->first;
484 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
486 ServerInstance->PI->SendMetaData(user, item->name, value);
489 Utils->TreeRoot->UserCount++;
492 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
494 // Only do this for local users
495 if (!IS_LOCAL(memb->user))
498 if (created_by_local)
500 CmdBuilder params("FJOIN");
501 params.push_back(memb->chan->name);
502 params.push_back(ConvToStr(memb->chan->age));
503 params.push_raw(" +").push_raw(memb->chan->ChanModes(true));
504 params.push(memb->modes).push_raw(',').push_raw(memb->user->uuid);
509 CmdBuilder params(memb->user, "IJOIN");
510 params.push_back(memb->chan->name);
511 if (!memb->modes.empty())
513 params.push_back(ConvToStr(memb->chan->age));
514 params.push_back(memb->modes);
520 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
522 if (user->registered != REG_ALL || !IS_LOCAL(user))
525 CmdBuilder(user, "FHOST").push(newhost).Broadcast();
528 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
530 if (user->registered != REG_ALL || !IS_LOCAL(user))
533 CmdBuilder(user, "FNAME").push_last(gecos).Broadcast();
536 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
538 if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
541 CmdBuilder(user, "FIDENT").push(ident).Broadcast();
544 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
546 if (IS_LOCAL(memb->user))
548 CmdBuilder params(memb->user, "PART");
549 params.push_back(memb->chan->name);
550 if (!partmessage.empty())
551 params.push_last(partmessage);
556 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
560 if (oper_message != reason)
561 ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
563 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
567 // Hide the message if one of the following is true:
568 // - User is being quit due to a netsplit and quietbursts is on
569 // - Server is a silent uline
570 bool hide = (((this->SplitInProgress) && (Utils->quiet_bursts)) || (user->server->IsSilentULine()));
573 ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
574 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
578 // Regardless, We need to modify the user Counts..
579 TreeServer::Get(user)->UserCount--;
582 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
586 CmdBuilder params(user, "NICK");
587 params.push_back(user->nick);
589 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
591 if ((irc::string(user->nick.c_str()) != assign(oldnick)) && (!this->KeepNickTS))
592 user->age = ServerInstance->Time();
594 params.push_back(ConvToStr(user->age));
596 this->KeepNickTS = false;
598 else if (!loopCall && user->nick == user->uuid)
600 CmdBuilder params("SAVE");
601 params.push_back(user->uuid);
602 params.push_back(ConvToStr(user->age));
607 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
609 if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
612 CmdBuilder params(source, "KICK");
613 params.push_back(memb->chan->name);
614 params.push_back(memb->user->uuid);
615 params.push_last(reason);
619 void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter)
622 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
624 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
626 // Send out to other servers
627 if (!parameter.empty() && parameter[0] != '-')
629 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
630 params.push_back(parameter);
631 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
635 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
637 // Re-read config stuff
640 Utils->ReadConfiguration();
642 catch (ModuleException& e)
644 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
645 Utils->RefreshIPCache();
646 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
647 std::string msg = "Error in configuration: ";
648 msg.append(e.GetReason());
649 ServerInstance->SNO->WriteToSnoMask('l', msg);
650 if (status.srcuser && !IS_LOCAL(status.srcuser))
651 ServerInstance->PI->SendSNONotice('L', msg);
655 void ModuleSpanningTree::OnLoadModule(Module* mod)
659 data.append(mod->ModuleSourceFile);
660 Version v = mod->GetVersion();
661 if (!v.link_data.empty())
664 data.append(v.link_data);
666 ServerInstance->PI->SendMetaData("modules", data);
669 void ModuleSpanningTree::OnUnloadModule(Module* mod)
673 ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
675 // Close all connections which use an IO hook provided by this module
676 const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
677 for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
679 TreeSocket* sock = (*i)->GetSocket();
680 if (sock && sock->GetIOHook() && sock->GetIOHook()->creator == mod)
682 sock->SendError("SSL module unloaded");
687 for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
689 TreeSocket* sock = i->first;
690 if (sock->GetIOHook() && sock->GetIOHook()->creator == mod)
695 // note: the protocol does not allow direct umode +o except
696 // via NICK with 8 params. sending OPERTYPE infers +o modechange
698 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
700 if (user->registered != REG_ALL || !IS_LOCAL(user))
702 CommandOpertype::Builder(user).Broadcast();
705 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
707 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
711 user = ServerInstance->FakeClient;
713 CommandAddLine::Builder(x, user).Broadcast();
716 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
718 if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
722 user = ServerInstance->FakeClient;
724 CmdBuilder params(user, "DELLINE");
725 params.push_back(x->type);
726 params.push_back(x->Displayable());
730 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
733 CommandAway::Builder(user, awaymsg).Broadcast();
735 return MOD_RES_PASSTHRU;
738 CullResult ModuleSpanningTree::cull()
742 return this->Module::cull();
745 ModuleSpanningTree::~ModuleSpanningTree()
747 delete ServerInstance->PI;
748 ServerInstance->PI = new ProtocolInterface;
750 Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
751 SetLocalUsersServer(newsrv);
753 /* This will also free the listeners */
759 Version ModuleSpanningTree::GetVersion()
761 return Version("Allows servers to be linked", VF_VENDOR);
764 /* It is IMPORTANT that m_spanningtree is the last module in the chain
765 * so that any activity it sees is FINAL, e.g. we arent going to send out
766 * a NICK message before m_cloaking has finished putting the +x on the user,
768 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
769 * the module call queue.
771 void ModuleSpanningTree::Prioritize()
773 ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
776 MODULE_INIT(ModuleSpanningTree)