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