]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
1aab60edaac41b9e2bfdb6a4e4a744c9e4abc6ab
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / main.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5  *   Copyright (C) 2013, 2017-2020 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2013, 2016 Adam <Adam@anope.org>
7  *   Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
10  *   Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
11  *   Copyright (C) 2007-2009 Dennis Friis <peavey@inspircd.org>
12  *   Copyright (C) 2005, 2007-2010 Craig Edwards <brain@inspircd.org>
13  *
14  * This file is part of InspIRCd.  InspIRCd is free software: you can
15  * redistribute it and/or modify it under the terms of the GNU General Public
16  * License as published by the Free Software Foundation, version 2.
17  *
18  * This program is distributed in the hope that it will be useful, but WITHOUT
19  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  */
26
27
28 #include "inspircd.h"
29 #include "socket.h"
30 #include "xline.h"
31 #include "iohook.h"
32
33 #include "resolvers.h"
34 #include "main.h"
35 #include "utils.h"
36 #include "treeserver.h"
37 #include "link.h"
38 #include "treesocket.h"
39 #include "commands.h"
40 #include "translate.h"
41
42 ModuleSpanningTree::ModuleSpanningTree()
43         : Away::EventListener(this)
44         , Stats::EventListener(this)
45         , CTCTags::EventListener(this)
46         , rconnect(this)
47         , rsquit(this)
48         , map(this)
49         , commands(this)
50         , currmembid(0)
51         , broadcasteventprov(this, "event/server-broadcast")
52         , linkeventprov(this, "event/server-link")
53         , messageeventprov(this, "event/server-message")
54         , synceventprov(this, "event/server-sync")
55         , sslapi(this)
56         , servicetag(this)
57         , DNS(this, "DNS")
58         , tagevprov(this)
59         , loopCall(false)
60 {
61 }
62
63 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
64         : svsjoin(module), svspart(module), svsnick(module), metadata(module),
65         uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
66         fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
67         away(module), addline(module), delline(module), encap(module), idle(module),
68         nick(module), ping(module), pong(module), save(module),
69         server(module), squit(module), snonotice(module),
70         endburst(module), sinfo(module), num(module)
71 {
72 }
73
74 namespace
75 {
76         void SetLocalUsersServer(Server* newserver)
77         {
78                 // Does not change the server of quitting users because those are not in the list
79
80                 ServerInstance->FakeClient->server = newserver;
81                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
82                 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
83                         (*i)->server = newserver;
84         }
85
86         void ResetMembershipIds()
87         {
88                 // Set all membership ids to 0
89                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
90                 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
91                 {
92                         LocalUser* user = *i;
93                         for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
94                                 (*j)->id = 0;
95                 }
96         }
97 }
98
99 void ModuleSpanningTree::init()
100 {
101         ServerInstance->SNO->EnableSnomask('l', "LINK");
102
103         ResetMembershipIds();
104
105         Utils = new SpanningTreeUtilities(this);
106         Utils->TreeRoot = new TreeServer;
107
108         ServerInstance->PI = &protocolinterface;
109
110         delete ServerInstance->FakeClient->server;
111         SetLocalUsersServer(Utils->TreeRoot);
112 }
113
114 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
115 {
116         std::string Parent = Utils->TreeRoot->GetName();
117         if (Current->GetParent())
118         {
119                 Parent = Current->GetParent()->GetName();
120         }
121
122         const TreeServer::ChildServers& children = Current->GetChildren();
123         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
124         {
125                 TreeServer* server = *i;
126                 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
127                 {
128                         if (user->IsOper())
129                         {
130                                  ShowLinks(server, user, hops+1);
131                         }
132                 }
133                 else
134                 {
135                         ShowLinks(server, user, hops+1);
136                 }
137         }
138         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
139         if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
140                 return;
141         /* Or if the server is hidden and they're not an oper */
142         else if ((Current->Hidden) && (!user->IsOper()))
143                 return;
144
145         user->WriteNumeric(RPL_LINKS, Current->GetName(),
146                         (((Utils->FlatLinks) && (!user->IsOper())) ? ServerInstance->Config->ServerName : Parent),
147                         InspIRCd::Format("%d %s", (((Utils->FlatLinks) && (!user->IsOper())) ? 0 : hops), Current->GetDesc().c_str()));
148 }
149
150 void ModuleSpanningTree::HandleLinks(const CommandBase::Params& parameters, User* user)
151 {
152         ShowLinks(Utils->TreeRoot,user,0);
153         user->WriteNumeric(RPL_ENDOFLINKS, '*', "End of /LINKS list.");
154 }
155
156 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
157 {
158         if (!a)
159                 return;
160         for(unsigned int j=0; j < a->servers.size(); j++)
161         {
162                 if (Utils->FindServer(a->servers[j]))
163                 {
164                         // found something in this block. Should the server fail,
165                         // we want to start at the start of the list, not in the
166                         // middle where we left off
167                         a->position = -1;
168                         return;
169                 }
170         }
171         if (on_timer && a->position >= 0)
172                 return;
173         if (!on_timer && a->position < 0)
174                 return;
175
176         a->position++;
177         while (a->position < (int)a->servers.size())
178         {
179                 Link* x = Utils->FindLink(a->servers[a->position]);
180                 if (x)
181                 {
182                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
183                         ConnectServer(x, a);
184                         return;
185                 }
186                 a->position++;
187         }
188         // Autoconnect chain has been fully iterated; start at the beginning on the
189         // next AutoConnectServers run
190         a->position = -1;
191 }
192
193 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
194 {
195         if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
196         {
197                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
198                 return;
199         }
200
201         irc::sockets::sockaddrs sa;
202         if (x->IPAddr.find('/') != std::string::npos)
203         {
204                 if (!irc::sockets::isunix(x->IPAddr) || !irc::sockets::untosa(x->IPAddr, sa))
205                 {
206                         // We don't use the family() != AF_UNSPEC check below for UNIX sockets as
207                         // that results in a DNS lookup.
208                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s is not a UNIX socket!",
209                                 x->Name.c_str(), x->IPAddr.c_str());
210                         return;
211                 }
212         }
213         else
214         {
215                 // If this fails then the IP sa will be AF_UNSPEC.
216                 irc::sockets::aptosa(x->IPAddr, x->Port, sa);
217         }
218         
219         /* Do we already have an IP? If so, no need to resolve it. */
220         if (sa.family() != AF_UNSPEC)
221         {
222                 // Create a TreeServer object that will start connecting immediately in the background
223                 TreeSocket* newsocket = new TreeSocket(x, y, sa);
224                 if (newsocket->GetFd() > -1)
225                 {
226                         /* Handled automatically on success */
227                 }
228                 else
229                 {
230                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
231                                 x->Name.c_str(), newsocket->getError().c_str());
232                         ServerInstance->GlobalCulls.AddItem(newsocket);
233                 }
234         }
235         else if (!DNS)
236         {
237                 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());
238         }
239         else
240         {
241                 // Guess start_type from bindip aftype
242                 DNS::QueryType start_type = DNS::QUERY_AAAA;
243                 irc::sockets::sockaddrs bind;
244                 if ((!x->Bind.empty()) && (irc::sockets::aptosa(x->Bind, 0, bind)))
245                 {
246                         if (bind.family() == AF_INET)
247                                 start_type = DNS::QUERY_A;
248                 }
249
250                 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
251                 try
252                 {
253                         DNS->Process(snr);
254                 }
255                 catch (DNS::Exception& e)
256                 {
257                         delete snr;
258                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
259                         ConnectServer(y, false);
260                 }
261         }
262 }
263
264 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
265 {
266         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
267         {
268                 Autoconnect* x = *i;
269                 if (curtime >= x->NextConnectTime)
270                 {
271                         x->NextConnectTime = curtime + x->Period;
272                         ConnectServer(x, true);
273                 }
274         }
275 }
276
277 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
278 {
279         SpanningTreeUtilities::TimeoutList::iterator i = Utils->timeoutlist.begin();
280         while (i != Utils->timeoutlist.end())
281         {
282                 TreeSocket* s = i->first;
283                 std::pair<std::string, unsigned int> p = i->second;
284                 SpanningTreeUtilities::TimeoutList::iterator me = i;
285                 i++;
286                 if (s->GetLinkState() == DYING)
287                 {
288                         Utils->timeoutlist.erase(me);
289                         s->Close();
290                 }
291                 else if (curtime > s->age + p.second)
292                 {
293                         ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %u seconds)",p.first.c_str(),p.second);
294                         Utils->timeoutlist.erase(me);
295                         s->Close();
296                 }
297         }
298 }
299
300 ModResult ModuleSpanningTree::HandleVersion(const CommandBase::Params& parameters, User* user)
301 {
302         // We've already confirmed that !parameters.empty(), so this is safe
303         TreeServer* found = Utils->FindServerMask(parameters[0]);
304         if (found)
305         {
306                 if (found == Utils->TreeRoot)
307                 {
308                         // Pass to default VERSION handler.
309                         return MOD_RES_PASSTHRU;
310                 }
311
312                 // If an oper wants to see the version then show the full version string instead of the normal,
313                 // but only if it is non-empty.
314                 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
315                 // or the server is a 2.0 server and does not send a full version.
316                 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
317
318                 Numeric::Numeric numeric(RPL_VERSION);
319                 irc::tokenstream tokens(showfull ? found->GetFullVersion() : found->GetVersion());
320                 for (std::string token; tokens.GetTrailing(token); )
321                         numeric.push(token);
322                 user->WriteNumeric(numeric);
323         }
324         else
325         {
326                 user->WriteNumeric(ERR_NOSUCHSERVER, parameters[0], "No such server");
327         }
328         return MOD_RES_DENY;
329 }
330
331 ModResult ModuleSpanningTree::HandleConnect(const CommandBase::Params& parameters, User* user)
332 {
333         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
334         {
335                 Link* x = *i;
336                 if (InspIRCd::Match(x->Name, parameters[0], ascii_case_insensitive_map))
337                 {
338                         if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
339                         {
340                                 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 is ME, not connecting.", x->Name.c_str()));
341                                 return MOD_RES_DENY;
342                         }
343
344                         TreeServer* CheckDupe = Utils->FindServer(x->Name);
345                         if (!CheckDupe)
346                         {
347                                 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));
348                                 ConnectServer(x);
349                                 return MOD_RES_DENY;
350                         }
351                         else
352                         {
353                                 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()));
354                                 return MOD_RES_DENY;
355                         }
356                 }
357         }
358         user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: No server matching \002%s\002 could be found in the config file.", parameters[0].c_str()));
359         return MOD_RES_DENY;
360 }
361
362 void ModuleSpanningTree::OnUserInvite(User* source, User* dest, Channel* channel, time_t expiry, unsigned int notifyrank, CUList& notifyexcepts)
363 {
364         if (IS_LOCAL(source))
365         {
366                 CmdBuilder params(source, "INVITE");
367                 params.push(dest->uuid);
368                 params.push(channel->name);
369                 params.push_int(channel->age);
370                 params.push(ConvToStr(expiry));
371                 params.Broadcast();
372         }
373 }
374
375 ModResult ModuleSpanningTree::OnPreTopicChange(User* user, Channel* chan, const std::string& topic)
376 {
377         // XXX: Deny topic changes if the current topic set time is the current time or is in the future because
378         // other servers will drop our FTOPIC. This restriction will be removed when the protocol is updated.
379         if ((chan->topicset >= ServerInstance->Time()) && (Utils->serverlist.size() > 1))
380         {
381                 user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, "Retry topic change later");
382                 return MOD_RES_DENY;
383         }
384         return MOD_RES_PASSTHRU;
385 }
386
387 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
388 {
389         // Drop remote events on the floor.
390         if (!IS_LOCAL(user))
391                 return;
392
393         CommandFTopic::Builder(user, chan).Broadcast();
394 }
395
396 void ModuleSpanningTree::OnUserPostMessage(User* user, const MessageTarget& target, const MessageDetails& details)
397 {
398         if (!IS_LOCAL(user))
399                 return;
400
401         const char* message_type = (details.type == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
402         switch (target.type)
403         {
404                 case MessageTarget::TYPE_USER:
405                 {
406                         User* d = target.Get<User>();
407                         if (!IS_LOCAL(d))
408                         {
409                                 CmdBuilder params(user, message_type);
410                                 params.push_tags(details.tags_out);
411                                 params.push(d->uuid);
412                                 params.push_last(details.text);
413                                 params.Unicast(d);
414                         }
415                         break;
416                 }
417                 case MessageTarget::TYPE_CHANNEL:
418                 {
419                         Utils->SendChannelMessage(user, target.Get<Channel>(), details.text, target.status, details.tags_out, details.exemptions, message_type);
420                         break;
421                 }
422                 case MessageTarget::TYPE_SERVER:
423                 {
424                         const std::string* serverglob = target.Get<std::string>();
425                         CmdBuilder par(user, message_type);
426                         par.push_tags(details.tags_out);
427                         par.push(*serverglob);
428                         par.push_last(details.text);
429                         par.Broadcast();
430                         break;
431                 }
432         }
433 }
434
435 void ModuleSpanningTree::OnUserPostTagMessage(User* user, const MessageTarget& target, const CTCTags::TagMessageDetails& details)
436 {
437         if (!IS_LOCAL(user))
438                 return;
439
440         switch (target.type)
441         {
442                 case MessageTarget::TYPE_USER:
443                 {
444                         User* d = target.Get<User>();
445                         if (!IS_LOCAL(d))
446                         {
447                                 CmdBuilder params(user, "TAGMSG");
448                                 params.push_tags(details.tags_out);
449                                 params.push(d->uuid);
450                                 params.Unicast(d);
451                         }
452                         break;
453                 }
454                 case MessageTarget::TYPE_CHANNEL:
455                 {
456                         Utils->SendChannelMessage(user, target.Get<Channel>(), "", target.status, details.tags_out, details.exemptions, "TAGMSG");
457                         break;
458                 }
459                 case MessageTarget::TYPE_SERVER:
460                 {
461                         const std::string* serverglob = target.Get<std::string>();
462                         CmdBuilder par(user, "TAGMSG");
463                         par.push_tags(details.tags_out);
464                         par.push(*serverglob);
465                         par.Broadcast();
466                         break;
467                 }
468         }
469 }
470
471 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
472 {
473         AutoConnectServers(curtime);
474         DoConnectTimeout(curtime);
475 }
476
477 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
478 {
479         if (user->quitting)
480                 return;
481
482         // Create the lazy ssl_cert metadata for this user if not already created.
483         if (sslapi)
484                 sslapi->GetCertificate(user);
485
486         CommandUID::Builder(user).Broadcast();
487
488         if (user->IsOper())
489                 CommandOpertype::Builder(user).Broadcast();
490
491         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
492         {
493                 ExtensionItem* item = i->first;
494                 std::string value = item->ToNetwork(user, i->second);
495                 if (!value.empty())
496                         ServerInstance->PI->SendMetaData(user, item->name, value);
497         }
498
499         Utils->TreeRoot->UserCount++;
500 }
501
502 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
503 {
504         // Only do this for local users
505         if (!IS_LOCAL(memb->user))
506                 return;
507
508         // Assign the current membership id to the new Membership and increase it
509         memb->id = currmembid++;
510
511         if (created_by_local)
512         {
513                 CommandFJoin::Builder params(memb->chan);
514                 params.add(memb);
515                 params.finalize();
516                 params.Broadcast();
517         }
518         else
519         {
520                 CmdBuilder params(memb->user, "IJOIN");
521                 params.push(memb->chan->name);
522                 params.push_int(memb->id);
523                 if (!memb->modes.empty())
524                 {
525                         params.push(ConvToStr(memb->chan->age));
526                         params.push(memb->modes);
527                 }
528                 params.Broadcast();
529         }
530 }
531
532 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
533 {
534         if (user->registered != REG_ALL || !IS_LOCAL(user))
535                 return;
536
537         CmdBuilder(user, "FHOST").push(newhost).Broadcast();
538 }
539
540 void ModuleSpanningTree::OnChangeRealName(User* user, const std::string& real)
541 {
542         if (user->registered != REG_ALL || !IS_LOCAL(user))
543                 return;
544
545         CmdBuilder(user, "FNAME").push_last(real).Broadcast();
546 }
547
548 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
549 {
550         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
551                 return;
552
553         CmdBuilder(user, "FIDENT").push(ident).Broadcast();
554 }
555
556 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
557 {
558         if (IS_LOCAL(memb->user))
559         {
560                 CmdBuilder params(memb->user, "PART");
561                 params.push(memb->chan->name);
562                 if (!partmessage.empty())
563                         params.push_last(partmessage);
564                 params.Broadcast();
565         }
566 }
567
568 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
569 {
570         if (IS_LOCAL(user))
571         {
572                 if (oper_message != reason)
573                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
574
575                 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
576         }
577         else
578         {
579                 // Hide the message if one of the following is true:
580                 // - User is being quit due to a netsplit and quietbursts is on
581                 // - Server is a silent uline
582                 TreeServer* server = TreeServer::Get(user);
583                 bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine()));
584                 if (!hide)
585                 {
586                         ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
587                                 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
588                 }
589         }
590
591         // Regardless, update the UserCount
592         TreeServer::Get(user)->UserCount--;
593 }
594
595 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
596 {
597         if (IS_LOCAL(user))
598         {
599                 // The nick TS is updated by the core, we don't do it
600                 CmdBuilder params(user, "NICK");
601                 params.push(user->nick);
602                 params.push(ConvToStr(user->age));
603                 params.Broadcast();
604         }
605         else if (!loopCall)
606         {
607                 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);
608         }
609 }
610
611 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
612 {
613         if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
614                 return;
615
616         CmdBuilder params(source, "KICK");
617         params.push(memb->chan->name);
618         params.push(memb->user->uuid);
619         // If a remote user is being kicked by us then send the membership id in the kick too
620         if (!IS_LOCAL(memb->user))
621                 params.push_int(memb->id);
622         params.push_last(reason);
623         params.Broadcast();
624 }
625
626 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
627 {
628         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
629
630         // Send out to other servers
631         if (!parameter.empty() && parameter[0] != '-')
632         {
633                 CmdBuilder params(user ? user : ServerInstance->FakeClient, "REHASH");
634                 params.push(parameter);
635                 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
636         }
637 }
638
639 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
640 {
641         // Did this rehash change the description of this server?
642         const std::string& newdesc = ServerInstance->Config->ServerDesc;
643         if (newdesc != Utils->TreeRoot->GetDesc())
644         {
645                 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
646                 // string that is sent in the SERVER message initially and shown for example in WHOIS.
647                 // We don't need to update the field itself in the Server object - the core does that.
648                 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
649         }
650
651         // Re-read config stuff
652         try
653         {
654                 Utils->ReadConfiguration();
655         }
656         catch (ModuleException& e)
657         {
658                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
659                 Utils->RefreshIPCache();
660                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
661                 std::string msg = "Error in configuration: ";
662                 msg.append(e.GetReason());
663                 ServerInstance->SNO->WriteToSnoMask('l', msg);
664                 if (status.srcuser && !IS_LOCAL(status.srcuser))
665                         ServerInstance->PI->SendSNONotice('L', msg);
666         }
667 }
668
669 void ModuleSpanningTree::OnLoadModule(Module* mod)
670 {
671         std::string data;
672         data.push_back('+');
673         data.append(mod->ModuleSourceFile);
674         Version v = mod->GetVersion();
675         if (!v.link_data.empty())
676         {
677                 data.push_back('=');
678                 data.append(v.link_data);
679         }
680         ServerInstance->PI->SendMetaData("modules", data);
681 }
682
683 void ModuleSpanningTree::OnUnloadModule(Module* mod)
684 {
685         if (!Utils)
686                 return;
687         ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
688
689         if (mod == this)
690         {
691                 // We are being unloaded, inform modules about all servers splitting which cannot be done later when the servers are actually disconnected
692                 const server_hash& servers = Utils->serverlist;
693                 for (server_hash::const_iterator i = servers.begin(); i != servers.end(); ++i)
694                 {
695                         TreeServer* server = i->second;
696                         if (!server->IsRoot())
697                                 FOREACH_MOD_CUSTOM(GetLinkEventProvider(), ServerProtocol::LinkEventListener, OnServerSplit, (server, false));
698                 }
699                 return;
700         }
701
702         // Some other module is being unloaded. If it provides an IOHook we use, we must close that server connection now.
703
704 restart:
705         // Close all connections which use an IO hook provided by this module
706         const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
707         for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
708         {
709                 TreeSocket* sock = (*i)->GetSocket();
710                 if (sock->GetModHook(mod))
711                 {
712                         sock->SendError("SSL module unloaded");
713                         sock->Close();
714                         // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close()
715                         goto restart;
716                 }
717         }
718
719         for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
720         {
721                 TreeSocket* sock = i->first;
722                 if (sock->GetModHook(mod))
723                         sock->Close();
724         }
725 }
726
727 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
728 {
729         if (user->registered != REG_ALL || !IS_LOCAL(user))
730                 return;
731
732         // Note: The protocol does not allow direct umode +o;
733         // sending OPERTYPE infers +o modechange locally.
734         CommandOpertype::Builder(user).Broadcast();
735 }
736
737 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
738 {
739         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
740                 return;
741
742         if (!user)
743                 user = ServerInstance->FakeClient;
744
745         CommandAddLine::Builder(x, user).Broadcast();
746 }
747
748 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
749 {
750         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
751                 return;
752
753         if (!user)
754                 user = ServerInstance->FakeClient;
755
756         CmdBuilder params(user, "DELLINE");
757         params.push(x->type);
758         params.push(x->Displayable());
759         params.Broadcast();
760 }
761
762 void ModuleSpanningTree::OnUserAway(User* user)
763 {
764         if (IS_LOCAL(user))
765                 CommandAway::Builder(user).Broadcast();
766 }
767
768 void ModuleSpanningTree::OnUserBack(User* user)
769 {
770         if (IS_LOCAL(user))
771                 CommandAway::Builder(user).Broadcast();
772 }
773
774 void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags)
775 {
776         if (processflags & ModeParser::MODE_LOCALONLY)
777                 return;
778
779         if (u)
780         {
781                 if (u->registered != REG_ALL)
782                         return;
783
784                 CmdBuilder params(source, "MODE");
785                 params.push(u->uuid);
786                 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
787                 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
788                 params.Broadcast();
789         }
790         else
791         {
792                 CmdBuilder params(source, "FMODE");
793                 params.push(c->name);
794                 params.push_int(c->age);
795                 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
796                 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
797                 params.Broadcast();
798         }
799 }
800
801 void ModuleSpanningTree::OnShutdown(const std::string& reason)
802 {
803         const TreeServer::ChildServers& children = Utils->TreeRoot->GetChildren();
804         while (!children.empty())
805                 children.front()->SQuit(reason, true);
806 }
807
808 CullResult ModuleSpanningTree::cull()
809 {
810         if (Utils)
811                 Utils->cull();
812         return this->Module::cull();
813 }
814
815 ModuleSpanningTree::~ModuleSpanningTree()
816 {
817         ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
818
819         Server* newsrv = new Server(ServerInstance->Config->GetSID(), ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
820         SetLocalUsersServer(newsrv);
821
822         delete Utils;
823 }
824
825 Version ModuleSpanningTree::GetVersion()
826 {
827         return Version("Allows servers to be linked", VF_VENDOR);
828 }
829
830 /* It is IMPORTANT that m_spanningtree is the last module in the chain
831  * so that any activity it sees is FINAL, e.g. we arent going to send out
832  * a NICK message before m_cloaking has finished putting the +x on the user,
833  * etc etc.
834  * Therefore, we set our priority to PRIORITY_LAST to make sure we end up at the END of
835  * the module call queue.
836  */
837 void ModuleSpanningTree::Prioritize()
838 {
839         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
840         ServerInstance->Modules.SetPriority(this, I_OnPreTopicChange, PRIORITY_FIRST);
841 }
842
843 MODULE_INIT(ModuleSpanningTree)