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