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