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