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