]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
If a parent server is hidden then also hide its child servers.
[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         , rconnect(this)
43         , rsquit(this)
44         , map(this)
45         , commands(this)
46         , currmembid(0)
47         , eventprov(this, "event/server")
48         , sslapi(this)
49         , DNS(this, "DNS")
50         , tagevprov(this, "event/messagetag")
51         , loopCall(false)
52 {
53 }
54
55 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
56         : svsjoin(module), svspart(module), svsnick(module), metadata(module),
57         uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
58         fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
59         away(module), addline(module), delline(module), encap(module), idle(module),
60         nick(module), ping(module), pong(module), save(module),
61         server(module), squit(module), snonotice(module),
62         endburst(module), sinfo(module), num(module)
63 {
64 }
65
66 namespace
67 {
68         void SetLocalUsersServer(Server* newserver)
69         {
70                 // Does not change the server of quitting users because those are not in the list
71
72                 ServerInstance->FakeClient->server = newserver;
73                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
74                 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
75                         (*i)->server = newserver;
76         }
77
78         void ResetMembershipIds()
79         {
80                 // Set all membership ids to 0
81                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
82                 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
83                 {
84                         LocalUser* user = *i;
85                         for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
86                                 (*j)->id = 0;
87                 }
88         }
89 }
90
91 void ModuleSpanningTree::init()
92 {
93         ServerInstance->SNO->EnableSnomask('l', "LINK");
94
95         ResetMembershipIds();
96
97         Utils = new SpanningTreeUtilities(this);
98         Utils->TreeRoot = new TreeServer;
99
100         ServerInstance->PI = &protocolinterface;
101
102         delete ServerInstance->FakeClient->server;
103         SetLocalUsersServer(Utils->TreeRoot);
104 }
105
106 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
107 {
108         std::string Parent = Utils->TreeRoot->GetName();
109         if (Current->GetParent())
110         {
111                 Parent = Current->GetParent()->GetName();
112         }
113
114         const TreeServer::ChildServers& children = Current->GetChildren();
115         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
116         {
117                 TreeServer* server = *i;
118                 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
119                 {
120                         if (user->IsOper())
121                         {
122                                  ShowLinks(server, user, hops+1);
123                         }
124                 }
125                 else
126                 {
127                         ShowLinks(server, user, hops+1);
128                 }
129         }
130         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
131         if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
132                 return;
133         /* Or if the server is hidden and they're not an oper */
134         else if ((Current->Hidden) && (!user->IsOper()))
135                 return;
136
137         user->WriteNumeric(RPL_LINKS, Current->GetName(),
138                         (((Utils->FlatLinks) && (!user->IsOper())) ? ServerInstance->Config->ServerName : Parent),
139                         InspIRCd::Format("%d %s", (((Utils->FlatLinks) && (!user->IsOper())) ? 0 : hops), Current->GetDesc().c_str()));
140 }
141
142 void ModuleSpanningTree::HandleLinks(const CommandBase::Params& parameters, User* user)
143 {
144         ShowLinks(Utils->TreeRoot,user,0);
145         user->WriteNumeric(RPL_ENDOFLINKS, '*', "End of /LINKS list.");
146 }
147
148 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
149 {
150         if (!a)
151                 return;
152         for(unsigned int j=0; j < a->servers.size(); j++)
153         {
154                 if (Utils->FindServer(a->servers[j]))
155                 {
156                         // found something in this block. Should the server fail,
157                         // we want to start at the start of the list, not in the
158                         // middle where we left off
159                         a->position = -1;
160                         return;
161                 }
162         }
163         if (on_timer && a->position >= 0)
164                 return;
165         if (!on_timer && a->position < 0)
166                 return;
167
168         a->position++;
169         while (a->position < (int)a->servers.size())
170         {
171                 Link* x = Utils->FindLink(a->servers[a->position]);
172                 if (x)
173                 {
174                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
175                         ConnectServer(x, a);
176                         return;
177                 }
178                 a->position++;
179         }
180         // Autoconnect chain has been fully iterated; start at the beginning on the
181         // next AutoConnectServers run
182         a->position = -1;
183 }
184
185 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
186 {
187         if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
188         {
189                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
190                 return;
191         }
192
193         irc::sockets::sockaddrs sa;
194 #ifndef _WIN32
195         if (x->IPAddr.find('/') != std::string::npos)
196         {
197                 struct stat sb;
198                 if (stat(x->IPAddr.c_str(), &sb) == -1 || !S_ISSOCK(sb.st_mode) || !irc::sockets::untosa(x->IPAddr, sa))
199                 {
200                         // We don't use the family() != AF_UNSPEC check below for UNIX sockets as
201                         // that results in a DNS lookup.
202                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s is not a UNIX socket!",
203                                 x->Name.c_str(), x->IPAddr.c_str());
204                         return;
205                 }
206         }
207         else
208 #endif
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         if (target.type == 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         }
409         else if (target.type == MessageTarget::TYPE_CHANNEL)
410         {
411                 Utils->SendChannelMessage(user->uuid, target.Get<Channel>(), details.text, target.status, details.tags_out, details.exemptions, message_type);
412         }
413         else if (target.type == MessageTarget::TYPE_SERVER)
414         {
415                 const std::string* serverglob = target.Get<std::string>();
416                 CmdBuilder par(user, message_type);
417                 par.push_tags(details.tags_out);
418                 par.push_back(*serverglob);
419                 par.push_last(details.text);
420                 par.Broadcast();
421         }
422 }
423
424 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
425 {
426         AutoConnectServers(curtime);
427         DoConnectTimeout(curtime);
428 }
429
430 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
431 {
432         if (user->quitting)
433                 return;
434
435         // Create the lazy ssl_cert metadata for this user if not already created.
436         if (sslapi)
437                 sslapi->GetCertificate(user);
438
439         CommandUID::Builder(user).Broadcast();
440
441         if (user->IsOper())
442                 CommandOpertype::Builder(user).Broadcast();
443
444         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
445         {
446                 ExtensionItem* item = i->first;
447                 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
448                 if (!value.empty())
449                         ServerInstance->PI->SendMetaData(user, item->name, value);
450         }
451
452         Utils->TreeRoot->UserCount++;
453 }
454
455 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
456 {
457         // Only do this for local users
458         if (!IS_LOCAL(memb->user))
459                 return;
460
461         // Assign the current membership id to the new Membership and increase it
462         memb->id = currmembid++;
463
464         if (created_by_local)
465         {
466                 CommandFJoin::Builder params(memb->chan);
467                 params.add(memb);
468                 params.finalize();
469                 params.Broadcast();
470         }
471         else
472         {
473                 CmdBuilder params(memb->user, "IJOIN");
474                 params.push_back(memb->chan->name);
475                 params.push_int(memb->id);
476                 if (!memb->modes.empty())
477                 {
478                         params.push_back(ConvToStr(memb->chan->age));
479                         params.push_back(memb->modes);
480                 }
481                 params.Broadcast();
482         }
483 }
484
485 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
486 {
487         if (user->registered != REG_ALL || !IS_LOCAL(user))
488                 return;
489
490         CmdBuilder(user, "FHOST").push(newhost).Broadcast();
491 }
492
493 void ModuleSpanningTree::OnChangeRealName(User* user, const std::string& real)
494 {
495         if (user->registered != REG_ALL || !IS_LOCAL(user))
496                 return;
497
498         CmdBuilder(user, "FNAME").push_last(real).Broadcast();
499 }
500
501 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
502 {
503         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
504                 return;
505
506         CmdBuilder(user, "FIDENT").push(ident).Broadcast();
507 }
508
509 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
510 {
511         if (IS_LOCAL(memb->user))
512         {
513                 CmdBuilder params(memb->user, "PART");
514                 params.push_back(memb->chan->name);
515                 if (!partmessage.empty())
516                         params.push_last(partmessage);
517                 params.Broadcast();
518         }
519 }
520
521 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
522 {
523         if (IS_LOCAL(user))
524         {
525                 if (oper_message != reason)
526                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
527
528                 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
529         }
530         else
531         {
532                 // Hide the message if one of the following is true:
533                 // - User is being quit due to a netsplit and quietbursts is on
534                 // - Server is a silent uline
535                 TreeServer* server = TreeServer::Get(user);
536                 bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine()));
537                 if (!hide)
538                 {
539                         ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
540                                 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
541                 }
542         }
543
544         // Regardless, update the UserCount
545         TreeServer::Get(user)->UserCount--;
546 }
547
548 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
549 {
550         if (IS_LOCAL(user))
551         {
552                 // The nick TS is updated by the core, we don't do it
553                 CmdBuilder params(user, "NICK");
554                 params.push_back(user->nick);
555                 params.push_back(ConvToStr(user->age));
556                 params.Broadcast();
557         }
558         else if (!loopCall)
559         {
560                 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);
561         }
562 }
563
564 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
565 {
566         if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
567                 return;
568
569         CmdBuilder params(source, "KICK");
570         params.push_back(memb->chan->name);
571         params.push_back(memb->user->uuid);
572         // If a remote user is being kicked by us then send the membership id in the kick too
573         if (!IS_LOCAL(memb->user))
574                 params.push_int(memb->id);
575         params.push_last(reason);
576         params.Broadcast();
577 }
578
579 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
580 {
581         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
582
583         // Send out to other servers
584         if (!parameter.empty() && parameter[0] != '-')
585         {
586                 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
587                 params.push_back(parameter);
588                 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
589         }
590 }
591
592 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
593 {
594         // Did this rehash change the description of this server?
595         const std::string& newdesc = ServerInstance->Config->ServerDesc;
596         if (newdesc != Utils->TreeRoot->GetDesc())
597         {
598                 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
599                 // string that is sent in the SERVER message initially and shown for example in WHOIS.
600                 // We don't need to update the field itself in the Server object - the core does that.
601                 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
602         }
603
604         // Re-read config stuff
605         try
606         {
607                 Utils->ReadConfiguration();
608         }
609         catch (ModuleException& e)
610         {
611                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
612                 Utils->RefreshIPCache();
613                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
614                 std::string msg = "Error in configuration: ";
615                 msg.append(e.GetReason());
616                 ServerInstance->SNO->WriteToSnoMask('l', msg);
617                 if (status.srcuser && !IS_LOCAL(status.srcuser))
618                         ServerInstance->PI->SendSNONotice('L', msg);
619         }
620 }
621
622 void ModuleSpanningTree::OnLoadModule(Module* mod)
623 {
624         std::string data;
625         data.push_back('+');
626         data.append(mod->ModuleSourceFile);
627         Version v = mod->GetVersion();
628         if (!v.link_data.empty())
629         {
630                 data.push_back('=');
631                 data.append(v.link_data);
632         }
633         ServerInstance->PI->SendMetaData("modules", data);
634 }
635
636 void ModuleSpanningTree::OnUnloadModule(Module* mod)
637 {
638         if (!Utils)
639                 return;
640         ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
641
642         if (mod == this)
643         {
644                 // We are being unloaded, inform modules about all servers splitting which cannot be done later when the servers are actually disconnected
645                 const server_hash& servers = Utils->serverlist;
646                 for (server_hash::const_iterator i = servers.begin(); i != servers.end(); ++i)
647                 {
648                         TreeServer* server = i->second;
649                         if (!server->IsRoot())
650                                 FOREACH_MOD_CUSTOM(GetEventProvider(), ServerEventListener, OnServerSplit, (server));
651                 }
652                 return;
653         }
654
655         // Some other module is being unloaded. If it provides an IOHook we use, we must close that server connection now.
656
657 restart:
658         // Close all connections which use an IO hook provided by this module
659         const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
660         for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
661         {
662                 TreeSocket* sock = (*i)->GetSocket();
663                 if (sock->GetModHook(mod))
664                 {
665                         sock->SendError("SSL module unloaded");
666                         sock->Close();
667                         // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close()
668                         goto restart;
669                 }
670         }
671
672         for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
673         {
674                 TreeSocket* sock = i->first;
675                 if (sock->GetModHook(mod))
676                         sock->Close();
677         }
678 }
679
680 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
681 {
682         if (user->registered != REG_ALL || !IS_LOCAL(user))
683                 return;
684
685         // Note: The protocol does not allow direct umode +o;
686         // sending OPERTYPE infers +o modechange locally.
687         CommandOpertype::Builder(user).Broadcast();
688 }
689
690 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
691 {
692         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
693                 return;
694
695         if (!user)
696                 user = ServerInstance->FakeClient;
697
698         CommandAddLine::Builder(x, user).Broadcast();
699 }
700
701 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
702 {
703         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
704                 return;
705
706         if (!user)
707                 user = ServerInstance->FakeClient;
708
709         CmdBuilder params(user, "DELLINE");
710         params.push_back(x->type);
711         params.push_back(x->Displayable());
712         params.Broadcast();
713 }
714
715 void ModuleSpanningTree::OnUserAway(User* user)
716 {
717         if (IS_LOCAL(user))
718                 CommandAway::Builder(user).Broadcast();
719 }
720
721 void ModuleSpanningTree::OnUserBack(User* user)
722 {
723         if (IS_LOCAL(user))
724                 CommandAway::Builder(user).Broadcast();
725 }
726
727 void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags)
728 {
729         if (processflags & ModeParser::MODE_LOCALONLY)
730                 return;
731
732         if (u)
733         {
734                 if (u->registered != REG_ALL)
735                         return;
736
737                 CmdBuilder params(source, "MODE");
738                 params.push(u->uuid);
739                 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
740                 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
741                 params.Broadcast();
742         }
743         else
744         {
745                 CmdBuilder params(source, "FMODE");
746                 params.push(c->name);
747                 params.push_int(c->age);
748                 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
749                 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
750                 params.Broadcast();
751         }
752 }
753
754 CullResult ModuleSpanningTree::cull()
755 {
756         if (Utils)
757                 Utils->cull();
758         return this->Module::cull();
759 }
760
761 ModuleSpanningTree::~ModuleSpanningTree()
762 {
763         ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
764
765         Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
766         SetLocalUsersServer(newsrv);
767
768         delete Utils;
769 }
770
771 Version ModuleSpanningTree::GetVersion()
772 {
773         return Version("Allows servers to be linked", VF_VENDOR);
774 }
775
776 /* It is IMPORTANT that m_spanningtree is the last module in the chain
777  * so that any activity it sees is FINAL, e.g. we arent going to send out
778  * a NICK message before m_cloaking has finished putting the +x on the user,
779  * etc etc.
780  * Therefore, we set our priority to PRIORITY_LAST to make sure we end up at the END of
781  * the module call queue.
782  */
783 void ModuleSpanningTree::Prioritize()
784 {
785         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
786         ServerInstance->Modules.SetPriority(this, I_OnPreTopicChange, PRIORITY_FIRST);
787 }
788
789 MODULE_INIT(ModuleSpanningTree)